Download more, file labels, split-file grouping, settings for labels and tags

- Files tab: "Download more" adds files to a model's selection and queues them
- Colored file labels (Model, MTP, Vision/mmproj, imatrix, Config, …)
- Split GGUF/safetensors parts shown and selected as one entry everywhere
- Settings page with a Labels section: file label names/colors, tag
  rename/recolor/delete; new settings table and tags.color
- Quants only count model weights

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 20:42:03 +02:00
1 parent 5211ec9064
commit df18415e02
34 files changed
+2256 -132

No files matched your search

+4 -2
View File
@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { groupJobFiles } from "@/lib/file-groups";
import { formatBytes, percent } from "@/lib/format";
const OPEN = ["queued", "downloading", "verifying"];
@@ -19,7 +20,7 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod
const [busy, setBusy] = useState(false);
const latest = snapshot?.jobs[0];
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const files = open ? (snapshot?.files ?? []) : [];
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
async function run(fn: () => Promise<void>) {
setBusy(true);
@@ -57,10 +58,11 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod
{files.length > 0 && (
<ul className="flex flex-col gap-1.5">
{files.map((f) => (
<li key={f.modelFileId} className="flex flex-col gap-1">
<li key={f.path} className="flex flex-col gap-1">
<div className="flex justify-between gap-2 text-xs">
<span className="truncate font-mono" title={f.path}>
{f.path}
{f.parts > 1 && <span className="text-muted-foreground"> · {f.parts} parts</span>}
</span>
<span className="shrink-0 text-muted-foreground tabular-nums">{formatBytes(f.expectedBytes)}</span>
</div>
@@ -0,0 +1,214 @@
"use client";
import { PlusIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
type Candidate = { path: string; size: number };
/**
* Files tab header: selection summary + on-disk progress, and a "Download more" panel to add
* files that aren't selected yet.
*/
export function FilesHeader({
modelId,
sha,
selectedCount,
totalBytes,
localCount,
localBytes,
candidates,
freeBytes,
busy,
}: {
modelId: string;
sha: string;
selectedCount: number;
totalBytes: number;
localCount: number;
localBytes: number;
candidates: Candidate[];
freeBytes: number | null;
/** A download is queued/running; adding files has to wait. */
busy: boolean;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [submitting, setSubmitting] = useState(false);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
for (const c of candidates) {
const g = quantGroup(c.path);
if (!g) continue;
const entry = m.get(g) ?? { paths: [], size: 0 };
entry.paths.push(c.path);
entry.size += c.size;
m.set(g, entry);
}
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [candidates]);
// Split files are one entry; its checkbox selects all parts.
const entries = useMemo(() => groupSplitFiles(candidates), [candidates]);
const pickedEntries = entries.filter((e) => e.parts.every((p) => picked.has(p.path))).length;
const pickedBytes = candidates.filter((c) => picked.has(c.path)).reduce((s, c) => s + c.size, 0);
const tooBig = freeBytes != null && pickedBytes > freeBytes;
function toggle(paths: string[], on: boolean) {
setPicked((prev) => {
const next = new Set(prev);
for (const p of paths) {
if (on) next.add(p);
else next.delete(p);
}
return next;
});
}
async function submit() {
setSubmitting(true);
try {
const res = await fetch(`/api/models/${modelId}/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ add: [...picked] }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not add files (${res.status})`);
return;
}
toast.success(`${body.added} file${body.added === 1 ? "" : "s"} added, download queued`);
setOpen(false);
setPicked(new Set());
router.refresh();
} finally {
setSubmitting(false);
}
}
return (
<div className="border-b">
<div className="flex flex-col gap-2 px-5 py-4">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-sm">
<span>
<span className="font-medium">
{selectedCount} selected file{selectedCount === 1 ? "" : "s"}
</span>
<span className="text-muted-foreground">
{" "}
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
</span>
</span>
<div className="flex items-center gap-3">
<span className="text-muted-foreground">
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
</span>
{candidates.length > 0 && (
<Button
size="sm"
variant={open ? "outline" : "default"}
onClick={() => setOpen((o) => !o)}
disabled={busy && !open}
title={busy ? "Wait until the current download has finished" : undefined}
>
{open ? (
"Close"
) : (
<>
<PlusIcon /> Download more
</>
)}
</Button>
)}
</div>
</div>
<Progress value={percent(localBytes, totalBytes)} />
</div>
{open && (
<div className="border-t bg-muted/30">
{groups.length > 0 && (
<div className="flex flex-col gap-1.5 px-5 pt-4">
<span className="text-xs text-muted-foreground">Quick select</span>
<div className="flex flex-wrap gap-1.5">
{groups.map(([name, g]) => {
const on = g.paths.every((p) => picked.has(p));
return (
<Button
key={name}
type="button"
size="xs"
variant={on ? "default" : "outline"}
onClick={() => toggle(g.paths, !on)}
title={g.paths.join("\n")}
>
{name}
<span className="opacity-70">{formatBytes(g.size)}</span>
</Button>
);
})}
</div>
</div>
)}
<ul className="mt-3 max-h-96 divide-y overflow-y-auto border-y bg-card">
{entries.map((e) => {
const paths = e.parts.map((p) => p.path);
const on = paths.every((p) => picked.has(p));
return (
<li key={e.path}>
<label className="grid cursor-pointer grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2 hover:bg-muted/50">
<Checkbox checked={on} onCheckedChange={(v) => toggle(paths, v === true)} />
<FileRoleBadge path={e.path} />
<span className="flex min-w-0 items-center gap-2" title={paths.join("\n")}>
<span className="truncate font-mono text-[13px]">{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>
)}
</span>
<span className="text-right text-sm text-muted-foreground tabular-nums">{formatBytes(e.size)}</span>
</label>
</li>
);
})}
</ul>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-3 text-sm">
<span>
<span className="font-medium">
{pickedEntries} file{pickedEntries === 1 ? "" : "s"} · {formatBytes(pickedBytes)}
</span>
{freeBytes != null && (
<span className={tooBig ? "text-destructive" : "text-muted-foreground"}>
{" "}
({formatBytes(freeBytes)} free)
</span>
)}
</span>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" onClick={() => setPicked(new Set())} disabled={picked.size === 0}>
Clear
</Button>
<Button size="sm" onClick={submit} disabled={picked.size === 0 || submitting || busy}>
{submitting ? "Adding…" : pickedEntries === 0 ? "Download" : `Download ${pickedEntries} file${pickedEntries === 1 ? "" : "s"}`}
</Button>
</div>
</div>
</div>
)}
</div>
);
}
+77 -33
View File
@@ -11,10 +11,12 @@ import {
ShieldCheckIcon,
XCircleIcon,
} from "lucide-react";
import { Progress } from "@/components/ui/progress";
import { FileRoleBadge } from "@/components/labels";
import type { ModelFileState } from "@/lib/db/schema";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { formatBytes } from "@/lib/format";
import { type FileGroup, groupSplitFiles } from "@/lib/file-groups";
import { cn } from "@/lib/utils";
import { FilesHeader } from "./download-more";
type FileRow = { id: string; path: string; size: number; lfsSha256: string | null; state: ModelFileState };
@@ -47,35 +49,64 @@ function FileName({ path }: { path: string }) {
);
}
function Row({ file, href, muted, showState }: { file: FileRow; href: string; muted?: boolean; showState: boolean }) {
const state = STATE[file.state];
type Entry = FileGroup<FileRow>;
/** One status for a whole entry (all parts of a split file). */
function entryState(e: Entry): { state: ModelFileState; label: string } {
const states = e.parts.map((p) => p.state);
const done = states.filter((st) => st === "present" || st === "verified").length;
const worst = (["missing", "hash_mismatch", "size_mismatch"] as const).find((st) => states.includes(st));
if (worst) return { state: worst, label: STATE[worst].label };
if (done === states.length) {
const state = states.every((st) => st === "verified") ? "verified" : "present";
return { state, label: STATE[state].label };
}
if (done > 0) return { state: "pending", label: `${done} of ${states.length} parts` };
return { state: "pending", label: STATE.pending.label };
}
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
function Row({ entry, href, muted, showState }: { entry: Entry; href: string; muted?: boolean; showState: boolean }) {
const { state: stateKey, label } = entryState(entry);
const state = STATE[stateKey];
const split = entry.totalParts > 1;
return (
<li>
<a
href={href}
target="_blank"
rel="noreferrer"
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
className={cn(
// Fixed status column so sizes line up between selected and unselected rows.
"grid grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_minmax(0,1fr)_5rem_7.5rem]",
"grid grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_7.5rem]",
muted && "text-muted-foreground",
)}
>
<FileTypeIcon path={file.path} />
<FileTypeIcon path={entry.path} />
<FileRoleBadge path={entry.path} className={muted ? "opacity-70" : undefined} />
<span className="flex min-w-0 items-center gap-2">
<FileName path={file.path} />
{file.lfsSha256 && (
<FileName path={entry.path} />
{split && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{entry.parts.length === entry.totalParts
? `${entry.totalParts} parts`
: `${entry.parts.length} of ${entry.totalParts} parts`}
</span>
)}
{entry.parts[0].lfsSha256 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">LFS</span>
)}
</span>
<span className="hidden text-right text-sm tabular-nums sm:block">{formatBytes(file.size)}</span>
<span className="hidden text-right text-sm tabular-nums sm:block">{formatBytes(entry.size)}</span>
{showState ? (
<span className={cn("flex items-center justify-end gap-1.5 text-xs whitespace-nowrap", state.className)}>
{state.icon}
<span className="hidden md:inline">{state.label}</span>
<span className="hidden md:inline">{label}</span>
</span>
) : (
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(file.size)}</span>
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(entry.size)}</span>
)}
</a>
</li>
@@ -84,54 +115,67 @@ function Row({ file, href, muted, showState }: { file: FileRow; href: string; mu
/** "Files and versions"-style list: selected files with their local state, the rest collapsed. */
export function FilesTab({
modelId,
repoId,
sha,
selected,
others,
freeBytes,
busy,
}: {
modelId: string;
repoId: string;
sha: string;
selected: FileRow[];
others: FileRow[];
freeBytes: number | null;
busy: boolean;
}) {
const blob = (path: string) => `https://huggingface.co/${repoId}/blob/${sha}/${path}`;
const hub = `https://huggingface.co/${repoId}`;
// Split files link to their folder (all parts), single files to the file itself.
const href = (e: Entry) => {
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
};
const selectedEntries = groupSplitFiles(selected);
const otherEntries = groupSplitFiles(others);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const local = selected.filter((f) => f.state === "present" || f.state === "verified");
const localBytes = local.reduce((s, f) => s + f.size, 0);
const localEntries = selectedEntries.filter(isLocal);
const localBytes = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
return (
<div>
<div className="flex flex-col gap-2 px-5 py-4">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 text-sm">
<span>
<span className="font-medium">{selected.length} selected file{selected.length === 1 ? "" : "s"}</span>
<span className="text-muted-foreground"> · {formatBytes(totalBytes)} · commit {shortSha(sha)}</span>
</span>
<span className="text-muted-foreground">
{local.length} of {selected.length} on disk · {formatBytes(localBytes)}
</span>
</div>
<Progress value={percent(localBytes, totalBytes)} />
</div>
<FilesHeader
modelId={modelId}
sha={sha}
selectedCount={selectedEntries.length}
totalBytes={totalBytes}
localCount={localEntries.length}
localBytes={localBytes}
candidates={others.map((f) => ({ path: f.path, size: f.size }))}
freeBytes={freeBytes}
busy={busy}
/>
<ul className="divide-y border-t">
{selected.map((f) => (
<Row key={f.id} file={f} href={blob(f.path)} showState />
<ul className="divide-y">
{selectedEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} showState />
))}
</ul>
{others.length > 0 && (
{otherEntries.length > 0 && (
<details className="group border-t">
<summary className="flex cursor-pointer list-none items-center gap-2 px-5 py-3 text-sm hover:bg-muted/50">
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-open:rotate-90" />
<span className="font-medium">Not selected</span>
<span className="text-muted-foreground">
{others.length} file{others.length === 1 ? "" : "s"} · {formatBytes(others.reduce((s, f) => s + f.size, 0))}
{otherEntries.length} file{otherEntries.length === 1 ? "" : "s"} ·{" "}
{formatBytes(others.reduce((s, f) => s + f.size, 0))}
</span>
</summary>
<ul className="divide-y border-t">
{others.map((f) => (
<Row key={f.id} file={f} href={blob(f.path)} muted showState={false} />
{otherEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} muted showState={false} />
))}
</ul>
</details>
+18 -3
View File
@@ -24,8 +24,10 @@ import { formatBytes, shortSha } from "@/lib/format";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { getModelByRepo, relatedModels } from "@/lib/library";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
import { modelTagList } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
import { DownloadCard } from "./download-card";
import { FilesTab } from "./files-tab";
import { JobsTab } from "./jobs-tab";
@@ -89,16 +91,19 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const baseModels = model.baseModels ?? [];
const hubTags = model.hubTags ?? [];
const [tags, related, card] = await Promise.all([
const [tags, related, card, worker] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
]);
const selected = files.filter((f) => f.selected);
const others = files.filter((f) => !f.selected);
const selectedBytes = selected.reduce((s, f) => s + f.size, 0);
const quants = [...new Set(selected.map((f) => quantGroup(f.path)).filter(Boolean))] as string[];
const quants = [
...new Set(selected.filter((f) => fileRole(f.path) === "model").map((f) => quantGroup(f.path)).filter(Boolean)),
] as string[];
const formats = hubTags.filter((t) => FORMATS[t]).map((t) => FORMATS[t]);
const languages = hubTags.map(languageName).filter(Boolean) as string[];
@@ -206,7 +211,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
)}
</div>
)}
{tab === "files" && <FilesTab repoId={model.repoId} sha={model.pinnedSha} selected={selected} others={others} />}
{tab === "files" && (
<FilesTab
modelId={model.id}
repoId={model.repoId}
sha={model.pinnedSha}
selected={selected}
others={others}
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
busy={model.status === "downloading"}
/>
)}
{tab === "jobs" && (
<div className="px-2 pb-2">
<JobsTab modelId={model.id} />
+1 -1
View File
@@ -51,7 +51,7 @@ export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) {
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.id} name={t.name}>
<TagBadge key={t.id} name={t.name} color={t.color}>
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)} className="opacity-60 hover:opacity-100">
<XIcon className="size-3" />
</button>
+48 -31
View File
@@ -3,6 +3,7 @@
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@@ -10,6 +11,7 @@ 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 { 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";
@@ -105,14 +107,19 @@ export function AddModelForm({
}, [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);
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
function toggle(path: string, on: boolean) {
function toggle(paths: string[], on: boolean) {
setChecked((prev) => {
const next = new Set(prev);
if (on) next.add(path);
else next.delete(path);
for (const path of paths) {
if (on) next.add(path);
else next.delete(path);
}
return next;
});
}
@@ -311,33 +318,43 @@ export function AddModelForm({
</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>
))}
{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);
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>}
</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>
@@ -346,7 +363,7 @@ export function AddModelForm({
<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)}
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{freeBytes != null && (
+9 -2
View File
@@ -2,14 +2,16 @@ import Link from "next/link";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
import { Button } from "@/components/ui/button";
import { LabelSettingsProvider } from "@/components/labels";
import { WorkerIndicator } from "@/components/worker-indicator";
import { getFileRoleStyles } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export default async function AppLayout({ children }: LayoutProps<"/">) {
const session = await auth();
if (!session?.user) redirect("/login");
const worker = await getWorkerStatus();
const [worker, fileRoles] = await Promise.all([getWorkerStatus(), getFileRoleStyles()]);
return (
<div className="flex min-h-screen flex-col overflow-x-clip">
@@ -23,6 +25,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<Link href="/" className="hover:text-foreground">
Library
</Link>
<Link href="/settings" className="hover:text-foreground">
Settings
</Link>
</nav>
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
@@ -42,7 +47,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
</div>
</div>
</header>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">{children}</main>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
<LabelSettingsProvider fileRoles={fileRoles}>{children}</LabelSettingsProvider>
</main>
</div>
);
}
+4 -3
View File
@@ -93,6 +93,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
};
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
@@ -123,7 +124,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
marker={facet === "tag" ? (v) => <TagDot name={v} /> : undefined}
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : undefined}
/>
))}
</div>
@@ -136,7 +137,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{FACETS.flatMap((facet) =>
filters[facet].map((v) => (
<Badge key={`${facet}:${v}`} variant="secondary" className="gap-1">
{facet === "tag" && <TagDot name={v} />}
{facet === "tag" && <TagDot name={v} color={tagColors.get(v)} />}
{FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v}
<button
type="button"
@@ -193,7 +194,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<TagBadge name={t.name} />
<TagBadge name={t.name} color={t.color} />
</button>
))}
</div>
@@ -0,0 +1,46 @@
"use client";
import { ChevronDownIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DOT_CLASS, LABEL_COLORS, type LabelColor } from "@/lib/colors";
import { cn } from "@/lib/utils";
/** Dropdown of the named label colors; optional "Automatic" entry (value null). */
export function ColorPicker({
value,
onChange,
allowAuto = false,
autoColor,
}: {
value: LabelColor | null;
onChange: (color: LabelColor | null) => void;
allowAuto?: boolean;
/** Color shown for the automatic option. */
autoColor?: LabelColor;
}) {
const shown = value ?? autoColor ?? "gray";
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="outline" size="sm" className="w-32 justify-start" />}>
<span className={cn("size-3 rounded-full", DOT_CLASS[shown])} />
<span className="flex-1 text-left capitalize">{value ?? "Automatic"}</span>
<ChevronDownIcon className="opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-72 min-w-40">
{allowAuto && (
<DropdownMenuItem onClick={() => onChange(null)}>
<span className={cn("size-3 rounded-full", DOT_CLASS[autoColor ?? "gray"])} />
Automatic
</DropdownMenuItem>
)}
{LABEL_COLORS.map((c) => (
<DropdownMenuItem key={c} onClick={() => onChange(c)}>
<span className={cn("size-3 rounded-full", DOT_CLASS[c])} />
<span className="capitalize">{c}</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,112 @@
"use client";
import { RotateCcwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { BADGE_CLASS } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRoleStyles } from "@/lib/file-roles";
import { cn } from "@/lib/utils";
import { ColorPicker } from "./color-picker";
/** Edit the label text and color shown in front of file names. */
export function FileLabelSettings({ initial }: { initial: FileRoleStyles }) {
const router = useRouter();
const [styles, setStyles] = useState(initial);
const [saving, setSaving] = useState(false);
const dirty = JSON.stringify(styles) !== JSON.stringify(initial);
function update(role: keyof FileRoleStyles, patch: Partial<FileRoleStyles[keyof FileRoleStyles]>) {
setStyles((prev) => ({ ...prev, [role]: { ...prev[role], ...patch } }));
}
async function save(next = styles) {
setSaving(true);
try {
const res = await fetch("/api/settings/labels", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileRoles: next }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not save (${res.status})`);
return;
}
setStyles(body.fileRoles);
toast.success("File labels saved");
router.refresh();
} finally {
setSaving(false);
}
}
const defaults = Object.fromEntries(
FILE_ROLE_ORDER.map((r) => [r, { label: FILE_ROLES[r].label, color: FILE_ROLES[r].color }]),
) as FileRoleStyles;
return (
<Card>
<CardHeader>
<CardTitle>File labels</CardTitle>
<CardDescription>
Shown in front of file names (Files tab, Add model). Kaname detects the type from the file name; here you
choose how each type is labeled and colored.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{FILE_ROLE_ORDER.map((role) => {
const s = styles[role];
const changed = s.label !== defaults[role].label || s.color !== defaults[role].color;
return (
<div key={role} className="grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[6rem_minmax(0,1fr)_10rem_8rem_2rem]">
<span
className={cn(
"inline-flex h-5 justify-self-start rounded-md border px-1.5 text-[11px] leading-[18px] font-medium",
BADGE_CLASS[s.color],
)}
>
{s.label || "…"}
</span>
<span className="min-w-0 text-xs text-muted-foreground">{FILE_ROLES[role].description}</span>
<Input
value={s.label}
maxLength={24}
onChange={(e) => update(role, { label: e.target.value })}
aria-label={`Label for ${FILE_ROLES[role].label}`}
className="h-8"
/>
<ColorPicker value={s.color} onChange={(c) => c && update(role, { color: c })} />
<Button
variant="ghost"
size="icon-sm"
disabled={!changed}
title="Reset to default"
aria-label="Reset to default"
onClick={() => update(role, defaults[role])}
>
<RotateCcwIcon />
</Button>
</div>
);
})}
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button variant="ghost" onClick={() => setStyles(initial)} disabled={!dirty || saving}>
Discard changes
</Button>
<Button variant="outline" onClick={() => save(defaults)} disabled={saving}>
Reset all to defaults
</Button>
<Button onClick={() => save()} disabled={!dirty || saving}>
{saving ? "Saving…" : "Save"}
</Button>
</div>
</CardContent>
</Card>
);
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { getFileRoleStyles } from "@/lib/settings";
import { listTags } from "@/lib/tags";
import { FileLabelSettings } from "./file-label-settings";
import { TagSettings } from "./tag-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Labels · Settings" };
export default async function LabelSettingsPage() {
const [fileRoles, tags] = await Promise.all([getFileRoleStyles(), listTags()]);
return (
<div className="flex flex-col gap-4">
<FileLabelSettings initial={fileRoles} />
<TagSettings tags={tags} />
</div>
);
}
@@ -0,0 +1,122 @@
"use client";
import { Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { TagBadge } from "@/components/tag-badge";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { autoTagColor, isLabelColor } from "@/lib/colors";
import type { Tag } from "@/lib/tags";
import { ColorPicker } from "./color-picker";
/** Rename, recolor or delete user tags. Changes save immediately. */
export function TagSettings({ tags }: { tags: (Tag & { count: number })[] }) {
return (
<Card>
<CardHeader>
<CardTitle>Tags</CardTitle>
<CardDescription>
Your own tags (added on a model page or when adding a model). Tags without a color get an automatic one.
</CardDescription>
</CardHeader>
<CardContent>
{tags.length === 0 ? (
<p className="text-sm text-muted-foreground">No tags yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tags.map((t) => (
<TagRow key={t.id} tag={t} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function TagRow({ tag }: { tag: Tag & { count: number } }) {
const router = useRouter();
const [name, setName] = useState(tag.name);
const [busy, setBusy] = useState(false);
async function patch(body: { name?: string; color?: string | null }) {
setBusy(true);
try {
const res = await fetch(`/api/tags/${tag.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
setName(tag.name);
return;
}
router.refresh();
} finally {
setBusy(false);
}
}
async function remove() {
const res = await fetch(`/api/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`Tag "${tag.name}" deleted`);
router.refresh();
}
const color = isLabelColor(tag.color) ? tag.color : null;
return (
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[8rem_minmax(0,1fr)_8rem_6rem_2rem]">
<TagBadge name={name || tag.name} color={tag.color} className="justify-self-start" />
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) => setName(e.target.value)}
onBlur={() => name.trim() && name !== tag.name && patch({ name })}
onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
aria-label={`Rename tag ${tag.name}`}
className="h-8"
/>
<ColorPicker value={color} onChange={(c) => patch({ color: c })} allowAuto autoColor={autoTagColor(tag.name)} />
<span className="text-xs text-muted-foreground tabular-nums">
{tag.count} model{tag.count === 1 ? "" : "s"}
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete tag ${tag.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete tag &ldquo;{tag.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>
It is removed from {tag.count} model{tag.count === 1 ? "" : "s"}. The models themselves are not touched.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [{ href: "/settings/labels", label: "Labels", icon: <TagsIcon className="size-4" /> }];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Settings</h1>
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
<SettingsNav sections={SECTIONS} />
<div className="min-w-0">{children}</div>
</div>
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function SettingsPage() {
redirect("/settings/labels");
}
+26
View File
@@ -0,0 +1,26 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
export function SettingsNav({ sections }: { sections: { href: string; label: string; icon: React.ReactNode }[] }) {
const pathname = usePathname();
return (
<nav className="flex gap-1 rounded-xl bg-card p-2 ring-1 ring-foreground/10 md:flex-col">
{sections.map((s) => (
<Link
key={s.href}
href={s.href}
className={cn(
"flex items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",
pathname === s.href ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:text-foreground",
)}
>
{s.icon}
{s.label}
</Link>
))}
</nav>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { addFilesToModel, ModelError } from "@/lib/models";
const Body = z.object({ add: z.array(z.string().min(1).max(1024)).min(1).max(10_000) });
/** Add files to a model's selection and queue their download. */
export const POST = withAuth<RouteContext<"/api/models/[id]/files">>(async (req, { params }) => {
const { id } = await params;
try {
const { add } = Body.parse(await req.json());
return NextResponse.json(await addFilesToModel(id, add), { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getFileRoleStyles, saveFileRoleStyles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Label text and color per file role (defaults merged with saved overrides). */
export const GET = withAuth(async () => NextResponse.json({ fileRoles: await getFileRoleStyles() }));
const Body = z.object({
fileRoles: z.record(z.string(), z.object({ label: z.string().optional(), color: z.string().optional() })),
});
/** Replace the saved overrides; send the full set (values equal to the default are dropped). */
export const PUT = withAuth(async (req) => {
try {
const { fileRoles } = Body.parse(await req.json());
return NextResponse.json({ fileRoles: await saveFileRoleStyles(fileRoles) });
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteTag, TagError, updateTag } from "@/lib/tags";
const Body = z.object({ name: z.string().optional(), color: z.string().nullable().optional() });
/** Rename a tag and/or change its color (null = automatic). */
export const PATCH = withAuth<RouteContext<"/api/tags/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await updateTag(id, Body.parse(await req.json())));
} catch (err) {
if (err instanceof TagError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Delete a tag everywhere. */
export const DELETE = withAuth<RouteContext<"/api/tags/[id]">>(async (_req, { params }) => {
const { id } = await params;
await deleteTag(id);
return new NextResponse(null, { status: 204 });
});