"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(url: string, body: unknown): Promise { 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(null); const [result, setResult] = useState(null); const [checked, setChecked] = useState>(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("/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(); 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 (
{importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"} {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."}
setRepo(e.target.value)} placeholder="unsloth/Qwen3-8B-GGUF" autoComplete="off" spellCheck={false} required />
setRevision(e.target.value)} placeholder="main" spellCheck={false} />
{error && (

{error}

)}
{result && ( <> {result.repoId} {result.gated && gated ({result.gated}), access OK} {result.revision} →{" "} {shortSha(result.sha)} {" · "} {result.files.length} files · {formatBytes(result.files.reduce((s, f) => s + f.size, 0))} total {importFolder && !result.existingModelId && (

{present.length} of {selected.length} selected files are already on disk {" "} 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.`}

{notInRepo > 0 && (

{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.

)}
)} {result.existingModelId && (

This repo is already in the library.{" "} Open it

)} {groups.length > 0 && (
{groups.map(([name, g]) => { const on = g.paths.every((p) => checked.has(p)); return ( ); })}
)}
setIncludeText(e.target.value)} placeholder="*Q4_K_M*, *.json" spellCheck={false} className="font-mono" />
setExcludeText(e.target.value)} placeholder="*mmproj*" spellCheck={false} className="font-mono" />

Comma-separated globs, same rules as hf download --include/--exclude:{" "} * also matches /, a trailing / matches a whole folder. Selected = checked or matching an include pattern, minus excludes.

{tags.map((t) => ( ))} t.name)} onPick={(name, tag) => setTags((prev) => prev.some((x) => x.name.toLowerCase() === name.toLowerCase()) ? prev : [...prev, { name, color: tag?.color }], ) } />

Optional. Editable later on the model page.

File Size Storage {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 ( 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} /> 1 ? parts.map((f) => f.path).join("\n") : undefined}> {e.path} {e.totalParts > 1 && ( {e.totalParts} parts )} {excluded && (excluded)} {isRecommended && ( recommended )} {importFolder && } {formatBytes(e.size)} {parts[0].lfsSha256 ? "LFS" : "git"} ); })}
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)} {" "} selected {importFolder && · {formatBytes(toDownload)} to download} {freeBytes != null && ( ({formatBytes(freeBytes)} free on the models volume) )}
)}
); } /** Import mode: is this entry already in the folder (and the right size)? */ function DiskState({ parts, onDisk }: { parts: { path: string; size: number }[]; onDisk: Map }) { 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 ( {ok ? "on disk" : here.length < parts.length ? `${here.length} of ${parts.length} parts on disk` : "on disk, size differs"} ); }