Files
Kaname/src/app/(app)/add-model-form.tsx
T
Pascal LinxweilerandClaude Opus 5.5 0247f257fb Recommended files with a quant; floating selection bar
Picking model weights in Add model or Download more also selects the
files that usually go with them (chat template, MTP head, mmproj, ...),
shown in a strip where each can be unchecked. Variants are matched by
quant, otherwise the best single one; kinds already selected aren't
added twice. Which kinds is set in Settings -> Downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:10:53 +02:00

498 lines
21 KiB
TypeScript

"use client";
import { XIcon } from "lucide-react";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { TagBadge } from "@/components/tag-badge";
import { TagPicker } from "@/components/tag-picker";
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 { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
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;
}
/** A folder from the models folder to import (found by the worker's scan). */
export type ImportFolder = { path: string; commit: string | null; files: { path: string; size: number }[]; fileCount: number };
export function AddModelForm({
freeBytes,
onAdded,
importFolder,
}: {
freeBytes: number | null;
onAdded: (modelId: string) => void;
/** Import mode: look up this folder's repo and preselect the files that are already there. */
importFolder?: ImportFolder;
}) {
const [repo, setRepo] = useState(importFolder?.path ?? "");
const [revision, setRevision] = useState(importFolder?.commit ?? "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);
const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]);
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const repoFiles = useMemo(() => result?.files ?? [], [result]);
const isExcluded = useCallback((path: string) => matchesAny(path, excludePatterns), [excludePatterns]);
// Picked by checkbox or include pattern; recommended companions come on top.
const picked = useMemo(
() => repoFiles.filter((f) => (checked.has(f.path) || matchesAny(f.path, includePatterns)) && !isExcluded(f.path)).map((f) => f.path),
[repoFiles, checked, includePatterns, isExcluded],
);
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(
repoFiles,
picked,
{ isExcluded },
);
// Local files of the imported folder by path.
const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]);
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);
// Import: preselect every repo file that's already in the folder.
setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path)));
resetRecommended();
setIncludeText("");
setExcludeText("");
setTags([]);
} catch (err) {
setResult(null);
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}
const autoLookup = useRef(false);
useEffect(() => {
if (importFolder && !autoLookup.current) {
autoLookup.current = true;
void lookup();
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported
}, [importFolder]);
const files = useMemo(() => {
const pickedSet = new Set(picked);
return repoFiles.map((f) => {
const byPattern = matchesAny(f.path, includePatterns);
const excluded = isExcluded(f.path);
return {
...f,
group: quantGroup(f.path),
byPattern,
excluded,
recommended: recAll.includes(f.path),
selected: pickedSet.has(f.path) || recActive.has(f.path),
};
});
}, [repoFiles, picked, includePatterns, isExcluded, recAll, recActive]);
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);
// Split files are one row; its checkbox covers all parts.
const entries = useMemo(() => groupSplitFiles(files), [files]);
const selectedEntries = entries.filter((e) => e.parts.every((f) => f.selected)).length;
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
// Files already on disk with the right size are verified by hf, not downloaded again.
const present = selected.filter((f) => onDisk.get(f.path) === f.size);
const toDownload = totalBytes - present.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && toDownload > freeBytes;
const repoPaths = useMemo(() => new Set(result?.files.map((f) => f.path)), [result]);
const sizeDiffers = selected.filter((f) => onDisk.has(f.path) && onDisk.get(f.path) !== f.size).length;
const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0;
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setChecked((prev) => {
const next = new Set(prev);
for (const path of paths) {
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, ...[...new Set([...checked, ...recActive])].sort().map(escapeGlob)],
exclude: excludePatterns,
tags: tags.map((t) => t.name),
localPath: importFolder?.path,
});
toast.success(importFolder ? `${result.repoId} imported, verifying files` : `${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>{importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"}</CardTitle>
<CardDescription>
{importFolder
? `The folder's files are matched against this Hub repo${importFolder.commit ? " at the commit hf recorded when it downloaded them" : ""}. Change the repo or revision if they don't fit.`
: "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">
{importFolder && !result.existingModelId && (
<div className="rounded-md bg-muted px-3 py-2 text-sm">
<p>
<span className="font-medium">
{present.length} of {selected.length} selected files are already on disk
</span>{" "}
and are verified by hash (hf only downloads files that are missing or different).
{sizeDiffers > 0 && ` ${sizeDiffers} differ in size and will be downloaded again.`}
</p>
{notInRepo > 0 && (
<p className="mt-1 text-muted-foreground">
{notInRepo} file{notInRepo === 1 ? " in the folder isn't" : "s in the folder aren't"} part of the repo at this
commit; {notInRepo === 1 ? "it stays" : "they stay"} untouched.
</p>
)}
</div>
)}
{result.existingModelId && (
<p className="rounded-md bg-muted px-3 py-2 text-sm">
This repo is already in the library.{" "}
<Link href={`/${result.repoId}`} 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>
)}
<RecommendedStrip files={repoFiles} paths={recAll} active={recActive} onToggle={toggle} />
<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>
<div className="flex flex-col gap-1.5">
<Label>Tags</Label>
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.name.toLowerCase()} name={t.name} color={t.color}>
<button
type="button"
aria-label={`Remove tag ${t.name}`}
onClick={() => setTags((prev) => prev.filter((x) => x !== t))}
className="opacity-60 hover:opacity-100"
>
<XIcon className="size-3" />
</button>
</TagBadge>
))}
<TagPicker
exclude={tags.map((t) => t.name)}
onPick={(name, tag) =>
setTags((prev) =>
prev.some((x) => x.name.toLowerCase() === name.toLowerCase())
? prev
: [...prev, { name, color: tag?.color }],
)
}
/>
</div>
<p className="text-xs text-muted-foreground">Optional. Editable later on the model page.</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>
{entries.map((e) => {
const parts = e.parts;
const all = parts.every((f) => f.selected);
const some = !all && parts.some((f) => f.selected);
const byPattern = parts.every((f) => f.byPattern);
const excluded = parts.every((f) => f.excluded);
const isRecommended = parts.every((f) => f.recommended);
return (
<TableRow key={e.path} data-state={all ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={all}
indeterminate={some}
disabled={byPattern || excluded}
onCheckedChange={(v) => toggle(parts.map((f) => f.path), v === true)}
aria-label={`Select ${e.path}`}
title={excluded ? "Excluded by a pattern" : byPattern ? "Selected by an include pattern" : undefined}
/>
</TableCell>
<TableCell className="whitespace-normal">
<span className="flex items-center gap-2" title={e.totalParts > 1 ? parts.map((f) => f.path).join("\n") : undefined}>
<FileRoleBadge path={e.path} />
<span className="font-mono text-xs break-all">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
{excluded && <span className="text-xs text-muted-foreground">(excluded)</span>}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
{importFolder && <DiskState parts={parts} onDisk={onDisk} />}
</span>
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(e.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{parts[0].lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
<div className="sticky bottom-3 z-10 rounded-xl bg-card/95 px-4 py-3 text-card-foreground shadow-lg ring-1 ring-foreground/10 backdrop-blur">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{importFolder && <span className="text-muted-foreground"> · {formatBytes(toDownload)} to download</span>}
{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());
resetRecommended();
}}>
Clear
</Button>
<Button
type="button"
onClick={addToLibrary}
disabled={selected.length === 0 || submitting || !!result.existingModelId}
>
{submitting ? "Adding…" : importFolder ? "Import & verify" : "Add & download"}
</Button>
</div>
</div>
</div>
</>
)}
</div>
);
}
/** Import mode: is this entry already in the folder (and the right size)? */
function DiskState({ parts, onDisk }: { parts: { path: string; size: number }[]; onDisk: Map<string, number> }) {
const here = parts.filter((f) => onDisk.has(f.path));
if (here.length === 0) return null;
const ok = here.every((f) => onDisk.get(f.path) === f.size) && here.length === parts.length;
return (
<span
className={
ok
? "shrink-0 rounded border border-emerald-500/30 bg-emerald-500/10 px-1 text-[10px] leading-4 text-emerald-700 dark:text-emerald-300"
: "shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300"
}
>
{ok ? "on disk" : here.length < parts.length ? `${here.length} of ${parts.length} parts on disk` : "on disk, size differs"}
</span>
);
}