Milestone (c): worker and downloads with live progress

- Worker queue with per-model exclusivity and MAX_CONCURRENT_DOWNLOADS,
  spawns `hf download --revision <sha> --local-dir ... --include <exact paths>`
  with HF_TOKEN via env only
- Progress from bytes on disk (final + .incomplete files matched by etag),
  per job and per file, with speed and ETA; post-download size/etag check
- Job logs (sanitized), cancel, graceful interrupt on shutdown,
  partial-file cleanup (hf 2.1.1 does not resume partials)
- Single-worker DB lease, free-space check
- SSE live updates for library, model and job pages
- Dockerfile + compose.yaml (web, worker, data/models volumes)
- HF_HUB_DISABLE_XET default on for measurable progress

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 16:57:12 +02:00
1 parent 8f7ac60ccf
commit 49440154a2
42 files changed
+2974 -110

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
"use client";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { cancelJob } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
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 type { JobSnapshot } from "@/lib/jobs";
const OPEN = ["queued", "downloading", "verifying"];
export function JobLive({ initial }: { initial: JobSnapshot }) {
const { snapshot, logs } = useLive({ job: initial.id }, true);
const job = snapshot?.jobs[0] ?? initial;
const files = snapshot?.files ?? [];
const open = OPEN.includes(job.state);
const [busy, setBusy] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
const [follow, setFollow] = useState(true);
useEffect(() => {
if (follow && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
}, [logs, follow]);
// Tick once per second while running so the duration keeps counting.
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (job.finishedAt != null) return;
const t = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(t);
}, [job.finishedAt]);
const duration = job.startedAt != null ? ((job.finishedAt ?? now) - job.startedAt) / 1000 : null;
return (
<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} ·{" "}
<Link href={`/models/${job.modelId}`} className="hover:underline">
{job.repoId}
</Link>
</h1>
{open && (
<Button
className="ml-auto"
variant="destructive"
size="sm"
disabled={busy || job.cancelRequested}
onClick={async () => {
setBusy(true);
await cancelJob(job.id);
setBusy(false);
}}
>
{job.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
)}
</div>
<Card>
<CardContent className="flex flex-col gap-3">
<JobProgress job={job} />
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 text-sm">
<dt className="text-muted-foreground">Created</dt>
<dd><LocalTime value={job.createdAt} /></dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={job.startedAt} />
{job.attempt > 1 ? ` (attempt ${job.attempt})` : ""}
</dd>
<dt className="text-muted-foreground">Finished</dt>
<dd><LocalTime value={job.finishedAt} /></dd>
<dt className="text-muted-foreground">Duration</dt>
<dd>{formatDuration(duration)}</dd>
{job.exitCode != null && (
<>
<dt className="text-muted-foreground">Exit code</dt>
<dd className="font-mono">{job.exitCode}</dd>
</>
)}
</dl>
{job.errorMessage && (
<pre className="rounded-md bg-destructive/10 px-3 py-2 text-xs whitespace-pre-wrap text-destructive">
{job.errorMessage}
</pre>
)}
</CardContent>
</Card>
{files.length > 0 && (
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>Files</CardTitle>
</CardHeader>
<JobFilesTable files={files} />
</Card>
)}
<Card className="gap-2">
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Log</CardTitle>
<div className="flex items-center gap-3 text-sm">
<label className="flex items-center gap-1.5 text-muted-foreground">
<input type="checkbox" checked={follow} onChange={(e) => setFollow(e.target.checked)} />
Follow
</label>
<a href={`/api/jobs/${job.id}/log`} className="underline">
Download full log
</a>
</div>
</CardHeader>
<CardContent>
<div
ref={logRef}
className="h-96 overflow-auto rounded-md bg-muted/50 p-3 font-mono text-xs leading-relaxed"
>
{logs.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
logs.map((l) => (
<div
key={l.id}
className={
l.stream === "stderr"
? "text-amber-700 dark:text-amber-400"
: l.stream === "system"
? "text-sky-700 dark:text-sky-400"
: undefined
}
>
<span className="text-muted-foreground select-none">
{new Date(l.ts).toLocaleTimeString("en-GB")}{" "}
</span>
<span className="whitespace-pre-wrap break-all">{l.line}</span>
</div>
))
)}
</div>
</CardContent>
</Card>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { notFound } from "next/navigation";
import { getJob } from "@/lib/jobs";
import { JobLive } from "./job-live";
export const dynamic = "force-dynamic";
export default async function JobPage({ params }: PageProps<"/jobs/[id]">) {
const { id } = await params;
const job = await getJob(id);
if (!job) notFound();
return <JobLive initial={job} />;
}
+75
View File
@@ -0,0 +1,75 @@
"use client";
import Link from "next/link";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import { formatBytes, shortSha } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
const OPEN = ["queued", "downloading", "verifying"];
export function LibraryTable({ rows }: { rows: LibraryRow[] }) {
const { snapshot } = useLive();
const openJobs = new Map<string, JobSnapshot>();
for (const j of snapshot?.jobs ?? []) {
if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j);
}
return (
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Repository</TableHead>
<TableHead>Selection</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((r) => {
const job = openJobs.get(r.id);
return (
<TableRow key={r.id}>
<TableCell className="font-medium">
<Link href={`/models/${r.id}`} className="hover:underline">
{r.repoId}
</Link>
</TableCell>
<TableCell className="text-sm">
{r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} files`}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell>
<code className="font-mono text-xs" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
</TableCell>
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
<LocalTime value={r.downloadedAt} />
</TableCell>
<TableCell>
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<ModelStatusBadge status={r.status} />
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
);
}
+136
View File
@@ -0,0 +1,136 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { cancelJob, startDownload } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import type { JobSnapshot } from "@/lib/jobs";
const OPEN = ["queued", "downloading", "verifying"];
export function ModelLive({ modelId, status }: { modelId: string; status: ModelStatus }) {
const { snapshot } = useLive({ model: modelId });
const [busy, setBusy] = useState(false);
const jobs = snapshot?.jobs ?? [];
const latest = jobs[0] as JobSnapshot | undefined;
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const workerOffline = snapshot && !snapshot.worker.online;
async function run(fn: () => Promise<void>) {
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
}
return (
<>
<Card>
<CardHeader>
<CardTitle className="flex flex-wrap items-center gap-2">
Download
{latest && <JobStateBadge job={latest} />}
</CardTitle>
<CardDescription>
{open
? open.state === "queued"
? workerOffline
? "Queued, but the worker is offline."
: "Queued, waiting for a free download slot."
: "Running in the background; you can close this page."
: status === "ready"
? "All selected files are present."
: "Downloads the selected files at the pinned SHA."}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{latest && !(latest.state === "completed" && status === "ready") && <JobProgress job={latest} compact />}
{latest?.errorMessage && latest.state === "failed" && (
<pre className="rounded-md bg-destructive/10 px-3 py-2 text-xs whitespace-pre-wrap text-destructive">
{latest.errorMessage}
</pre>
)}
<div className="flex flex-wrap gap-2">
{open ? (
<Button
variant="destructive"
size="sm"
disabled={busy || open.cancelRequested}
onClick={() => run(() => cancelJob(open.id))}
>
{open.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
status !== "ready" &&
snapshot && (
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
{latest ? "Download again" : "Download"}
</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"
>
View log
</Link>
)}
</div>
</CardContent>
{open && snapshot && snapshot.files.length > 0 && <JobFilesTable files={snapshot.files} />}
</Card>
{jobs.length > 0 && (
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>Jobs</CardTitle>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>Started</TableHead>
<TableHead>Kind</TableHead>
<TableHead>State</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden sm:table-cell">Finished</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<Link href={`/jobs/${j.id}`} className="hover:underline">
<LocalTime value={j.startedAt ?? j.createdAt} />
</Link>
</TableCell>
<TableCell className="text-sm">
{j.kind}
{j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""}
</TableCell>
<TableCell>
<JobStateBadge job={j} />
</TableCell>
<TableCell className="text-right text-sm tabular-nums">{formatBytes(j.totalBytes)}</TableCell>
<TableCell className="hidden text-sm text-muted-foreground sm:table-cell">
<LocalTime value={j.finishedAt} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
)}
</>
);
}
+6 -3
View File
@@ -2,8 +2,10 @@ import { notFound } from "next/navigation";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes, formatDate } from "@/lib/format";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { getModel } from "@/lib/library";
import { ModelLive } from "./model-live";
import { RemoveModelButton } from "./remove-model-button";
export const dynamic = "force-dynamic";
@@ -27,7 +29,6 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
<Card>
<CardHeader>
<CardTitle>Details</CardTitle>
<CardDescription>Downloading starts in the next milestone.</CardDescription>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm">
@@ -53,11 +54,13 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
<dt className="text-muted-foreground">Exclude</dt>
<dd className="font-mono text-xs break-all">{model.excludePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Added</dt>
<dd>{formatDate(model.createdAt)}</dd>
<dd><LocalTime value={model.createdAt} /></dd>
</dl>
</CardContent>
</Card>
<ModelLive modelId={model.id} status={model.status} />
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>
+2 -2
View File
@@ -126,7 +126,7 @@ export function AddModelForm({ freeBytes }: { freeBytes: number | null }) {
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
exclude: excludePatterns,
});
toast.success(`${result.repoId} added to the library`);
toast.success(`${result.repoId} added, download queued`);
router.push(`/models/${id}`);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
@@ -331,7 +331,7 @@ export function AddModelForm({ freeBytes }: { freeBytes: number | null }) {
onClick={addToLibrary}
disabled={selected.length === 0 || submitting || !!result.existingModelId}
>
{submitting ? "Adding…" : "Add to library"}
{submitting ? "Adding…" : "Add & download"}
</Button>
</div>
</div>
+2 -43
View File
@@ -1,10 +1,8 @@
import Link from "next/link";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes, formatDate, shortSha } from "@/lib/format";
import { listLibrary } from "@/lib/library";
import { LibraryTable } from "./library-table";
export const dynamic = "force-dynamic";
@@ -28,46 +26,7 @@ export default async function LibraryPage() {
</CardHeader>
</Card>
) : (
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Repository</TableHead>
<TableHead>Selection</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((r) => (
<TableRow key={r.id}>
<TableCell className="font-medium">
<Link href={`/models/${r.id}`} className="hover:underline">
{r.repoId}
</Link>
</TableCell>
<TableCell className="text-sm">
{r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} files`}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell>
<code className="font-mono text-xs" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
</TableCell>
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
{formatDate(r.downloadedAt)}
</TableCell>
<TableCell>
<ModelStatusBadge status={r.status} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
<LibraryTable rows={rows} />
)}
</div>
);
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError, requestCancel } from "@/lib/jobs";
export const POST = withAuth<RouteContext<"/api/jobs/[id]/cancel">>(async (_req, { params }) => {
const { id } = await params;
try {
await requestCancel(id);
return NextResponse.json({ ok: true }, { status: 202 });
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+16
View File
@@ -0,0 +1,16 @@
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { fullJobLog, getJob } from "@/lib/jobs";
/** Full job log as a plain-text download. */
export const GET = withAuth<RouteContext<"/api/jobs/[id]/log">>(async (_req, { params }) => {
const { id } = await params;
const job = await getJob(id);
if (!job) return apiError(404, "not_found", "Job not found.");
return new Response(await fullJobLog(id), {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Content-Disposition": `attachment; filename="job-${id}.log"`,
},
});
});
+15
View File
@@ -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";
/** Queue a download of the model's selected files at its pinned SHA. */
export const POST = withAuth<RouteContext<"/api/models/[id]/download">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await queueDownload(id), { status: 201 });
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+5 -2
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
import { queueDownload } from "@/lib/jobs";
import { addModel, ModelError } from "@/lib/models";
const Body = z.object({
@@ -11,9 +12,10 @@ const Body = z.object({
sha: z.string().regex(SHA_RE, "must be a full 40-character commit SHA"),
include: z.array(z.string().min(1).max(1024)).max(10_000),
exclude: z.array(z.string().min(1).max(1024)).max(1_000),
download: z.boolean().default(true),
});
/** Add a model to the library, pinned to the SHA the user reviewed. */
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
@@ -23,7 +25,8 @@ export const POST = withAuth(async (req) => {
sha: body.sha,
rule: { include: body.include, exclude: body.exclude },
});
return NextResponse.json({ id }, { status: 201 });
const job = body.download ? await queueDownload(id) : null;
return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
+97
View File
@@ -0,0 +1,97 @@
import { withAuth } from "@/lib/api-auth";
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
import { getWorkerStatus } from "@/lib/worker-status";
export const dynamic = "force-dynamic";
const INTERVAL_MS = 1_000;
const KEEPALIVE_MS = 15_000;
/**
* Server-Sent Events with live job state, polled from the DB once per second.
* ?model=<id> jobs of one model (+ files of its newest job)
* ?job=<id> one job with per-file progress and incremental log lines
* (none) open and recently finished jobs (library view)
* Events: "snapshot" (only when something changed) and "logs" (new lines).
*/
export const GET = withAuth(async (req) => {
const url = new URL(req.url);
const modelId = url.searchParams.get("model");
const jobId = url.searchParams.get("job");
let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0;
const encoder = new TextEncoder();
const signal = req.signal;
const stream = new ReadableStream({
async start(controller) {
let last = "";
let lastWrite = Date.now();
const write = (chunk: string) => {
controller.enqueue(encoder.encode(chunk));
lastWrite = Date.now();
};
const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
try {
write("retry: 3000\n\n");
while (!signal.aborted) {
const snapshot = await buildSnapshot(modelId, jobId);
const serialized = JSON.stringify(snapshot);
if (serialized !== last) {
send("snapshot", snapshot);
last = serialized;
}
if (jobId) {
const lines = await listJobLogs(jobId, logCursor);
if (lines.length > 0) {
logCursor = lines[lines.length - 1].id;
send("logs", lines);
}
}
if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n");
await sleep(INTERVAL_MS, signal);
}
} catch {
// client went away or the stream was closed
} finally {
try {
controller.close();
} catch {}
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
});
async function buildSnapshot(modelId: string | null, jobId: string | null) {
const worker = await getWorkerStatus();
if (jobId) {
const job = await getJob(jobId);
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
}
if (modelId) {
const jobs = await listModelJobs(modelId);
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
return { worker, jobs, files };
}
return { worker, jobs: await listLiveJobs(), files: [] };
}
function sleep(ms: number, signal: AbortSignal) {
return new Promise<void>((resolve) => {
const t = setTimeout(resolve, ms);
signal.addEventListener("abort", () => {
clearTimeout(t);
resolve();
});
});
}