Milestone (b): repo lookup and file selection

- Hub API client: resolve revision to SHA, paginated recursive file tree,
  gated-access probe, readable error mapping
- Add-model page with quant quick-select, fnmatch-compatible include/exclude
  globs, selection summary and free-space hint
- Models stored pinned to the reviewed SHA with full file list and selection rule
- Library list, model detail page, remove (never-downloaded models only)
- Worker reports MODELS_DIR free space; unit tests for selection logic

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 15:39:45 +02:00
1 parent 891e496157
commit 8f7ac60ccf
35 files changed
+2567 -19

No files matched your search

+3
View File
@@ -22,6 +22,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<Link href="/" className="hover:text-foreground">
Library
</Link>
<Link href="/models/new" className="hover:text-foreground">
Add model
</Link>
</nav>
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
+91
View File
@@ -0,0 +1,91 @@
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 { getModel } from "@/lib/library";
import { RemoveModelButton } from "./remove-model-button";
export const dynamic = "force-dynamic";
export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
const { id } = await params;
const data = await getModel(id);
if (!data) notFound();
const { model, files } = data;
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold break-all">{model.repoId}</h1>
<ModelStatusBadge status={model.status} />
<div className="ml-auto">{model.status === "pending" && <RemoveModelButton id={model.id} />}</div>
</div>
<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">
<dt className="text-muted-foreground">Hub</dt>
<dd>
<a
href={`https://huggingface.co/${model.repoId}/tree/${model.pinnedSha}`}
target="_blank"
rel="noreferrer"
className="underline"
>
huggingface.co/{model.repoId}
</a>
</dd>
<dt className="text-muted-foreground">Tracked revision</dt>
<dd className="font-mono">{model.trackedRevision}</dd>
<dt className="text-muted-foreground">Pinned SHA</dt>
<dd className="font-mono break-all">{model.pinnedSha}</dd>
<dt className="text-muted-foreground">Local path</dt>
<dd className="font-mono break-all">$MODELS_DIR/{model.localPath}</dd>
<dt className="text-muted-foreground">Include</dt>
<dd className="font-mono text-xs break-all">{model.includePatterns.join(", ") || "–"}</dd>
<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>
</dl>
</CardContent>
</Card>
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>
Selected files · {selected.length} · {formatBytes(totalBytes)}
</CardTitle>
<CardDescription>
{files.length - selected.length} other files in the repo are not selected.
</CardDescription>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>File</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>State</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{selected.map((f) => (
<TableRow key={f.id}>
<TableCell className="font-mono text-xs break-all whitespace-normal">{f.path}</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="text-sm text-muted-foreground">{f.state}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</div>
);
}
@@ -0,0 +1,57 @@
"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>
);
}
+343
View File
@@ -0,0 +1,343 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes, shortSha } from "@/lib/format";
import type { LookupResult } from "@/lib/hub/lookup";
import { escapeGlob, matchesAny, parsePatternList, quantGroup } from "@/lib/selection";
type ApiErrorBody = { error?: { code: string; message: string } };
async function postJson<T>(url: string, body: unknown): Promise<T> {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = (await res.json().catch(() => ({}))) as T & ApiErrorBody;
if (!res.ok) throw new Error(json.error?.message ?? `Request failed (${res.status})`);
return json;
}
export function AddModelForm({ freeBytes }: { freeBytes: number | null }) {
const router = useRouter();
const [repo, setRepo] = useState("");
const [revision, setRevision] = useState("main");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<LookupResult | null>(null);
const [checked, setChecked] = useState<Set<string>>(new Set());
const [includeText, setIncludeText] = useState("");
const [excludeText, setExcludeText] = useState("");
const [submitting, setSubmitting] = useState(false);
async function lookup(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
try {
const r = await postJson<LookupResult>("/api/hub/lookup", { repo, revision });
setResult(r);
setRevision(r.revision);
setChecked(new Set());
setIncludeText("");
setExcludeText("");
} catch (err) {
setResult(null);
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const files = useMemo(() => {
if (!result) return [];
return result.files.map((f) => {
const byPattern = matchesAny(f.path, includePatterns);
const excluded = matchesAny(f.path, excludePatterns);
return {
...f,
group: quantGroup(f.path),
byPattern,
excluded,
selected: (checked.has(f.path) || byPattern) && !excluded,
};
});
}, [result, checked, includePatterns, excludePatterns]);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
for (const f of files) {
if (!f.group) continue;
const g = m.get(f.group) ?? { paths: [], size: 0 };
g.paths.push(f.path);
g.size += f.size;
m.set(f.group, g);
}
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [files]);
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
function toggle(path: string, on: boolean) {
setChecked((prev) => {
const next = new Set(prev);
if (on) next.add(path);
else next.delete(path);
return next;
});
}
function toggleGroup(paths: string[]) {
setChecked((prev) => {
const next = new Set(prev);
const allOn = paths.every((p) => next.has(p));
for (const p of paths) {
if (allOn) next.delete(p);
else next.add(p);
}
return next;
});
}
async function addToLibrary() {
if (!result) return;
setSubmitting(true);
try {
const { id } = await postJson<{ id: string }>("/api/models", {
repoId: result.repoId,
revision: result.revision,
sha: result.sha,
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
exclude: excludePatterns,
});
toast.success(`${result.repoId} added to the library`);
router.push(`/models/${id}`);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
setSubmitting(false);
}
}
return (
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Hugging Face repository</CardTitle>
<CardDescription>Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={lookup} className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor="repo">Repo ID</Label>
<Input
id="repo"
value={repo}
onChange={(e) => setRepo(e.target.value)}
placeholder="unsloth/Qwen3-8B-GGUF"
autoComplete="off"
spellCheck={false}
required
/>
</div>
<div className="flex flex-col gap-1.5 sm:w-48">
<Label htmlFor="revision">Revision</Label>
<Input
id="revision"
value={revision}
onChange={(e) => setRevision(e.target.value)}
placeholder="main"
spellCheck={false}
/>
</div>
<Button type="submit" disabled={loading || !repo.trim()}>
{loading ? "Looking up…" : "Look up"}
</Button>
</form>
{error && (
<p role="alert" className="mt-3 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</p>
)}
</CardContent>
</Card>
{result && (
<>
<Card>
<CardHeader>
<CardTitle className="flex flex-wrap items-center gap-2">
<a
href={`https://huggingface.co/${result.repoId}`}
target="_blank"
rel="noreferrer"
className="hover:underline"
>
{result.repoId}
</a>
{result.gated && <Badge variant="outline">gated ({result.gated}), access OK</Badge>}
</CardTitle>
<CardDescription>
{result.revision} →{" "}
<code className="font-mono" title={result.sha}>
{shortSha(result.sha)}
</code>
{" · "}
{result.files.length} files · {formatBytes(result.files.reduce((s, f) => s + f.size, 0))} total
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{result.existingModelId && (
<p className="rounded-md bg-muted px-3 py-2 text-sm">
This repo is already in the library.{" "}
<Link href={`/models/${result.existingModelId}`} className="underline">
Open it
</Link>
</p>
)}
{groups.length > 0 && (
<div className="flex flex-col gap-1.5">
<Label>Quick select a quant</Label>
<div className="flex flex-wrap gap-1.5">
{groups.map(([name, g]) => {
const on = g.paths.every((p) => checked.has(p));
return (
<Button
key={name}
type="button"
size="sm"
variant={on ? "default" : "outline"}
onClick={() => toggleGroup(g.paths)}
title={g.paths.join("\n")}
>
{name}
<span className="text-xs opacity-70">{formatBytes(g.size)}</span>
</Button>
);
})}
</div>
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="include">Include patterns</Label>
<Input
id="include"
value={includeText}
onChange={(e) => setIncludeText(e.target.value)}
placeholder="*Q4_K_M*, *.json"
spellCheck={false}
className="font-mono"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="exclude">Exclude patterns</Label>
<Input
id="exclude"
value={excludeText}
onChange={(e) => setExcludeText(e.target.value)}
placeholder="*mmproj*"
spellCheck={false}
className="font-mono"
/>
</div>
<p className="text-xs text-muted-foreground sm:col-span-2">
Comma-separated globs, same rules as <code>hf download --include/--exclude</code>:{" "}
<code>*</code> also matches <code>/</code>, a trailing <code>/</code> matches a whole
folder. Selected = checked or matching an include pattern, minus excludes.
</p>
</div>
</CardContent>
</Card>
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10" />
<TableHead>File</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden w-20 sm:table-cell">Storage</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{files.map((f) => (
<TableRow key={f.path} data-state={f.selected ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={f.selected}
disabled={f.byPattern || f.excluded}
onCheckedChange={(v) => toggle(f.path, v === true)}
aria-label={`Select ${f.path}`}
title={
f.excluded
? "Excluded by a pattern"
: f.byPattern
? "Selected by an include pattern"
: undefined
}
/>
</TableCell>
<TableCell className="font-mono text-xs break-all whitespace-normal">
{f.path}
{f.excluded && <span className="ml-2 text-muted-foreground">(excluded)</span>}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{f.lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
<div className="sticky bottom-0 -mx-4 border-t bg-background/95 px-4 py-3 backdrop-blur">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
{selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{freeBytes != null && (
<span className={notEnoughSpace ? "ml-2 text-destructive" : "ml-2 text-muted-foreground"}>
({formatBytes(freeBytes)} free on the models volume)
</span>
)}
</div>
<div className="ml-auto flex gap-2">
<Button type="button" variant="ghost" onClick={() => setChecked(new Set())}>
Clear
</Button>
<Button
type="button"
onClick={addToLibrary}
disabled={selected.length === 0 || submitting || !!result.existingModelId}
>
{submitting ? "Adding…" : "Add to library"}
</Button>
</div>
</div>
</div>
</>
)}
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { getWorkerStatus } from "@/lib/worker-status";
import { AddModelForm } from "./add-model-form";
export const dynamic = "force-dynamic";
export default async function AddModelPage() {
const worker = await getWorkerStatus();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Add model</h1>
<AddModelForm freeBytes={worker.online ? worker.modelsDirFreeBytes : null} />
</div>
);
}
+67 -8
View File
@@ -1,15 +1,74 @@
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";
export const dynamic = "force-dynamic";
export default async function LibraryPage() {
const rows = await listLibrary();
export default function LibraryPage() {
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Library</h1>
<Card>
<CardHeader>
<CardTitle>No models yet</CardTitle>
<CardDescription>Adding models from Hugging Face comes in the next milestone.</CardDescription>
</CardHeader>
</Card>
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Library</h1>
<Link href="/models/new" className={buttonVariants()}>
Add model
</Link>
</div>
{rows.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>No models yet</CardTitle>
<CardDescription>Add a Hugging Face repo to get started.</CardDescription>
</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>
)}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { handleApiError } from "@/lib/api-errors";
import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup";
const Body = z.object({
repo: z.string().trim().min(1),
revision: z.string().trim().optional(),
});
/** Resolve a repo + revision to a commit SHA and list its files with sizes. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
const { repoId, revision: urlRevision } = normalizeRepoInput(body.repo);
const revision = body.revision || urlRevision || "main";
return NextResponse.json(await lookupRepo(repoId, revision));
} catch (err) {
return handleApiError(err);
}
});
+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 { ModelError, removeModel } from "@/lib/models";
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 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
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 { addModel, ModelError } from "@/lib/models";
const Body = z.object({
repoId: z.string().regex(REPO_ID_RE),
revision: z.string().trim().min(1).max(255),
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),
});
/** Add a model to the library, pinned to the SHA the user reviewed. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
const { id } = await addModel({
repoId: body.repoId,
revision: body.revision,
sha: body.sha,
rule: { include: body.include, exclude: body.exclude },
});
return NextResponse.json({ id }, { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});