Move "Add model" into the library page

The add form now opens inline from the library instead of living on its own
page with a separate menu entry. After adding, the panel closes and the new
model's download progress shows in the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 17:06:09 +02:00
1 parent 49440154a2
commit c7cb6ed433
6 files changed
+53 -42

No files matched your search

+348
View File
@@ -0,0 +1,348 @@
"use client";
import Link from "next/link";
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,
onAdded,
}: {
freeBytes: number | null;
onAdded: (modelId: string) => void;
}) {
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, download queued`);
onAdded(id);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
} finally {
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 & download"}
</Button>
</div>
</div>
</div>
</>
)}
</div>
);
}