Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76683ffd7b | ||
|
|
7864a492c9 |
No files matched your search
+1
-1
@@ -37,7 +37,7 @@ KANAME_VERSION=
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MAX_CONCURRENT_DOWNLOADS=1
|
||||
# How often the worker checks every model on the Hub (still there? later: newer commits); 0 disables it
|
||||
# How often the worker checks every model on the Hub (still there? newer commit?); 0 disables it
|
||||
UPDATE_CHECK_INTERVAL_HOURS=12
|
||||
# 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk.
|
||||
# 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps.
|
||||
|
||||
@@ -6,6 +6,32 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.6.0] - 2026-10-06
|
||||
|
||||
Delete models (with their files), verify and deep verify, one-click repair, and update checks
|
||||
with a deliberate Update. Database migrations run automatically on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Delete** any model (also failed or incomplete ones), with confirmation. By default the worker
|
||||
deletes its files from disk: only the repo's files and hf's `.cache`; files you put in the folder
|
||||
yourself are kept, empty folders are removed. Unchecked, only the library entry goes and the folder
|
||||
shows up under "Found in the models folder".
|
||||
- **Verify** a model: every selected file is checked for existence, size and the version hf recorded;
|
||||
reports missing files, size mismatches and extra files in the folder. **Deep verify** hashes every
|
||||
file (SHA-256 for LFS files, git blob SHA-1 for small files) against the Hub, with progress.
|
||||
- **Repair** re-downloads only what's missing or broken. Broken files are deleted before `hf` runs,
|
||||
because `hf` skips a file whose metadata matches without checking its content or size.
|
||||
- **Update checks:** the Hub check (every `UPDATE_CHECK_INTERVAL_HOURS` and "Check now") also
|
||||
resolves the tracked revision. If there's a newer commit, the model shows "update available" (badge
|
||||
in the library and a Status filter value, banner on the model page) with the selected files that
|
||||
changed, were added or were removed. **Update** is a deliberate action: it pins the new commit (the
|
||||
old one stays in the revision history), downloads changed and new files, and deletes files that are
|
||||
no longer selected once the download succeeded.
|
||||
- Download card: **Resume** for interrupted or cancelled downloads, **Retry** for failed ones.
|
||||
- Job names in the job list and job page: Download, Download more, Import, Repair, Update, Verify,
|
||||
Deep verify, Delete.
|
||||
|
||||
## [0.5.0] - 2026-10-06
|
||||
|
||||
Hugging Face style model pages, file labels, recommended files, importing models already on disk,
|
||||
|
||||
@@ -76,8 +76,12 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
"Found in the models folder"; **Import** matches them with the Hub repo and verifies the files
|
||||
instead of downloading them again. See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models).
|
||||
- **Deleted on the Hub:** if a repo (or its pinned commit) disappears from Hugging Face, the model
|
||||
is flagged and your local copy is kept.
|
||||
- **Verify / repair:** Verify checks every file's presence and size, Deep verify hashes them against
|
||||
the Hub; Repair downloads only what's missing or broken.
|
||||
- **Updates:** Kaname checks the Hub regularly and shows which of your files a newer commit changes;
|
||||
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
|
||||
model is flagged and your local copy is kept.
|
||||
- **Delete:** removes the model and, if you want, its files from disk.
|
||||
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `jobs` ADD `result` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `update_diff` text;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,13 @@
|
||||
"when": 1791233749207,
|
||||
"tag": "0008_local_folders",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "6",
|
||||
"when": 1791238659338,
|
||||
"tag": "0009_verify_update",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
"@libsql/client": "^0.18.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
|
||||
/**
|
||||
* Delete a model, whatever its state (failed, incomplete, ready, …). By default its files are
|
||||
* deleted from disk too (by the worker); unchecked, only the library entry goes.
|
||||
*/
|
||||
export function DeleteModelButton({
|
||||
id,
|
||||
repoId,
|
||||
localPath,
|
||||
mayHaveFiles,
|
||||
}: {
|
||||
id: string;
|
||||
repoId: string;
|
||||
localPath: string;
|
||||
/** False if nothing was ever downloaded, so there's nothing on disk to ask about. */
|
||||
mayHaveFiles: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [deleteFiles, setDeleteFiles] = useState(true);
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
async function remove() {
|
||||
setPending(true);
|
||||
const res = await fetch(`/api/models/${id}${mayHaveFiles && deleteFiles ? "?files=1" : ""}`, { method: "DELETE" });
|
||||
if (res.ok) {
|
||||
toast.success(res.status === 202 ? `Deleting ${repoId} and its files…` : `${repoId} removed from the library`);
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Delete failed (${res.status})`);
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {repoId}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{mayHaveFiles
|
||||
? "The model is removed from the library, including its tags and job history."
|
||||
: "Nothing was downloaded yet, so this only removes the library entry."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{mayHaveFiles && (
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-md bg-muted/50 px-3 py-2.5 text-sm">
|
||||
<Checkbox checked={deleteFiles} onCheckedChange={(v) => setDeleteFiles(v === true)} className="mt-0.5" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span>Also delete the files from disk</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Deletes the repo's files in <code className="font-mono">{localPath}</code>. Files you put there yourself are
|
||||
kept. Unchecked, the folder stays and shows up under “Found in the models folder”.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove} disabled={pending}>
|
||||
{mayHaveFiles && deleteFiles ? "Delete with files" : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { cancelJob, startDownload } from "@/components/job-actions";
|
||||
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
|
||||
import { JobProgress, JobStateBadge } from "@/components/job-progress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { VerifyResult } from "@/components/verify-result";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import type { ModelStatus } from "@/lib/db/schema";
|
||||
import { groupJobFiles } from "@/lib/file-groups";
|
||||
import { formatBytes, percent } from "@/lib/format";
|
||||
import { jobLabel } from "@/lib/job-labels";
|
||||
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
const VERIFY_KINDS = ["verify", "deep_verify"];
|
||||
|
||||
/** Sidebar card: current download state, actions and (while running) per-file progress. */
|
||||
/** Sidebar card: current job with progress, the last verify result, and the model's actions. */
|
||||
export function DownloadCard({
|
||||
modelId,
|
||||
status,
|
||||
@@ -27,11 +30,18 @@ export function DownloadCard({
|
||||
}) {
|
||||
const { snapshot } = useLive({ model: modelId });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const latest = snapshot?.jobs[0];
|
||||
const jobs = snapshot?.jobs ?? [];
|
||||
const latest = jobs[0];
|
||||
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
|
||||
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
|
||||
// The newest verify, unless a download ran after it (its result would be stale).
|
||||
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
|
||||
const verify = lastCheck && VERIFY_KINDS.includes(lastCheck.kind) && lastCheck.state === "completed" ? lastCheck : undefined;
|
||||
const verifyProblems = verify?.result
|
||||
? (verify.result.missing?.length ?? 0) + (verify.result.sizeMismatch?.length ?? 0) + (verify.result.hashMismatch?.length ?? 0)
|
||||
: 0;
|
||||
|
||||
async function run(fn: () => Promise<void>) {
|
||||
async function run(fn: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
@@ -40,24 +50,40 @@ export function DownloadCard({
|
||||
}
|
||||
}
|
||||
|
||||
const neverRan = jobs.length === 0;
|
||||
const downloadLabel = neverRan
|
||||
? "Download"
|
||||
: latest?.state === "interrupted" || latest?.state === "cancelled"
|
||||
? "Resume"
|
||||
: latest?.state === "failed" && latest.kind === "download"
|
||||
? "Retry"
|
||||
: "Download missing";
|
||||
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
|
||||
let hint = "Downloads the selected files at the pinned commit.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free download slot." : "Queued, but the worker is offline.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
else if (open) hint = "Runs in the background; you can close this page.";
|
||||
else if (status === "deleting") hint = "Deleting…";
|
||||
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
else if (status === "ready") hint = "All selected files are present.";
|
||||
else if (hubMissing) hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
|
||||
const showProgress =
|
||||
latest && latest.kind !== "delete" && !(latest.state === "completed" && (status === "ready" || VERIFY_KINDS.includes(latest.kind)));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
|
||||
<DownloadIcon className="size-4 text-muted-foreground" />
|
||||
Download
|
||||
{open ? jobLabel(open) : "Download"}
|
||||
</h3>
|
||||
{latest && <JobStateBadge job={latest} />}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
|
||||
{latest && !(latest.state === "completed" && status === "ready") && <JobProgress job={latest} compact />}
|
||||
{showProgress && <JobProgress job={latest} compact />}
|
||||
|
||||
{latest?.state === "failed" && latest.errorMessage && (
|
||||
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
|
||||
@@ -82,30 +108,58 @@ export function DownloadCard({
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{verify?.result && !open && (
|
||||
<div className="rounded-md bg-muted/50 px-2.5 py-2">
|
||||
<VerifyResult result={verify.result} deep={verify.kind === "deep_verify"} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{open ? (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={busy || open.cancelRequested}
|
||||
onClick={() => run(() => cancelJob(open.id))}
|
||||
>
|
||||
<Button variant="destructive" size="sm" disabled={busy || open.cancelRequested} onClick={() => run(() => cancelJob(open.id))}>
|
||||
{open.cancelRequested ? "Cancelling…" : "Cancel"}
|
||||
</Button>
|
||||
) : (
|
||||
status !== "ready" &&
|
||||
!hubMissing &&
|
||||
snapshot && (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
|
||||
{latest ? "Download again" : "Download"}
|
||||
</Button>
|
||||
)
|
||||
<>
|
||||
{needsRepair ? (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startRepair(modelId))}>
|
||||
<WrenchIcon />
|
||||
Repair
|
||||
</Button>
|
||||
) : (
|
||||
canDownload && (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
|
||||
{downloadLabel}
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
{canVerify && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, false))}
|
||||
title="Check that every selected file exists with the right size (seconds)"
|
||||
>
|
||||
<ShieldCheckIcon />
|
||||
Verify
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, true))}
|
||||
title="Hash every file and compare with the Hub (slow: reads every byte)"
|
||||
>
|
||||
Deep verify
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{latest && (
|
||||
<Link
|
||||
href={`/jobs/${latest.id}`}
|
||||
className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted"
|
||||
>
|
||||
{latest && latest.kind !== "delete" && (
|
||||
<Link href={`/jobs/${latest.id}`} className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted">
|
||||
View log
|
||||
</Link>
|
||||
)}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Re-check right now whether the repo and pinned commit are still on the Hub. */
|
||||
/** Check the Hub right now: repo and pinned commit still there, newer commit on the tracked revision. */
|
||||
export function HubCheckButton({ modelId, label = "Check now" }: { modelId: string; label?: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -18,7 +18,8 @@ export function HubCheckButton({ modelId, label = "Check now" }: { modelId: stri
|
||||
const res = await fetch(`/api/models/${modelId}/hub-check`, { method: "POST" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) toast.error(json.error?.message ?? `Check failed (${res.status})`);
|
||||
else if (json.state === "available") toast.success("Still available on Hugging Face");
|
||||
else if (json.state === "available" && json.update) toast.info("Update available");
|
||||
else if (json.state === "available") toast.success(json.warning ?? "Up to date");
|
||||
else if (json.state === "repo_missing") toast.warning("The repo is no longer on Hugging Face");
|
||||
else if (json.state === "commit_missing") toast.warning("The pinned commit is no longer on Hugging Face");
|
||||
else toast.error(`Could not check: ${json.error ?? "unknown error"}`);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LocalTime } from "@/components/local-time";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { jobLabel } from "@/lib/job-labels";
|
||||
|
||||
/** Job history of one model (live). */
|
||||
export function JobsTab({ modelId }: { modelId: string }) {
|
||||
@@ -35,8 +36,7 @@ export function JobsTab({ modelId }: { modelId: string }) {
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{j.kind}
|
||||
{j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""}
|
||||
{jobLabel(j)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<JobStateBadge job={j} />
|
||||
|
||||
@@ -25,6 +25,7 @@ import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
import { getModelByRepo, relatedModels } from "@/lib/library";
|
||||
import { fileRole } from "@/lib/file-roles";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
@@ -35,8 +36,9 @@ import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCard } from "./model-card";
|
||||
import { RemoveModelButton } from "./remove-model-button";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -95,12 +97,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const hubTags = model.hubTags ?? [];
|
||||
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
|
||||
|
||||
const [tags, related, card, worker] = await Promise.all([
|
||||
const [tags, related, card, worker, recentJobs] = await Promise.all([
|
||||
modelTagList(model.id),
|
||||
relatedModels(model.id, baseModels),
|
||||
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
|
||||
getWorkerStatus(),
|
||||
listModelJobs(model.id, 1),
|
||||
]);
|
||||
const update =
|
||||
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
|
||||
? model.updateDiff
|
||||
: null;
|
||||
|
||||
const selected = files.filter((f) => f.selected);
|
||||
const others = files.filter((f) => !f.selected);
|
||||
@@ -130,8 +137,18 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<CopyButton value={model.repoId} label="Copy repo ID" />
|
||||
<ModelStatusBadge status={model.status} />
|
||||
<HubStateBadge state={model.hubState} />
|
||||
{update && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
|
||||
update available
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{model.status === "pending" && <RemoveModelButton id={model.id} />}
|
||||
<DeleteModelButton
|
||||
id={model.id}
|
||||
repoId={model.repoId}
|
||||
localPath={model.localPath}
|
||||
mayHaveFiles={model.status !== "pending" || recentJobs.length > 0}
|
||||
/>
|
||||
<ExternalButton href={hub}>🤗 Hugging Face</ExternalButton>
|
||||
</div>
|
||||
</div>
|
||||
@@ -190,6 +207,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
|
||||
{update && (
|
||||
<UpdateBanner modelId={model.id} revision={model.trackedRevision} pinnedSha={model.pinnedSha} diff={update} hubUrl={hub} />
|
||||
)}
|
||||
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
|
||||
{/* Content card with the tabs as a segmented control in its header */}
|
||||
<Panel className="min-w-0 overflow-hidden">
|
||||
@@ -305,9 +326,11 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
)}
|
||||
<dt className="text-muted-foreground">On the Hub</dt>
|
||||
<dd className="flex flex-col items-start gap-0.5">
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300")}>
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
|
||||
{model.hubState === "available"
|
||||
? "Available"
|
||||
? update
|
||||
? "Update available"
|
||||
: "Up to date"
|
||||
: model.hubState === "repo_missing"
|
||||
? "Repo deleted"
|
||||
: model.hubState === "commit_missing"
|
||||
@@ -316,9 +339,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</span>
|
||||
{model.lastCheckedAt && (
|
||||
<span className="text-xs text-muted-foreground" title={model.lastCheckError ?? undefined}>
|
||||
{model.lastCheckError ? "check failed" : "checked"} <LocalTime value={model.lastCheckedAt} />
|
||||
checked <LocalTime value={model.lastCheckedAt} />
|
||||
</span>
|
||||
)}
|
||||
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
|
||||
<HubCheckButton modelId={model.id} />
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Added</dt>
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** Removes a not-yet-downloaded model from the library (DB only, no files exist yet). */
|
||||
export function RemoveModelButton({ id }: { id: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
const res = await fetch(`/api/models/${id}`, { method: "DELETE" });
|
||||
if (res.ok) {
|
||||
toast.success("Removed from library");
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Remove failed (${res.status})`);
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="destructive" size="sm" />}>Remove</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove from library?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Nothing has been downloaded yet, so this only removes the entry.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove} disabled={busy}>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowUpCircleIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { startUpdate } from "@/components/job-actions";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
|
||||
function FileGroup({ title, files, tone }: { title: string; files: UpdateDiffFile[]; tone: string }) {
|
||||
if (files.length === 0) return null;
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className={`text-xs font-medium ${tone}`}>
|
||||
{title} ({files.length})
|
||||
</span>
|
||||
<ul className="flex flex-col gap-0.5 text-xs">
|
||||
{files.slice(0, 20).map((f) => (
|
||||
<li key={f.path} className="flex justify-between gap-3">
|
||||
<span className="font-mono break-all">{f.path}</span>
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">
|
||||
{f.oldSize != null && f.oldSize !== f.size ? `${formatBytes(f.oldSize)} → ` : ""}
|
||||
{formatBytes(f.size)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{files.length > 20 && <li className="text-muted-foreground">… {files.length - 20} more</li>}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Update available": what would change in the selection, and the deliberate Update action. */
|
||||
export function UpdateBanner({
|
||||
modelId,
|
||||
revision,
|
||||
pinnedSha,
|
||||
diff,
|
||||
hubUrl,
|
||||
}: {
|
||||
modelId: string;
|
||||
revision: string;
|
||||
pinnedSha: string;
|
||||
diff: UpdateDiff;
|
||||
hubUrl: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const changes = diff.changed.length + diff.added.length + diff.removed.length;
|
||||
const download = [...diff.changed, ...diff.added].reduce((s, f) => s + f.size, 0);
|
||||
|
||||
async function update() {
|
||||
setBusy(true);
|
||||
try {
|
||||
if (await startUpdate(modelId)) router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-xl border border-sky-500/30 bg-sky-500/10 px-4 py-3 text-sm">
|
||||
<div className="flex flex-wrap items-start gap-3">
|
||||
<ArrowUpCircleIcon className="mt-0.5 size-4 shrink-0 text-sky-600 dark:text-sky-400" />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<p className="font-medium text-sky-900 dark:text-sky-100">
|
||||
Update available: {revision} is at{" "}
|
||||
<a href={`${hubUrl}/commit/${diff.sha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline">
|
||||
{shortSha(diff.sha)}
|
||||
</a>
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
You have <span className="font-mono">{shortSha(pinnedSha)}</span>.{" "}
|
||||
{changes === 0
|
||||
? "None of your selected files changed; updating only moves the pin."
|
||||
: `${changes} of your selected files would change (${formatBytes(download)} to download).`}{" "}
|
||||
Checked <LocalTime value={diff.checkedAt} />.
|
||||
</p>
|
||||
</div>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button size="sm" disabled={busy} />}>Update</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Update to {shortSha(diff.sha)}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The model is pinned to the new commit (the old one stays in the history) and changed or new files are
|
||||
downloaded. Files that are no longer part of your selection are deleted after the download succeeded.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={update} disabled={busy}>
|
||||
Update
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
{changes > 0 && (
|
||||
<div className="grid gap-3 rounded-lg bg-background/60 px-3 py-2.5 md:grid-cols-3">
|
||||
<FileGroup title="Changed" files={diff.changed} tone="text-amber-700 dark:text-amber-300" />
|
||||
<FileGroup title="Added" files={diff.added} tone="text-emerald-700 dark:text-emerald-300" />
|
||||
<FileGroup title="Removed" files={diff.removed} tone="text-destructive" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import { formatDuration } from "@/lib/format";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { jobLabel } from "@/lib/job-labels";
|
||||
import type { JobSnapshot } from "@/lib/jobs";
|
||||
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
@@ -40,7 +41,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-xl font-semibold">
|
||||
{job.kind === "download" ? "Download" : job.kind} ·{" "}
|
||||
{jobLabel(job)} ·{" "}
|
||||
<Link href={`/${job.repoId}`} className="hover:underline">
|
||||
{job.repoId}
|
||||
</Link>
|
||||
|
||||
@@ -56,7 +56,12 @@ function toSearchable(r: LibraryRow): SearchableModel {
|
||||
pipelineTag: r.pipelineTag,
|
||||
license: r.license,
|
||||
status: r.status,
|
||||
hubStatus: r.hubState && r.hubState !== "available" ? HUB_STATE_LABEL[r.hubState].label : null,
|
||||
hubStatus:
|
||||
r.hubState && r.hubState !== "available"
|
||||
? HUB_STATE_LABEL[r.hubState].label
|
||||
: r.updateAvailable
|
||||
? "update available"
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -223,6 +228,11 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
<span className="flex flex-wrap gap-1">
|
||||
<ModelStatusBadge status={r.status} />
|
||||
<HubStateBadge state={r.hubState} />
|
||||
{r.updateAvailable && (r.hubState === "available" || !r.hubState) && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium whitespace-nowrap text-sky-700 dark:text-sky-300">
|
||||
update available
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { checkHubAvailability, getCheckedModel } from "@/lib/hub/availability";
|
||||
import { checkHub, getCheckedModel } from "@/lib/hub/availability";
|
||||
|
||||
/** Check right now whether the repo and pinned commit are still on the Hub. */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
const model = await getCheckedModel(id);
|
||||
if (!model) return apiError(404, "not_found", "Model not found.");
|
||||
return NextResponse.json(await checkHubAvailability(model));
|
||||
return NextResponse.json(await checkHub(model));
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError, queueDownload } from "@/lib/jobs";
|
||||
|
||||
/** Download again what's missing or broken (the worker deletes broken files first). */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/repair">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await queueDownload(id, "repair"), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -1,13 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { ModelError, removeModel } from "@/lib/models";
|
||||
import { deleteModel, ModelError } from "@/lib/models";
|
||||
|
||||
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (_req, { params }) => {
|
||||
/** Delete a model; `?files=1` also deletes its files from disk (queued for the worker). */
|
||||
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await removeModel(id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
const deleteFiles = new URL(req.url).searchParams.get("files") === "1";
|
||||
const { queued } = await deleteModel(id, { deleteFiles });
|
||||
return queued ? NextResponse.json({ queued }, { status: 202 }) : new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { applyUpdate, ModelError } from "@/lib/models";
|
||||
|
||||
/** Update to the newer commit found by the last Hub check (deliberate, never automatic). */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/update">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await applyUpdate(id), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError, queueVerify } from "@/lib/jobs";
|
||||
|
||||
/** Queue a verify (`?deep=1`: hash every file) of the model's selected files. */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/verify">>(async (req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const deep = new URL(req.url).searchParams.get("deep") === "1";
|
||||
return NextResponse.json(await queueVerify(id, deep), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -17,3 +17,17 @@ export async function startDownload(modelId: string) {
|
||||
export async function cancelJob(jobId: string) {
|
||||
if (await post(`/api/jobs/${jobId}/cancel`)) toast.info("Cancelling…");
|
||||
}
|
||||
|
||||
export async function startVerify(modelId: string, deep: boolean) {
|
||||
if (await post(`/api/models/${modelId}/verify${deep ? "?deep=1" : ""}`)) toast.success(deep ? "Deep verify queued" : "Verify queued");
|
||||
}
|
||||
|
||||
export async function startRepair(modelId: string) {
|
||||
if (await post(`/api/models/${modelId}/repair`)) toast.success("Repair queued");
|
||||
}
|
||||
|
||||
export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
const ok = await post(`/api/models/${modelId}/update`);
|
||||
if (ok) toast.success("Update queued");
|
||||
return ok;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { CircleAlertIcon, CircleCheckIcon } from "lucide-react";
|
||||
import type { JobResult } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function PathList({ title, paths, tone }: { title: string; paths: string[]; tone: "bad" | "muted" }) {
|
||||
if (paths.length === 0) return null;
|
||||
return (
|
||||
<details className="text-xs">
|
||||
<summary className={cn("cursor-pointer select-none", tone === "bad" ? "text-destructive" : "text-muted-foreground")}>
|
||||
{title} ({paths.length})
|
||||
</summary>
|
||||
<ul className="mt-1 ml-3 flex flex-col gap-0.5 font-mono break-all text-muted-foreground">
|
||||
{paths.slice(0, 50).map((p) => (
|
||||
<li key={p}>{p}</li>
|
||||
))}
|
||||
{paths.length > 50 && <li>… {paths.length - 50} more</li>}
|
||||
</ul>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
/** Outcome of a (deep) verify: problems per kind, plus extra files in the folder. */
|
||||
export function VerifyResult({ result, deep }: { result: JobResult; deep: boolean }) {
|
||||
const missing = result.missing ?? [];
|
||||
const sizeMismatch = result.sizeMismatch ?? [];
|
||||
const hashMismatch = result.hashMismatch ?? [];
|
||||
const extra = result.extra ?? [];
|
||||
const problems = missing.length + sizeMismatch.length + hashMismatch.length;
|
||||
const extraBytes = extra.reduce((s, e) => s + e.size, 0);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className={cn("flex items-center gap-1.5 text-xs", problems > 0 ? "text-destructive" : "text-emerald-700 dark:text-emerald-400")}>
|
||||
{problems > 0 ? <CircleAlertIcon className="size-3.5" /> : <CircleCheckIcon className="size-3.5" />}
|
||||
{problems > 0
|
||||
? `${problems} of ${result.checked ?? 0} files need repair`
|
||||
: `All ${result.checked ?? 0} files OK${deep ? ", hashes match the Hub" : ""}`}
|
||||
</p>
|
||||
<PathList title="Missing" paths={missing} tone="bad" />
|
||||
<PathList title="Wrong size" paths={sizeMismatch} tone="bad" />
|
||||
<PathList title={deep ? "Hash mismatch" : "Different version (hf metadata)"} paths={hashMismatch} tone="bad" />
|
||||
{extra.length > 0 && (
|
||||
<PathList
|
||||
title={`Extra files in the folder, ${formatBytes(extraBytes)}`}
|
||||
paths={extra.map((e) => (e.inRepo ? `${e.path} (repo file, not selected)` : e.path))}
|
||||
tone="muted"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+28
-1
@@ -50,6 +50,30 @@ export type ModelStatus = (typeof MODEL_STATUSES)[number];
|
||||
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
|
||||
export type HubState = (typeof HUB_STATES)[number];
|
||||
|
||||
export type UpdateDiffFile = { path: string; size: number; oldSize?: number };
|
||||
export type UpdateDiff = {
|
||||
/** Commit the diff was computed against (the tracked revision's head on the Hub). */
|
||||
sha: string;
|
||||
changed: UpdateDiffFile[];
|
||||
added: UpdateDiffFile[];
|
||||
removed: UpdateDiffFile[];
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
/** Outcome of a verify job, or extra instructions for a job (`removePaths` after an update). */
|
||||
export type JobResult = {
|
||||
checked?: number;
|
||||
missing?: string[];
|
||||
sizeMismatch?: string[];
|
||||
hashMismatch?: string[];
|
||||
/** Files in the model folder that aren't selected repo files. */
|
||||
extra?: { path: string; size: number; inRepo: boolean }[];
|
||||
/** Update jobs: files of the old revision to delete once the download succeeded. */
|
||||
removePaths?: string[];
|
||||
/** Delete jobs: files that were kept because they don't belong to the repo. */
|
||||
kept?: string[];
|
||||
};
|
||||
|
||||
export const models = sqliteTable(
|
||||
"models",
|
||||
{
|
||||
@@ -81,6 +105,8 @@ export const models = sqliteTable(
|
||||
hubState: text("hub_state", { enum: HUB_STATES }),
|
||||
/** When the repo or pinned commit was first seen missing; cleared when it's back. */
|
||||
hubMissingSince: ts("hub_missing_since"),
|
||||
/** What updating to `remoteSha` would change in the selection; null when up to date. */
|
||||
updateDiff: text("update_diff", { mode: "json" }).$type<UpdateDiff>(),
|
||||
lastVerifiedAt: ts("last_verified_at"),
|
||||
downloadedAt: ts("downloaded_at"),
|
||||
// Hub metadata (for search/filters), refreshed by the worker. Null until fetched.
|
||||
@@ -190,7 +216,7 @@ export const modelFiles = sqliteTable(
|
||||
// Jobs (executed by the worker)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const;
|
||||
@@ -239,6 +265,7 @@ export const jobs = sqliteTable(
|
||||
exitCode: integer("exit_code"),
|
||||
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
|
||||
errorMessage: text("error_message"),
|
||||
result: text("result", { mode: "json" }).$type<JobResult>(),
|
||||
/** Set by the web app; the worker picks it up and stops the job. */
|
||||
cancelRequestedAt: ts("cancel_requested_at"),
|
||||
startedAt: ts("started_at"),
|
||||
|
||||
+90
-24
@@ -1,9 +1,28 @@
|
||||
import { asc, eq, isNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models, type HubState } from "@/lib/db/schema";
|
||||
import { getRepoInfo, HubError } from "./client";
|
||||
// Hub checks per model: is the repo (and the pinned commit) still there, and is there a newer
|
||||
// commit on the tracked revision? Run periodically by the worker and on "Check now". Results are
|
||||
// stored on the model; nothing local is ever changed by a check.
|
||||
|
||||
type CheckedModel = Pick<typeof models.$inferSelect, "id" | "repoId" | "pinnedSha" | "hubMissingSince">;
|
||||
import { and, asc, eq, isNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema";
|
||||
import { computeUpdateDiff } from "@/lib/update-diff";
|
||||
import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client";
|
||||
|
||||
type CheckedModel = Pick<
|
||||
typeof models.$inferSelect,
|
||||
"id" | "repoId" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
|
||||
>;
|
||||
|
||||
const CHECKED_COLUMNS = {
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
pinnedSha: models.pinnedSha,
|
||||
trackedRevision: models.trackedRevision,
|
||||
hubMissingSince: models.hubMissingSince,
|
||||
updateDiff: models.updateDiff,
|
||||
includePatterns: models.includePatterns,
|
||||
excludePatterns: models.excludePatterns,
|
||||
};
|
||||
|
||||
/** Why new downloads are impossible, or null if the Hub still has the repo at the pinned commit. */
|
||||
export function hubMissingMessage(model: { repoId: string; hubState: HubState | null }): string | null {
|
||||
@@ -16,25 +35,73 @@ export function hubMissingMessage(model: { repoId: string; hubState: HubState |
|
||||
return null;
|
||||
}
|
||||
|
||||
export type HubCheckResult = { state: HubState } | { state: null; error: string };
|
||||
export type HubCheckResult =
|
||||
| { state: HubState; remoteSha: string | null; update: UpdateDiff | null; warning: string | null }
|
||||
| { state: null; error: string };
|
||||
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
const isGated = (err: unknown) => err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access");
|
||||
|
||||
/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */
|
||||
async function resolve(repoId: string, revision: string): Promise<string | null> {
|
||||
try {
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "revision_not_found") return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(model: CheckedModel): Promise<HubCheckResult> {
|
||||
// 1. Head of the tracked revision (a full SHA as revision means "pinned for good").
|
||||
let remoteSha: string | null;
|
||||
let warning: string | null = null;
|
||||
if (SHA_RE.test(model.trackedRevision)) {
|
||||
remoteSha = model.trackedRevision;
|
||||
} else {
|
||||
remoteSha = await resolve(model.repoId, model.trackedRevision);
|
||||
if (!remoteSha) warning = `Revision "${model.trackedRevision}" no longer exists on the Hub; can't check for updates.`;
|
||||
}
|
||||
|
||||
// 2. Is the pinned commit still there? (Known if it's the head.)
|
||||
const pinnedExists = remoteSha === model.pinnedSha || (await resolve(model.repoId, model.pinnedSha)) !== null;
|
||||
const state: HubState = pinnedExists ? "available" : "commit_missing";
|
||||
|
||||
// 3. Newer commit: what would change in the selection? Only recomputed when the head moved.
|
||||
let update: UpdateDiff | null = null;
|
||||
if (remoteSha && remoteSha !== model.pinnedSha) {
|
||||
update = model.updateDiff?.sha === remoteSha ? model.updateDiff : null;
|
||||
if (!update) {
|
||||
const [next, current] = await Promise.all([
|
||||
listFiles(model.repoId, remoteSha),
|
||||
db()
|
||||
.select({ path: modelFiles.path, size: modelFiles.size, blobOid: modelFiles.blobOid, lfsSha256: modelFiles.lfsSha256 })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, model.id), eq(modelFiles.selected, true))),
|
||||
]);
|
||||
update = computeUpdateDiff(remoteSha, current, next, { include: model.includePatterns, exclude: model.excludePatterns });
|
||||
}
|
||||
}
|
||||
return { state, remoteSha, update, warning };
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the repo, and the pinned commit, still on the Hub? Stores the result on the model. Only a
|
||||
* definite answer changes `hubState`; network errors, rate limits or a bad token are kept as
|
||||
* `lastCheckError`. Never touches local files.
|
||||
* Check one model against the Hub and store the result. Only a definite answer changes the stored
|
||||
* state; network errors, rate limits or a bad token are kept as `lastCheckError`.
|
||||
*/
|
||||
export async function checkHubAvailability(model: CheckedModel): Promise<HubCheckResult> {
|
||||
export async function checkHub(model: CheckedModel): Promise<HubCheckResult> {
|
||||
let result: HubCheckResult;
|
||||
try {
|
||||
await getRepoInfo(model.repoId, model.pinnedSha);
|
||||
result = { state: "available" };
|
||||
result = await run(model);
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "repo_not_found") result = { state: "repo_missing" };
|
||||
else if (err instanceof HubError && err.code === "revision_not_found") result = { state: "commit_missing" };
|
||||
// Gated repos exist; access is a download concern, not availability.
|
||||
else if (err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access")) {
|
||||
result = { state: "available" };
|
||||
} else result = { state: null, error: err instanceof Error ? err.message : String(err) };
|
||||
if (err instanceof HubError && err.code === "repo_not_found") {
|
||||
result = { state: "repo_missing", remoteSha: null, update: null, warning: null };
|
||||
} else if (isGated(err)) {
|
||||
// Gated repos exist; access is a download concern.
|
||||
result = { state: "available", remoteSha: null, update: model.updateDiff ?? null, warning: message(err) };
|
||||
} else {
|
||||
result = { state: null, error: message(err) };
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
@@ -45,9 +112,10 @@ export async function checkHubAvailability(model: CheckedModel): Promise<HubChec
|
||||
? { lastCheckedAt: now, lastCheckError: result.error }
|
||||
: {
|
||||
lastCheckedAt: now,
|
||||
lastCheckError: null,
|
||||
lastCheckError: result.warning,
|
||||
hubState: result.state,
|
||||
hubMissingSince: result.state === "available" ? null : (model.hubMissingSince ?? now),
|
||||
...(result.state === "repo_missing" ? {} : { remoteSha: result.remoteSha, updateDiff: result.update }),
|
||||
},
|
||||
)
|
||||
.where(eq(models.id, model.id));
|
||||
@@ -58,7 +126,7 @@ export async function checkHubAvailability(model: CheckedModel): Promise<HubChec
|
||||
export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Promise<CheckedModel[]> {
|
||||
const cutoff = new Date(Date.now() - intervalMs);
|
||||
return db()
|
||||
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha, hubMissingSince: models.hubMissingSince })
|
||||
.select(CHECKED_COLUMNS)
|
||||
.from(models)
|
||||
.where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff)))
|
||||
.orderBy(asc(models.lastCheckedAt))
|
||||
@@ -66,8 +134,6 @@ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Prom
|
||||
}
|
||||
|
||||
export async function getCheckedModel(id: string): Promise<CheckedModel | undefined> {
|
||||
return db().query.models.findFirst({
|
||||
columns: { id: true, repoId: true, pinnedSha: true, hubMissingSince: true },
|
||||
where: eq(models.id, id),
|
||||
});
|
||||
const [row] = await db().select(CHECKED_COLUMNS).from(models).where(eq(models.id, id));
|
||||
return row;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Human-readable job names (shared by UI components).
|
||||
|
||||
const DOWNLOAD_PURPOSE: Record<string, string> = {
|
||||
initial: "Download",
|
||||
add: "Download more",
|
||||
import: "Import",
|
||||
repair: "Repair",
|
||||
update: "Update",
|
||||
};
|
||||
|
||||
const KIND: Record<string, string> = { download: "Download", verify: "Verify", deep_verify: "Deep verify", delete: "Delete" };
|
||||
|
||||
export function jobLabel(job: { kind: string; purpose: string | null }): string {
|
||||
if (job.kind === "download") return DOWNLOAD_PURPOSE[job.purpose ?? "initial"] ?? "Download";
|
||||
return KIND[job.kind] ?? job.kind;
|
||||
}
|
||||
+54
-8
@@ -6,6 +6,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import {
|
||||
ACTIVE_JOB_STATES,
|
||||
type JobPurpose,
|
||||
type JobResult,
|
||||
jobFiles,
|
||||
jobLogs,
|
||||
jobs,
|
||||
@@ -26,19 +27,31 @@ export class JobError extends Error {
|
||||
const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
|
||||
const INSERT_CHUNK = 500;
|
||||
|
||||
/** Queue a download of all selected files of a model at its pinned SHA. */
|
||||
export async function queueDownload(modelId: string, purpose: JobPurpose = "initial"): Promise<{ jobId: string }> {
|
||||
/** True if the model has a queued or running job (only one job per model at a time). */
|
||||
export async function hasOpenJob(modelId: string): Promise<boolean> {
|
||||
const open = await db().query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
|
||||
});
|
||||
return !!open;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a download of all selected files of a model at its pinned SHA. hf skips files that are
|
||||
* already complete, so this also serves as resume and repair. `removePaths`: files of an older
|
||||
* revision to delete once the download succeeded (updates).
|
||||
*/
|
||||
export async function queueDownload(
|
||||
modelId: string,
|
||||
purpose: JobPurpose = "initial",
|
||||
options: { removePaths?: string[] } = {},
|
||||
): Promise<{ jobId: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new JobError("hub_missing", missing, 409);
|
||||
|
||||
const open = await d.query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
|
||||
});
|
||||
if (open) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
@@ -57,6 +70,7 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init
|
||||
purpose,
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: files.reduce((s, f) => s + f.size, 0),
|
||||
result: options.removePaths?.length ? { removePaths: options.removePaths } : null,
|
||||
}),
|
||||
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
|
||||
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
|
||||
@@ -64,6 +78,36 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init
|
||||
return { jobId };
|
||||
}
|
||||
|
||||
/** Queue a verify (size + hf metadata) or deep verify (hashes) of the selected files. Local only. */
|
||||
export async function queueVerify(modelId: string, deep: boolean): Promise<{ jobId: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true)))
|
||||
.orderBy(asc(modelFiles.path));
|
||||
if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400);
|
||||
|
||||
const jobId = ulid();
|
||||
await d.batch([
|
||||
d.insert(jobs).values({
|
||||
id: jobId,
|
||||
modelId,
|
||||
kind: deep ? "deep_verify" : "verify",
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: files.reduce((s, f) => s + f.size, 0),
|
||||
}),
|
||||
...chunk(
|
||||
files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })),
|
||||
INSERT_CHUNK,
|
||||
).map((c) => d.insert(jobFiles).values(c)),
|
||||
]);
|
||||
return { jobId };
|
||||
}
|
||||
|
||||
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
|
||||
export async function requestCancel(jobId: string): Promise<void> {
|
||||
const res = await db()
|
||||
@@ -97,6 +141,7 @@ export type JobSnapshot = {
|
||||
exitCode: number | null;
|
||||
errorCode: string | null;
|
||||
errorMessage: string | null;
|
||||
result: JobResult | null;
|
||||
cancelRequested: boolean;
|
||||
createdAt: number;
|
||||
startedAt: number | null;
|
||||
@@ -128,6 +173,7 @@ const jobColumns = {
|
||||
exitCode: jobs.exitCode,
|
||||
errorCode: jobs.errorCode,
|
||||
errorMessage: jobs.errorMessage,
|
||||
result: jobs.result,
|
||||
cancelRequestedAt: jobs.cancelRequestedAt,
|
||||
createdAt: jobs.createdAt,
|
||||
startedAt: jobs.startedAt,
|
||||
|
||||
+3
-1
@@ -21,6 +21,7 @@ export async function listLibrary() {
|
||||
remoteSha: models.remoteSha,
|
||||
status: models.status,
|
||||
hubState: models.hubState,
|
||||
updateDiff: models.updateDiff,
|
||||
createdAt: models.createdAt,
|
||||
downloadedAt: models.downloadedAt,
|
||||
baseModels: models.baseModels,
|
||||
@@ -51,8 +52,9 @@ export async function listLibrary() {
|
||||
const tagsByModel = new Map<string, Tag[]>();
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
|
||||
|
||||
return rows.map((r) => ({
|
||||
return rows.map(({ updateDiff, ...r }) => ({
|
||||
...r,
|
||||
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
|
||||
author: r.repoId.split("/")[0],
|
||||
families: modelFamilies(r.repoId, r.baseModels),
|
||||
baseModels: r.baseModels ?? [],
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Remove a model and everything that references it from the database (not its files).
|
||||
// Shared by the web app and the worker, so no "server-only" import here.
|
||||
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobFiles, jobLogs, jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
|
||||
export async function purgeModelRows(modelId: string): Promise<void> {
|
||||
const d = db();
|
||||
const jobIds = d.select({ id: jobs.id }).from(jobs).where(eq(jobs.modelId, modelId));
|
||||
await d.batch([
|
||||
d.delete(jobLogs).where(inArray(jobLogs.jobId, jobIds)),
|
||||
d.delete(jobFiles).where(inArray(jobFiles.jobId, jobIds)),
|
||||
d.delete(jobs).where(eq(jobs.modelId, modelId)),
|
||||
d.delete(modelTags).where(eq(modelTags.modelId, modelId)),
|
||||
d.delete(modelFiles).where(eq(modelFiles.modelId, modelId)),
|
||||
d.delete(modelRevisions).where(eq(modelRevisions.modelId, modelId)),
|
||||
d.delete(models).where(eq(models.id, modelId)),
|
||||
]);
|
||||
}
|
||||
+97
-22
@@ -1,18 +1,20 @@
|
||||
import "server-only";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, localFolders, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from "@/lib/db/schema";
|
||||
import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder } from "@/lib/local-folders";
|
||||
import { hasOpenJob, queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { contentId } from "@/lib/update-diff";
|
||||
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy" | "hub_missing",
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -88,28 +90,100 @@ export async function addModel(input: {
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/** Remove a model from the library. Only allowed before anything was downloaded (for now). */
|
||||
export async function removeModel(id: string): Promise<void> {
|
||||
/**
|
||||
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
|
||||
* files that aren't part of the repo are kept); without, only the library entry goes and the
|
||||
* folder shows up under "Found in the models folder" again.
|
||||
*/
|
||||
export async function deleteModel(id: string, options: { deleteFiles: boolean }): Promise<{ queued: boolean }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
const [{ n }] = await d
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(jobs)
|
||||
.where(eq(jobs.modelId, id));
|
||||
if (model.status !== "pending" || n > 0) {
|
||||
throw new ModelError(
|
||||
"not_removable",
|
||||
"Only models that were never downloaded can be removed yet. Deleting downloaded models comes in a later milestone.",
|
||||
409,
|
||||
);
|
||||
if (await hasOpenJob(id)) {
|
||||
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
|
||||
}
|
||||
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
|
||||
const neverDownloaded = model.status === "pending" && n === 0;
|
||||
if (!options.deleteFiles || neverDownloaded) {
|
||||
await purgeModelRows(id);
|
||||
if (!neverDownloaded) await requestFolderScan();
|
||||
return { queued: false };
|
||||
}
|
||||
await d.batch([
|
||||
d.delete(modelTags).where(eq(modelTags.modelId, id)),
|
||||
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
|
||||
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
|
||||
d.delete(models).where(eq(models.id, id)),
|
||||
d.insert(jobs).values({ id: ulid(), modelId: id, kind: "delete", targetSha: model.pinnedSha }),
|
||||
d.update(models).set({ status: "deleting" }).where(eq(models.id, id)),
|
||||
]);
|
||||
return { queued: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a model to the newer commit found by the last Hub check: pin it (the old commit stays in
|
||||
* the revision history), refresh the file list, re-apply the selection rule and queue a download.
|
||||
* Unchanged files are kept; changed ones are downloaded again; files that are no longer selected are
|
||||
* deleted after the download succeeded.
|
||||
*/
|
||||
export async function applyUpdate(id: string): Promise<{ jobId: string; sha: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new ModelError("hub_missing", missing, 409);
|
||||
if (await hasOpenJob(id)) {
|
||||
throw new ModelError("busy", "A job for this model is still queued or running. Try again when it has finished.", 409);
|
||||
}
|
||||
const target = model.updateDiff?.sha;
|
||||
if (!target || target !== model.remoteSha || target === model.pinnedSha) {
|
||||
throw new ModelError("no_update", "No update available. Check the Hub again.", 409);
|
||||
}
|
||||
|
||||
const info = await getRepoInfo(model.repoId, target);
|
||||
const files = await listFiles(model.repoId, info.sha);
|
||||
const rule: SelectionRule = { include: model.includePatterns, exclude: model.excludePatterns };
|
||||
const existing = await d.select().from(modelFiles).where(eq(modelFiles.modelId, id));
|
||||
const byPath = new Map(existing.map((f) => [f.path, f]));
|
||||
const next = new Set(files.map((f) => f.path));
|
||||
|
||||
const now = new Date();
|
||||
const writes = [];
|
||||
for (const f of files) {
|
||||
const selected = isSelected(f.path, rule);
|
||||
const old = byPath.get(f.path);
|
||||
if (!old) {
|
||||
writes.push(d.insert(modelFiles).values({ modelId: id, path: f.path, size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected }));
|
||||
continue;
|
||||
}
|
||||
const same = contentId(old) === contentId(f);
|
||||
if (same && old.selected === selected) continue;
|
||||
writes.push(
|
||||
d
|
||||
.update(modelFiles)
|
||||
.set({ size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected, state: same ? old.state : "pending" })
|
||||
.where(eq(modelFiles.id, old.id)),
|
||||
);
|
||||
}
|
||||
// Files gone at the new commit: drop them (and their rows in old jobs' file lists).
|
||||
const gone = existing.filter((f) => !next.has(f.path));
|
||||
if (gone.length > 0) {
|
||||
const ids = gone.map((f) => f.id);
|
||||
writes.push(d.delete(jobFiles).where(inArray(jobFiles.modelFileId, ids)), d.delete(modelFiles).where(inArray(modelFiles.id, ids)));
|
||||
}
|
||||
// Selected before, not anymore (removed from the repo or no longer matching): delete after the download.
|
||||
const removePaths = existing.filter((f) => f.selected && (!next.has(f.path) || !isSelected(f.path, rule))).map((f) => f.path);
|
||||
|
||||
await d.batch([
|
||||
d
|
||||
.update(models)
|
||||
.set({ pinnedSha: info.sha, updateDiff: null, ...metadataColumns(info.metadata, model.authorAvatarUrl) })
|
||||
.where(eq(models.id, id)),
|
||||
d
|
||||
.update(modelRevisions)
|
||||
.set({ supersededAt: now })
|
||||
.where(and(eq(modelRevisions.modelId, id), isNull(modelRevisions.supersededAt))),
|
||||
d.insert(modelRevisions).values({ modelId: id, sha: info.sha }),
|
||||
...writes,
|
||||
]);
|
||||
const { jobId } = await queueDownload(id, "update", { removePaths });
|
||||
return { jobId, sha: info.sha };
|
||||
}
|
||||
|
||||
function chunk<T>(items: T[], size: number): T[][] {
|
||||
@@ -148,7 +222,8 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
|
||||
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
||||
|
||||
await d.batch([
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude }).where(eq(models.id, modelId)),
|
||||
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
|
||||
...changed.map((f) =>
|
||||
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { computeUpdateDiff, diffHasChanges } from "./update-diff";
|
||||
|
||||
const f = (path: string, oid: string, size = 10, lfs = true) => ({
|
||||
path,
|
||||
size,
|
||||
blobOid: `blob-${oid}`,
|
||||
lfsSha256: lfs ? `sha-${oid}` : null,
|
||||
});
|
||||
|
||||
describe("computeUpdateDiff", () => {
|
||||
const current = [f("Q4_K_M.gguf", "a"), f("mmproj-F16.gguf", "b"), f("config.json", "c", 1, false)];
|
||||
const rule = { include: ["Q4_K_M.gguf", "mmproj-F16.gguf", "*.json"], exclude: [] };
|
||||
|
||||
it("finds changed, added and removed selected files", () => {
|
||||
const next = [
|
||||
f("Q4_K_M.gguf", "a2", 12), // re-quantized
|
||||
f("config.json", "c", 1, false), // unchanged
|
||||
f("generation_config.json", "d", 1, false), // new, matches *.json
|
||||
f("Q8_0.gguf", "e"), // new, not selected
|
||||
];
|
||||
const d = computeUpdateDiff("new", current, next, rule, new Date(0));
|
||||
assert.deepEqual(d.changed, [{ path: "Q4_K_M.gguf", size: 12, oldSize: 10 }]);
|
||||
assert.deepEqual(d.added, [{ path: "generation_config.json", size: 1 }]);
|
||||
assert.deepEqual(d.removed, [{ path: "mmproj-F16.gguf", size: 10 }]);
|
||||
assert.ok(diffHasChanges(d));
|
||||
});
|
||||
|
||||
it("reports nothing when the selected files are identical", () => {
|
||||
const d = computeUpdateDiff("new", current, [...current, f("README.md", "r", 1, false)], rule);
|
||||
assert.ok(!diffHasChanges(d));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
// What updating a model to a newer commit would change in its selection. Pure; used by the worker
|
||||
// (update checks) and the web app (applying an update).
|
||||
|
||||
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
|
||||
import { isSelected, type SelectionRule } from "@/lib/selection";
|
||||
|
||||
type RepoFile = { path: string; size: number; blobOid: string | null; lfsSha256: string | null };
|
||||
|
||||
/** Content identity of a file: the LFS SHA-256, else the git blob SHA-1. */
|
||||
export const contentId = (f: { blobOid: string | null; lfsSha256: string | null }) => f.lfsSha256 ?? f.blobOid ?? "";
|
||||
|
||||
/**
|
||||
* Compare the currently selected files with the files the same selection rule picks at the new
|
||||
* commit: changed content, newly matching files, and selected files that are gone.
|
||||
*/
|
||||
export function computeUpdateDiff(sha: string, current: RepoFile[], next: RepoFile[], rule: SelectionRule, now = new Date()): UpdateDiff {
|
||||
const before = new Map(current.map((f) => [f.path, f]));
|
||||
const after = new Map(next.filter((f) => isSelected(f.path, rule)).map((f) => [f.path, f]));
|
||||
const changed: UpdateDiffFile[] = [];
|
||||
const added: UpdateDiffFile[] = [];
|
||||
const removed: UpdateDiffFile[] = [];
|
||||
for (const [path, f] of after) {
|
||||
const old = before.get(path);
|
||||
if (!old) added.push({ path, size: f.size });
|
||||
else if (contentId(old) !== contentId(f)) changed.push({ path, size: f.size, oldSize: old.size });
|
||||
}
|
||||
for (const [path, f] of before) if (!after.has(path)) removed.push({ path, size: f.size });
|
||||
const byPath = (a: UpdateDiffFile, b: UpdateDiffFile) => a.path.localeCompare(b.path);
|
||||
return { sha, changed: changed.sort(byPath), added: added.sort(byPath), removed: removed.sort(byPath), checkedAt: now.toISOString() };
|
||||
}
|
||||
|
||||
/** True if updating would change anything in the selection. */
|
||||
export const diffHasChanges = (d: UpdateDiff | null | undefined) =>
|
||||
!!d && d.changed.length + d.added.length + d.removed.length > 0;
|
||||
@@ -0,0 +1,107 @@
|
||||
// Delete a model: its files on disk, then its database rows.
|
||||
// Only files that belong to the repo (any revision we know of) and hf's .cache folder are removed;
|
||||
// anything else in the folder is kept and logged, and the folder stays if it isn't empty.
|
||||
|
||||
import { readdir, rm, rmdir } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, models } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { HF_CACHE_DIR, listLocalFiles, modelDir, removeLocalFile } from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
|
||||
/** Remove empty directories below `dir` (deepest first), then `dir` itself if empty. */
|
||||
async function removeEmptyDirs(dir: string): Promise<void> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) if (e.isDirectory()) await removeEmptyDirs(join(dir, e.name));
|
||||
await rmdir(dir).catch(() => {}); // fails if not empty, which is fine
|
||||
}
|
||||
|
||||
export class DeleteRunner implements Runner {
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
/** Every file path of the model's repo we know of. */
|
||||
private repoPaths: string[],
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
// Deleting is quick and shouldn't stop halfway; cancel and shutdown wait for it.
|
||||
cancel() {}
|
||||
interrupt() {}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const root = resolve(coreEnv().MODELS_DIR);
|
||||
const dir = modelDir(root, this.model.localPath);
|
||||
const deleted: string[] = [];
|
||||
try {
|
||||
const before = await listLocalFiles(dir);
|
||||
const sizes = new Map(before.map((f) => [f.path, f.size]));
|
||||
for (const path of this.repoPaths) if (await removeLocalFile(dir, path)) deleted.push(path);
|
||||
await rm(join(dir, HF_CACHE_DIR), { recursive: true, force: true });
|
||||
await rmdir(join(dir, ".cache")).catch(() => {});
|
||||
|
||||
const kept = (await listLocalFiles(dir)).map((f) => f.path);
|
||||
await removeEmptyDirs(dir);
|
||||
// The org folder too, if this was its last model (never MODELS_DIR itself).
|
||||
const parent = dirname(dir);
|
||||
if (parent !== root) await rmdir(parent).catch(() => {});
|
||||
|
||||
const bytes = deleted.reduce((s, p) => s + (sizes.get(p) ?? 0), 0);
|
||||
log.info(
|
||||
`deleted ${this.model.repoId}: ${deleted.length} file(s), ${formatBytes(bytes)}` +
|
||||
(kept.length > 0 ? `; kept ${kept.length} file(s) that aren't part of the repo: ${kept.slice(0, 5).join(", ")}` : ""),
|
||||
);
|
||||
// The job and its log go with the model; the worker log above is the record.
|
||||
await purgeModelRows(this.model.id);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.jobLog.system(`Failed after deleting ${deleted.length} file(s): ${message}`);
|
||||
await this.jobLog.close();
|
||||
const d = db();
|
||||
await d.batch([
|
||||
d
|
||||
.update(jobs)
|
||||
.set({ state: "failed", finishedAt: new Date(), errorCode: "unknown", errorMessage: message })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
...(deleted.length > 0
|
||||
? [
|
||||
d
|
||||
.update(modelFiles)
|
||||
.set({ state: "missing", checkedAt: new Date() })
|
||||
.where(and(eq(modelFiles.modelId, this.model.id), inArray(modelFiles.path, deleted))),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
await settleModelStatus(this.model.id);
|
||||
log.error(`job ${this.job.id}: deleting ${this.model.repoId} failed`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-1
@@ -1,10 +1,12 @@
|
||||
import { type ChildProcess, spawn } from "node:child_process";
|
||||
import { mkdir, statfs } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import {
|
||||
type JobErrorCode,
|
||||
type JobState,
|
||||
type ModelFileState,
|
||||
jobFiles,
|
||||
jobs,
|
||||
modelFiles,
|
||||
@@ -17,12 +19,15 @@ import {
|
||||
bytesOnDisk,
|
||||
type ExpectedFile,
|
||||
listIncomplete,
|
||||
fileSize,
|
||||
modelDir,
|
||||
removeLocalFile,
|
||||
removeStaleIncomplete,
|
||||
} from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
import { SpeedMeter } from "./speed";
|
||||
|
||||
const SAMPLE_MS = 1_000;
|
||||
@@ -45,6 +50,8 @@ type FileRow = {
|
||||
doneBytes: number;
|
||||
lfsSha256: string | null;
|
||||
blobOid: string | null;
|
||||
/** Last known state of the file (deep verify may have found a hash mismatch). */
|
||||
state: ModelFileState;
|
||||
};
|
||||
|
||||
type Outcome =
|
||||
@@ -52,7 +59,7 @@ type Outcome =
|
||||
| { state: "cancelled" | "interrupted"; message: string }
|
||||
| { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null };
|
||||
|
||||
export class DownloadRunner {
|
||||
export class DownloadRunner implements Runner {
|
||||
private child?: ChildProcess;
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private killTimer?: NodeJS.Timeout;
|
||||
@@ -74,6 +81,10 @@ export class DownloadRunner {
|
||||
return this.model.id;
|
||||
}
|
||||
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
/** User cancel: stop hf, keep completed files. */
|
||||
cancel() {
|
||||
this.stop("cancelled");
|
||||
@@ -144,6 +155,18 @@ export class DownloadRunner {
|
||||
this.jobLog.system(`Removed ${stale.count} partial file(s) from an earlier run (${formatBytes(stale.bytes)}).`);
|
||||
}
|
||||
|
||||
// hf skips a file whose metadata matches without looking at its content or size, so broken
|
||||
// files (wrong size, or a hash mismatch found by deep verify) have to go first.
|
||||
const broken: string[] = [];
|
||||
for (const f of this.files) {
|
||||
const size = await fileSize(join(dir, f.path));
|
||||
const wrong = size != null && (size !== f.expectedBytes || f.state === "hash_mismatch");
|
||||
if (wrong && (await removeLocalFile(dir, f.path))) broken.push(f.path);
|
||||
}
|
||||
if (broken.length > 0) {
|
||||
this.jobLog.system(`Deleted ${broken.length} broken file(s) so hf downloads them again: ${broken.slice(0, 5).join(", ")}${broken.length > 5 ? ", …" : ""}`);
|
||||
}
|
||||
|
||||
const initial = await this.sample(dir, expected);
|
||||
const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0);
|
||||
const doneCount = initial.filter((p) => p.complete).length;
|
||||
@@ -199,6 +222,12 @@ export class DownloadRunner {
|
||||
.join(", ")}${bad.length > 5 ? ", …" : ""}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Update: files the new revision no longer has (or that are no longer selected).
|
||||
const remove = (this.job.result?.removePaths ?? []).filter((p) => !this.files.some((f) => f.path === p));
|
||||
let removed = 0;
|
||||
for (const path of remove) if (await removeLocalFile(dir, path)) removed++;
|
||||
if (removed > 0) this.jobLog.system(`Deleted ${removed} file(s) that are no longer part of the selection: ${remove.slice(0, 5).join(", ")}`);
|
||||
return { state: "completed" };
|
||||
}
|
||||
|
||||
|
||||
@@ -109,3 +109,31 @@ export async function bytesOnDisk(
|
||||
}
|
||||
return { done: Math.min(partial, file.size), complete: false };
|
||||
}
|
||||
|
||||
/** Delete a downloaded file and hf's metadata/lock for it, so the next `hf download` fetches it again. */
|
||||
export async function removeLocalFile(dir: string, path: string): Promise<boolean> {
|
||||
const full = join(dir, path);
|
||||
const existed = (await fileSize(full)) != null;
|
||||
await rm(full, { force: true });
|
||||
await rm(join(dir, DOWNLOAD_DIR, `${path}.metadata`), { force: true });
|
||||
await rm(join(dir, DOWNLOAD_DIR, `${path}.lock`), { force: true });
|
||||
return existed;
|
||||
}
|
||||
|
||||
/** All files under `dir` (relative, "/"-separated), skipping hf's .cache and .git folders. */
|
||||
export async function listLocalFiles(dir: string): Promise<{ path: string; size: number }[]> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: { path: string; size: number }[] = [];
|
||||
for (const e of entries) {
|
||||
if (!e.isFile()) continue;
|
||||
const rel = join(e.parentPath, e.name).slice(dir.length + 1).split(sep).join("/");
|
||||
if (rel.startsWith(".cache/") || rel.startsWith(".git/")) continue;
|
||||
out.push({ path: rel, size: (await fileSize(join(dir, rel))) ?? 0 });
|
||||
}
|
||||
return out.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
+70
-29
@@ -7,13 +7,16 @@ import { promisify } from "node:util";
|
||||
import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { runMigrations } from "@/lib/db/migrate";
|
||||
import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DeleteRunner } from "./delete";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import type { Runner } from "./runner";
|
||||
import { scanModelsDir } from "./scan";
|
||||
import { VerifyRunner } from "./verify";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
const HEARTBEAT_MS = 5_000;
|
||||
@@ -30,7 +33,7 @@ const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
const instanceId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
const runners = new Map<string, DownloadRunner>();
|
||||
const runners = new Map<string, Runner>();
|
||||
let hfVersion: string | null = null;
|
||||
let stopping = false;
|
||||
|
||||
@@ -168,13 +171,19 @@ async function handleCancelRequests() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Claim the oldest queued download whose model has no running job. */
|
||||
async function claimNextJob() {
|
||||
/** Downloads are limited by MAX_CONCURRENT_DOWNLOADS; verify and delete jobs by this. */
|
||||
const MAX_LOCAL_JOBS = 2;
|
||||
const LOCAL_KINDS = ["verify", "deep_verify", "delete"] as const;
|
||||
|
||||
const running = (local: boolean) => [...runners.values()].filter((r) => (r.kind === "download") !== local).length;
|
||||
|
||||
/** Claim the oldest queued job of the given kinds whose model has no running job. */
|
||||
async function claimNextJob(kinds: readonly JobKind[]) {
|
||||
const busyModels = [...runners.values()].map((r) => r.modelId);
|
||||
const candidates = await db()
|
||||
.select({ id: jobs.id, modelId: jobs.modelId })
|
||||
.select({ id: jobs.id, modelId: jobs.modelId, kind: jobs.kind })
|
||||
.from(jobs)
|
||||
.where(and(eq(jobs.state, "queued"), eq(jobs.kind, "download"), isNull(jobs.cancelRequestedAt)))
|
||||
.where(and(eq(jobs.state, "queued"), inArray(jobs.kind, [...kinds]), isNull(jobs.cancelRequestedAt)))
|
||||
.orderBy(asc(jobs.createdAt))
|
||||
.limit(20);
|
||||
const next = candidates.find((c) => !busyModels.includes(c.modelId));
|
||||
@@ -182,12 +191,33 @@ async function claimNextJob() {
|
||||
|
||||
const [job] = await db()
|
||||
.update(jobs)
|
||||
.set({ state: "downloading", startedAt: new Date(), finishedAt: null, attempt: sql`${jobs.attempt} + 1` })
|
||||
.set({
|
||||
state: next.kind === "download" ? "downloading" : "verifying",
|
||||
startedAt: new Date(),
|
||||
finishedAt: null,
|
||||
attempt: sql`${jobs.attempt} + 1`,
|
||||
})
|
||||
.where(and(eq(jobs.id, next.id), eq(jobs.state, "queued")))
|
||||
.returning();
|
||||
return job ?? null;
|
||||
}
|
||||
|
||||
async function jobFileRows(jobId: string) {
|
||||
return db()
|
||||
.select({
|
||||
modelFileId: jobFiles.modelFileId,
|
||||
path: jobFiles.path,
|
||||
expectedBytes: jobFiles.expectedBytes,
|
||||
doneBytes: jobFiles.doneBytes,
|
||||
lfsSha256: modelFiles.lfsSha256,
|
||||
blobOid: modelFiles.blobOid,
|
||||
state: modelFiles.state,
|
||||
})
|
||||
.from(jobFiles)
|
||||
.innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId))
|
||||
.where(eq(jobFiles.jobId, jobId));
|
||||
}
|
||||
|
||||
async function startJob(job: typeof jobs.$inferSelect) {
|
||||
const model = await db().query.models.findFirst({ where: eq(models.id, job.modelId) });
|
||||
if (!model) {
|
||||
@@ -197,41 +227,47 @@ async function startJob(job: typeof jobs.$inferSelect) {
|
||||
.where(eq(jobs.id, job.id));
|
||||
return;
|
||||
}
|
||||
const files = await db()
|
||||
.select({
|
||||
modelFileId: jobFiles.modelFileId,
|
||||
path: jobFiles.path,
|
||||
expectedBytes: jobFiles.expectedBytes,
|
||||
doneBytes: jobFiles.doneBytes,
|
||||
lfsSha256: modelFiles.lfsSha256,
|
||||
blobOid: modelFiles.blobOid,
|
||||
})
|
||||
.from(jobFiles)
|
||||
.innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId))
|
||||
.where(eq(jobFiles.jobId, job.id));
|
||||
|
||||
await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id));
|
||||
const runner = new DownloadRunner(job, model, files);
|
||||
let runner: Runner;
|
||||
if (job.kind === "download") {
|
||||
const files = await jobFileRows(job.id);
|
||||
await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id));
|
||||
runner = new DownloadRunner(job, model, files);
|
||||
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
|
||||
} else {
|
||||
const repoPaths = (await db().select({ path: modelFiles.path }).from(modelFiles).where(eq(modelFiles.modelId, model.id))).map(
|
||||
(f) => f.path,
|
||||
);
|
||||
if (job.kind === "delete") {
|
||||
runner = new DeleteRunner(job, model, repoPaths);
|
||||
log.info(`job ${job.id}: deleting ${model.repoId}`);
|
||||
} else {
|
||||
runner = new VerifyRunner(job, model, await jobFileRows(job.id), new Set(repoPaths));
|
||||
log.info(`job ${job.id}: ${job.kind === "deep_verify" ? "deep verify" : "verify"} ${model.repoId}`);
|
||||
}
|
||||
}
|
||||
|
||||
runners.set(job.id, runner);
|
||||
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
|
||||
runner
|
||||
.run()
|
||||
.then(async () => {
|
||||
if (job.kind !== "download") return;
|
||||
// A failed download may mean the repo or commit is gone from the Hub; find out right away.
|
||||
const done = await db().query.jobs.findFirst({ columns: { state: true }, where: eq(jobs.id, job.id) });
|
||||
if (done?.state === "failed") await reportHubCheck(model, await checkHubAvailability(model));
|
||||
if (done?.state === "failed") reportHubCheck(model, await checkHub(model));
|
||||
})
|
||||
.catch((err) => log.error(`job ${job.id} crashed`, err))
|
||||
.finally(() => runners.delete(job.id));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hub availability: flags models whose repo or pinned commit disappeared from the Hub
|
||||
// Hub checks: repo/commit still there, newer commit on the tracked revision
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<typeof checkHubAvailability>>) {
|
||||
function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<typeof checkHub>>) {
|
||||
if (result.state === null) log.warn(`Hub check for ${model.repoId} failed: ${result.error}`);
|
||||
else if (result.state !== "available") log.warn(`${model.repoId}: ${result.state.replace("_", " ")} on the Hub (local files kept)`);
|
||||
else if (result.update) log.info(`${model.repoId}: update available (${result.update.sha.slice(0, 7)})`);
|
||||
}
|
||||
|
||||
let scanning = false;
|
||||
@@ -258,7 +294,7 @@ async function checkHubDue() {
|
||||
try {
|
||||
for (const model of await modelsDueForHubCheck(hours * 3_600_000)) {
|
||||
if (stopping) break;
|
||||
reportHubCheck(model, await checkHubAvailability(model));
|
||||
reportHubCheck(model, await checkHub(model));
|
||||
await sleep(1_000); // be gentle with the Hub API
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -275,8 +311,13 @@ async function tick() {
|
||||
try {
|
||||
await handleCancelRequests();
|
||||
const max = coreEnv().MAX_CONCURRENT_DOWNLOADS;
|
||||
while (runners.size < max && !stopping) {
|
||||
const job = await claimNextJob();
|
||||
while (running(false) < max && !stopping) {
|
||||
const job = await claimNextJob(["download"]);
|
||||
if (!job) break;
|
||||
await startJob(job);
|
||||
}
|
||||
while (running(true) < MAX_LOCAL_JOBS && !stopping) {
|
||||
const job = await claimNextJob(LOCAL_KINDS);
|
||||
if (!job) break;
|
||||
await startJob(job);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { JobKind } from "@/lib/db/schema";
|
||||
|
||||
/** A job the worker is executing (download, verify, delete). */
|
||||
export interface Runner {
|
||||
readonly jobId: string;
|
||||
readonly modelId: string;
|
||||
readonly kind: JobKind;
|
||||
/** User cancel. */
|
||||
cancel(): void;
|
||||
/** Worker shutdown; the job can be resumed later. */
|
||||
interrupt(): void;
|
||||
run(): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Verify a model's local files against the file list of its pinned commit.
|
||||
// verify: existence, size, and hf's recorded etag (fast)
|
||||
// deep_verify: additionally hashes every file: SHA-256 for LFS files, git blob SHA-1 for small
|
||||
// files, compared with the hashes from the Hub API (slow, with progress)
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type JobResult, jobFiles, jobs, type ModelFileState, modelFiles, models } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { fileSize, listLocalFiles, modelDir, readMetadata } from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
import { SpeedMeter } from "./speed";
|
||||
|
||||
const PROGRESS_MS = 1_000;
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
export type VerifyFile = { modelFileId: string; path: string; expectedBytes: number; lfsSha256: string | null; blobOid: string | null };
|
||||
|
||||
class Stopped extends Error {}
|
||||
|
||||
export class VerifyRunner implements Runner {
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
private files: VerifyFile[],
|
||||
/** Every path of the repo at the pinned commit (selected or not), to classify extra files. */
|
||||
private repoPaths: Set<string>,
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
cancel() {
|
||||
this.stopReason ??= "cancelled";
|
||||
}
|
||||
interrupt() {
|
||||
this.stopReason ??= "interrupted";
|
||||
}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const deep = this.job.kind === "deep_verify";
|
||||
const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath);
|
||||
const result: Required<Pick<JobResult, "checked" | "missing" | "sizeMismatch" | "hashMismatch" | "extra">> = {
|
||||
checked: 0,
|
||||
missing: [],
|
||||
sizeMismatch: [],
|
||||
hashMismatch: [],
|
||||
extra: [],
|
||||
};
|
||||
this.jobLog.system(
|
||||
`${deep ? "Deep verify (hashing every file)" : "Verify (existence, size, hf metadata)"}: ${this.files.length} selected file(s), ${formatBytes(this.job.totalBytes)} in ${dir}`,
|
||||
);
|
||||
|
||||
const speed = new SpeedMeter();
|
||||
let doneBytes = 0;
|
||||
let lastWrite = 0;
|
||||
const writeProgress = async (force = false) => {
|
||||
if (!force && Date.now() - lastWrite < PROGRESS_MS) return;
|
||||
lastWrite = Date.now();
|
||||
speed.add(Date.now(), doneBytes);
|
||||
const bps = speed.bytesPerSecond();
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ doneBytes, speedBps: bps == null ? null : Math.round(bps), etaSeconds: speed.eta(this.job.totalBytes - doneBytes) })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
await this.jobLog.flush();
|
||||
};
|
||||
|
||||
let failure: string | null = null;
|
||||
try {
|
||||
for (const f of this.files) {
|
||||
if (this.stopReason) throw new Stopped();
|
||||
const state = await this.check(dir, f, deep, async (n) => {
|
||||
doneBytes += n;
|
||||
await writeProgress();
|
||||
});
|
||||
if (!deep) doneBytes += f.expectedBytes;
|
||||
result.checked++;
|
||||
if (state === "missing") result.missing.push(f.path);
|
||||
if (state === "size_mismatch") result.sizeMismatch.push(f.path);
|
||||
if (state === "hash_mismatch") result.hashMismatch.push(f.path);
|
||||
if (state !== "present" && state !== "verified") this.jobLog.system(`${state.replace("_", " ")}: ${f.path}`);
|
||||
await this.markFile(f, state);
|
||||
await writeProgress();
|
||||
}
|
||||
|
||||
// Anything else in the folder: unselected repo files, or files that aren't in the repo at all.
|
||||
const selected = new Set(this.files.map((f) => f.path));
|
||||
for (const local of await listLocalFiles(dir)) {
|
||||
if (!selected.has(local.path)) result.extra.push({ ...local, inRepo: this.repoPaths.has(local.path) });
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Stopped)) failure = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const problems = result.missing.length + result.sizeMismatch.length + result.hashMismatch.length;
|
||||
if (this.stopReason) {
|
||||
this.jobLog.system(this.stopReason === "cancelled" ? "Cancelled by user." : "Interrupted by worker shutdown.");
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: this.stopReason, finishedAt: now, speedBps: null, etaSeconds: null, result })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
} else if (failure) {
|
||||
this.jobLog.system(`Failed: ${failure}`);
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "failed", finishedAt: now, speedBps: null, etaSeconds: null, errorCode: "unknown", errorMessage: failure, result })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
} else {
|
||||
const extraLine =
|
||||
result.extra.length > 0
|
||||
? ` ${result.extra.length} extra file(s) in the folder (${formatBytes(result.extra.reduce((s, e) => s + e.size, 0))}).`
|
||||
: "";
|
||||
this.jobLog.system(
|
||||
problems === 0
|
||||
? `All ${result.checked} file(s) OK${deep ? " (hashes match the Hub)" : ""}.${extraLine}`
|
||||
: `${problems} problem(s): ${result.missing.length} missing, ${result.sizeMismatch.length} size mismatch, ${result.hashMismatch.length} hash mismatch.${extraLine} Use Repair to download them again.`,
|
||||
);
|
||||
await db().batch([
|
||||
db()
|
||||
.update(jobs)
|
||||
.set({ state: "completed", finishedAt: now, speedBps: null, etaSeconds: 0, doneBytes: this.job.totalBytes, result })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
db().update(models).set({ lastVerifiedAt: now }).where(eq(models.id, this.model.id)),
|
||||
]);
|
||||
}
|
||||
await this.jobLog.close();
|
||||
await settleModelStatus(this.model.id);
|
||||
log.info(`job ${this.job.id} (${this.job.kind} ${this.model.repoId}) ${this.stopReason ?? (failure ? "failed" : "completed")}`);
|
||||
}
|
||||
|
||||
private async check(dir: string, f: VerifyFile, deep: boolean, onBytes: (n: number) => Promise<void>): Promise<ModelFileState> {
|
||||
const full = join(dir, f.path);
|
||||
const size = await fileSize(full);
|
||||
if (size == null) return "missing";
|
||||
if (size !== f.expectedBytes) return "size_mismatch";
|
||||
if (!deep) {
|
||||
// hf records the etag it downloaded; a different one means another version of the file.
|
||||
const meta = await readMetadata(dir, f.path);
|
||||
const etags = [f.lfsSha256, f.blobOid].filter(Boolean);
|
||||
return meta && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
}
|
||||
const actual = await this.hash(full, f, onBytes);
|
||||
const expected = f.lfsSha256 ?? f.blobOid;
|
||||
return expected && actual === expected ? "verified" : "hash_mismatch";
|
||||
}
|
||||
|
||||
/** SHA-256 of the content (LFS files) or the git blob SHA-1 (small files stored in git). */
|
||||
private hash(full: string, f: VerifyFile, onBytes: (n: number) => Promise<void>): Promise<string> {
|
||||
const h = f.lfsSha256 ? createHash("sha256") : createHash("sha1").update(`blob ${f.expectedBytes}\0`);
|
||||
return new Promise((resolve, reject) => {
|
||||
const stream = createReadStream(full, { highWaterMark: 8 * 1024 * 1024 });
|
||||
stream.on("data", (chunk) => {
|
||||
if (this.stopReason) {
|
||||
stream.destroy(new Stopped());
|
||||
return;
|
||||
}
|
||||
h.update(chunk);
|
||||
stream.pause();
|
||||
onBytes(chunk.length).then(
|
||||
() => stream.resume(),
|
||||
(err) => stream.destroy(err),
|
||||
);
|
||||
});
|
||||
stream.on("error", reject);
|
||||
stream.on("end", () => resolve(h.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
private async markFile(f: VerifyFile, state: ModelFileState) {
|
||||
const now = new Date();
|
||||
const ok = state === "present" || state === "verified";
|
||||
await db().batch([
|
||||
db().update(modelFiles).set({ state, checkedAt: now }).where(eq(modelFiles.id, f.modelFileId)),
|
||||
db()
|
||||
.update(jobFiles)
|
||||
.set({ state: ok ? "done" : "failed", doneBytes: ok ? f.expectedBytes : 0 })
|
||||
.where(and(eq(jobFiles.jobId, this.job.id), inArray(jobFiles.modelFileId, [f.modelFileId]))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user