Release 0.4.0: Kaname, search, filters and tags
Release / release (push) Successful in 11m41s

- Rename the app to Kaname
- Hub metadata per model (base models, architecture, license, Hub tags),
  backfilled by the worker for existing models
- Library search across repo/author/family/quant/tags and multi-select
  facet filters (author, family, quant, tag, status) kept in the URL
- Custom tags (model page editor, on add, click-to-filter)
- README rewritten around a quick install, with banner and screenshots
- deploy/compose.yaml: models in a host folder (KANAME_MODELS_DIR)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 19:49:17 +02:00
1 parent 2167ea0950
commit 67191b3e16
37 files changed
+2028 -206

No files matched your search

+29 -1
View File
@@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -44,6 +44,15 @@ export function AddModelForm({
const [includeText, setIncludeText] = useState("");
const [excludeText, setExcludeText] = useState("");
const [submitting, setSubmitting] = useState(false);
const [tagsText, setTagsText] = useState("");
const [knownTags, setKnownTags] = useState<string[]>([]);
useEffect(() => {
fetch("/api/tags")
.then((r) => (r.ok ? r.json() : []))
.then((all: { name: string }[]) => setKnownTags(all.map((t) => t.name)))
.catch(() => {});
}, []);
async function lookup(e: React.FormEvent) {
e.preventDefault();
@@ -56,6 +65,7 @@ export function AddModelForm({
setChecked(new Set());
setIncludeText("");
setExcludeText("");
setTagsText("");
} catch (err) {
setResult(null);
setError(err instanceof Error ? err.message : String(err));
@@ -129,6 +139,7 @@ export function AddModelForm({
sha: result.sha,
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
exclude: excludePatterns,
tags: parsePatternList(tagsText),
});
toast.success(`${result.repoId} added, download queued`);
onAdded(id);
@@ -269,6 +280,23 @@ export function AddModelForm({
folder. Selected = checked or matching an include pattern, minus excludes.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="tags">Tags</Label>
<Input
id="tags"
value={tagsText}
onChange={(e) => setTagsText(e.target.value)}
placeholder="roleplay, security"
list="known-tags"
/>
<datalist id="known-tags">
{knownTags.map((t) => (
<option key={t} value={t} />
))}
</datalist>
<p className="text-xs text-muted-foreground">Optional, comma-separated. Editable later on the model page.</p>
</div>
</CardContent>
</Card>
+51
View File
@@ -0,0 +1,51 @@
"use client";
import { ChevronDownIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
/** Multi-select dropdown for one facet, with per-value counts. */
export function FacetFilter({
label,
values,
selected,
onChange,
format = (v) => v,
}: {
label: string;
values: [string, number][];
selected: string[];
onChange: (next: string[]) => void;
format?: (value: string) => string;
}) {
const active = selected.length > 0;
return (
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant={active ? "secondary" : "outline"} size="sm" disabled={values.length === 0} />}
>
{label}
{active && <span className="rounded bg-background/60 px-1 text-xs tabular-nums">{selected.length}</span>}
<ChevronDownIcon className="opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-auto min-w-48">
{values.map(([value, count]) => (
<DropdownMenuCheckboxItem
key={value}
checked={selected.includes(value)}
closeOnClick={false}
onCheckedChange={(on) => onChange(on ? [...selected, value] : selected.filter((v) => v !== value))}
>
<span className="flex-1">{format(value)}</span>
<span className="ml-4 text-xs text-muted-foreground tabular-nums">{count}</span>
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
+1 -1
View File
@@ -16,7 +16,7 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<header className="border-b">
<div className="mx-auto flex h-14 max-w-6xl items-center gap-6 px-4">
<Link href="/" className="flex items-baseline gap-1.5 font-semibold">
Model Manager
Kaname
<span className="text-xs font-normal text-muted-foreground">{process.env.APP_VERSION ?? "dev"}</span>
</Link>
<nav className="flex items-center gap-4 text-sm text-muted-foreground">
-75
View File
@@ -1,75 +0,0 @@
"use client";
import Link from "next/link";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import { formatBytes, shortSha } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
const OPEN = ["queued", "downloading", "verifying"];
export function LibraryTable({ rows }: { rows: LibraryRow[] }) {
const { snapshot } = useLive();
const openJobs = new Map<string, JobSnapshot>();
for (const j of snapshot?.jobs ?? []) {
if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j);
}
return (
<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 className="w-56">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((r) => {
const job = openJobs.get(r.id);
return (
<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">
<LocalTime value={r.downloadedAt} />
</TableCell>
<TableCell>
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<ModelStatusBadge status={r.status} />
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
);
}
+229
View File
@@ -0,0 +1,229 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import {
EMPTY_FILTERS,
type Facet,
FACETS,
facetCounts,
type Filters,
matchesFilters,
matchesQuery,
type SearchableModel,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
const OPEN = ["queued", "downloading", "verifying"];
const FACET_LABEL: Record<Facet, string> = {
author: "Author",
family: "Family",
quant: "Quant",
tag: "Tag",
status: "Status",
};
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
function toSearchable(r: LibraryRow): SearchableModel {
return {
repoId: r.repoId,
author: r.author,
families: r.families,
baseModels: r.baseModels,
architecture: r.architecture,
quants: r.quants,
tags: r.tags.map((t) => t.name),
hubTags: r.hubTags,
pipelineTag: r.pipelineTag,
license: r.license,
status: r.status,
};
}
/** Search + facet filters (kept in the URL) over the library table. */
export function LibraryView({ rows }: { rows: LibraryRow[] }) {
const router = useRouter();
const pathname = usePathname();
const params = useSearchParams();
const [query, setQuery] = useState(() => params.get("q") ?? "");
const [filters, setFilters] = useState<Filters>(() => {
const f = { ...EMPTY_FILTERS };
for (const facet of FACETS) f[facet] = params.getAll(facet);
return f;
});
function sync(nextQuery: string, nextFilters: Filters) {
const p = new URLSearchParams();
if (nextQuery) p.set("q", nextQuery);
for (const facet of FACETS) for (const v of nextFilters[facet]) p.append(facet, v);
const qs = p.toString();
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
}
const updateQuery = (q: string) => {
setQuery(q);
sync(q, filters);
};
const updateFilter = (facet: Facet, values: string[]) => {
const next = { ...filters, [facet]: values };
setFilters(next);
sync(query, next);
};
const clearAll = () => {
setQuery("");
setFilters(EMPTY_FILTERS);
sync("", EMPTY_FILTERS);
};
const searchable = useMemo(() => rows.map(toSearchable), [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);
const { snapshot } = useLive();
const openJobs = new Map<string, JobSnapshot>();
for (const j of snapshot?.jobs ?? []) {
if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j);
}
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<div className="relative min-w-56 flex-1">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(e) => updateQuery(e.target.value)}
placeholder="Search repo, author, family, quant, tag…"
className="pl-8"
aria-label="Search models"
/>
</div>
{FACETS.map((facet) => (
<FacetFilter
key={facet}
label={FACET_LABEL[facet]}
values={facetCounts(searchable, facet, query, filters)}
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
/>
))}
</div>
{anyActive && (
<div className="flex flex-wrap items-center gap-1.5 text-sm">
<span className="text-muted-foreground">
{visible.length} of {rows.length} models
</span>
{FACETS.flatMap((facet) =>
filters[facet].map((v) => (
<Badge key={`${facet}:${v}`} variant="secondary" className="gap-1">
{FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v}
<button
type="button"
aria-label={`Remove filter ${v}`}
onClick={() => updateFilter(facet, filters[facet].filter((x) => x !== v))}
>
<XIcon className="size-3" />
</button>
</Badge>
)),
)}
<Button variant="ghost" size="xs" onClick={clearAll}>
Clear all
</Button>
</div>
)}
{visible.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>No matching models</CardTitle>
<CardDescription>Try a different search or remove a filter.</CardDescription>
</CardHeader>
</Card>
) : (
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Model</TableHead>
<TableHead>Selection</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{visible.map((r) => {
const job = openJobs.get(r.id);
const base = r.baseModels[0];
return (
<TableRow key={r.id}>
<TableCell className="whitespace-normal">
<Link href={`/models/${r.id}`} className="font-medium hover:underline">
{r.repoId}
</Link>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.tags.map((t) => (
<button
key={t.id}
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<Badge variant="outline">{t.name}</Badge>
</button>
))}
</div>
</TableCell>
<TableCell className="text-sm">
{r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} file${r.fileCount === 1 ? "" : "s"}`}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell className="hidden lg:table-cell">
<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">
<LocalTime value={r.downloadedAt} />
</TableCell>
<TableCell>
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<ModelStatusBadge status={r.status} />
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
)}
</div>
);
}
+29
View File
@@ -4,9 +4,12 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { modelFamilies } from "@/lib/hub/metadata";
import { getModel } from "@/lib/library";
import { modelTagList } from "@/lib/tags";
import { ModelLive } from "./model-live";
import { RemoveModelButton } from "./remove-model-button";
import { TagEditor } from "./tag-editor";
export const dynamic = "force-dynamic";
@@ -15,6 +18,7 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
const data = await getModel(id);
if (!data) notFound();
const { model, files } = data;
const modelTags = await modelTagList(model.id);
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
@@ -25,6 +29,7 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
<ModelStatusBadge status={model.status} />
<div className="ml-auto">{model.status === "pending" && <RemoveModelButton id={model.id} />}</div>
</div>
<TagEditor modelId={model.id} tags={modelTags} />
<Card>
<CardHeader>
@@ -43,6 +48,30 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
huggingface.co/{model.repoId}
</a>
</dd>
<dt className="text-muted-foreground">Author</dt>
<dd>{model.repoId.split("/")[0]}</dd>
<dt className="text-muted-foreground">Family</dt>
<dd>{modelFamilies(model.repoId, model.baseModels).join(", ")}</dd>
<dt className="text-muted-foreground">Base model</dt>
<dd className="flex flex-col">
{(model.baseModels ?? []).length === 0
? "–"
: model.baseModels!.map((b) => (
<a key={b} href={`https://huggingface.co/${b}`} target="_blank" rel="noreferrer" className="underline">
{b}
</a>
))}
</dd>
<dt className="text-muted-foreground">Architecture</dt>
<dd>{model.architecture ?? "–"}</dd>
<dt className="text-muted-foreground">License</dt>
<dd>{model.license ?? "–"}</dd>
{(model.hubTags ?? []).length > 0 && (
<>
<dt className="text-muted-foreground">Hub tags</dt>
<dd className="text-xs text-muted-foreground">{model.hubTags!.join(", ")}</dd>
</>
)}
<dt className="text-muted-foreground">Tracked revision</dt>
<dd className="font-mono">{model.trackedRevision}</dd>
<dt className="text-muted-foreground">Pinned SHA</dt>
+87
View File
@@ -0,0 +1,87 @@
"use client";
import { XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useId, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import type { Tag } from "@/lib/tags";
/** Add/remove user tags on a model; suggests existing tags. */
export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) {
const router = useRouter();
const listId = useId();
const [value, setValue] = useState("");
const [busy, setBusy] = useState(false);
const [suggestions, setSuggestions] = useState<string[]>([]);
useEffect(() => {
fetch("/api/tags")
.then((r) => (r.ok ? r.json() : []))
.then((all: Tag[]) => setSuggestions(all.map((t) => t.name)))
.catch(() => {});
}, [tags]);
async function add(name: string) {
if (!name.trim()) return;
setBusy(true);
const res = await fetch(`/api/models/${modelId}/tags`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
setBusy(false);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Could not add tag (${res.status})`);
return;
}
setValue("");
router.refresh();
}
async function remove(tag: Tag) {
const res = await fetch(`/api/models/${modelId}/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not remove tag (${res.status})`);
router.refresh();
}
const current = new Set(tags.map((t) => t.name.toLowerCase()));
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<Badge key={t.id} variant="secondary" className="gap-1">
{t.name}
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)}>
<XIcon className="size-3" />
</button>
</Badge>
))}
<form
onSubmit={(e) => {
e.preventDefault();
void add(value);
}}
>
<Input
value={value}
onChange={(e) => setValue(e.target.value)}
list={listId}
placeholder="Add tag…"
disabled={busy}
maxLength={40}
className="h-6 w-36 text-xs"
aria-label="Add tag"
/>
<datalist id={listId}>
{suggestions
.filter((s) => !current.has(s.toLowerCase()))
.map((s) => (
<option key={s} value={s} />
))}
</datalist>
</form>
</div>
);
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { listLibrary } from "@/lib/library";
import { getWorkerStatus } from "@/lib/worker-status";
import { AddModelPanel } from "./add-model-panel";
import { LibraryTable } from "./library-table";
import { LibraryView } from "./library-view";
export const dynamic = "force-dynamic";
@@ -12,7 +12,7 @@ export default async function LibraryPage() {
<div className="flex flex-col gap-4">
{/* Opens by default while the library is empty. */}
<AddModelPanel freeBytes={worker.online ? worker.modelsDirFreeBytes : null} defaultOpen={rows.length === 0} />
{rows.length > 0 && <LibraryTable rows={rows} />}
{rows.length > 0 && <LibraryView rows={rows} />}
</div>
);
}
@@ -0,0 +1,10 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { removeTag } from "@/lib/tags";
/** Detach a tag from a model. */
export const DELETE = withAuth<RouteContext<"/api/models/[id]/tags/[tagId]">>(async (_req, { params }) => {
const { id, tagId } = await params;
await removeTag(id, tagId);
return new NextResponse(null, { status: 204 });
});
+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 { addTag, TagError } from "@/lib/tags";
const Body = z.object({ name: z.string() });
/** Attach a tag to a model (creates the tag on first use). */
export const POST = withAuth<RouteContext<"/api/models/[id]/tags">>(async (req, { params }) => {
const { id } = await params;
try {
const { name } = Body.parse(await req.json());
return NextResponse.json(await addTag(id, name), { status: 201 });
} catch (err) {
if (err instanceof TagError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+5 -1
View File
@@ -5,6 +5,7 @@ import { apiError, handleApiError } from "@/lib/api-errors";
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
import { queueDownload } from "@/lib/jobs";
import { addModel, ModelError } from "@/lib/models";
import { addTag, normalizeTagName, TagError } from "@/lib/tags";
const Body = z.object({
repoId: z.string().regex(REPO_ID_RE),
@@ -13,22 +14,25 @@ const Body = z.object({
include: z.array(z.string().min(1).max(1024)).max(10_000),
exclude: z.array(z.string().min(1).max(1024)).max(1_000),
download: z.boolean().default(true),
tags: z.array(z.string()).max(50).default([]),
});
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
body.tags.forEach(normalizeTagName); // validate before anything is written
const { id } = await addModel({
repoId: body.repoId,
revision: body.revision,
sha: body.sha,
rule: { include: body.include, exclude: body.exclude },
});
for (const tag of body.tags) await addTag(id, tag);
const job = body.download ? await queueDownload(id) : null;
return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
if (err instanceof ModelError || err instanceof TagError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+8
View File
@@ -0,0 +1,8 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listTags } from "@/lib/tags";
export const dynamic = "force-dynamic";
/** All user tags with usage counts. */
export const GET = withAuth(async () => NextResponse.json(await listTags()));
+1 -1
View File
@@ -9,7 +9,7 @@ const geist = Geist({ subsets: ["latin"], variable: "--font-sans" });
const geistMono = Geist_Mono({ subsets: ["latin"], variable: "--font-mono" });
export const metadata: Metadata = {
title: "Model Manager",
title: { default: "Kaname", template: "%s · Kaname" },
description: "Download and manage local LLMs from Hugging Face",
};
+1 -1
View File
@@ -28,7 +28,7 @@ export default async function LoginPage({ searchParams }: PageProps<"/login">) {
<main className="flex min-h-screen items-center justify-center p-4">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-lg">Model Manager</CardTitle>
<CardTitle className="text-lg">Kaname</CardTitle>
<CardDescription>Sign in to manage local models.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
+2 -2
View File
@@ -1,7 +1,7 @@
import { Badge } from "@/components/ui/badge";
import type { ModelStatus } from "@/lib/db/schema";
const LABELS: Record<ModelStatus, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
export const MODEL_STATUS: Record<ModelStatus, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
pending: { label: "not downloaded", variant: "outline" },
downloading: { label: "downloading", variant: "secondary" },
ready: { label: "ok", variant: "default" },
@@ -11,6 +11,6 @@ const LABELS: Record<ModelStatus, { label: string; variant: "default" | "seconda
};
export function ModelStatusBadge({ status }: { status: ModelStatus }) {
const { label, variant } = LABELS[status];
const { label, variant } = MODEL_STATUS[status];
return <Badge variant={variant}>{label}</Badge>;
}
+41
View File
@@ -75,12 +75,53 @@ export const models = sqliteTable(
lastCheckError: text("last_check_error"),
lastVerifiedAt: ts("last_verified_at"),
downloadedAt: ts("downloaded_at"),
// Hub metadata (for search/filters), refreshed by the worker. Null until fetched.
/** e.g. ["Qwen/Qwen3-8B"] (cardData.base_model, or base_model:* tags). */
baseModels: text("base_models", { mode: "json" }).$type<string[]>(),
/** e.g. "qwen3" (gguf.architecture or config.model_type). */
architecture: text("architecture"),
pipelineTag: text("pipeline_tag"),
license: text("license"),
/** Hub tags, minus noise like arxiv:/region:/deploy:. */
hubTags: text("hub_tags", { mode: "json" }).$type<string[]>(),
metadataFetchedAt: ts("metadata_fetched_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)],
);
// ---------------------------------------------------------------------------
// User tags (e.g. "roleplay", "security")
// ---------------------------------------------------------------------------
export const tags = sqliteTable(
"tags",
{
id: id(),
/** Display name as entered. */
name: text("name").notNull(),
/** Lowercased, trimmed name; unique. */
slug: text("slug").notNull(),
createdAt: createdAt(),
},
(t) => [uniqueIndex("tags_slug_uq").on(t.slug)],
);
export const modelTags = sqliteTable(
"model_tags",
{
modelId: text("model_id")
.notNull()
.references(() => models.id),
tagId: text("tag_id")
.notNull()
.references(() => tags.id),
createdAt: createdAt(),
},
(t) => [primaryKey({ columns: [t.modelId, t.tagId] }), index("model_tags_tag_idx").on(t.tagId)],
);
/** History of SHAs a model has been pinned to. */
export const modelRevisions = sqliteTable(
"model_revisions",
+4 -1
View File
@@ -2,6 +2,7 @@
// Server-side only: it reads HF_TOKEN from the environment. Never import from client components.
import { coreEnv } from "@/lib/env";
import { parseRepoMetadata, type RepoMetadata } from "./metadata";
const HUB = "https://huggingface.co";
const TIMEOUT_MS = 20_000;
@@ -48,6 +49,7 @@ export type RepoInfo = {
gated: false | "auto" | "manual";
private: boolean;
lastModified: string | null;
metadata: RepoMetadata;
};
function headers(): HeadersInit {
@@ -138,13 +140,14 @@ export async function getRepoInfo(repoId: string, revision: string): Promise<Rep
gated?: false | "auto" | "manual";
private?: boolean;
lastModified?: string;
};
} & Parameters<typeof parseRepoMetadata>[0];
return {
repoId: j.id ?? repoId,
sha: j.sha,
gated: j.gated ?? false,
private: j.private ?? false,
lastModified: j.lastModified ?? null,
metadata: parseRepoMetadata(j),
};
}
+59
View File
@@ -0,0 +1,59 @@
// Pure helpers that turn Hub model info into searchable metadata. Shared by web and worker.
export type RepoMetadata = {
author: string | null;
baseModels: string[];
architecture: string | null;
pipelineTag: string | null;
license: string | null;
hubTags: string[];
};
type HubModelInfo = {
id?: string;
author?: string;
pipeline_tag?: string;
tags?: string[];
cardData?: { base_model?: string | string[]; license?: string | string[] } | null;
gguf?: { architecture?: string } | null;
config?: { model_type?: string } | null;
};
/** Hub tags that carry no useful search signal (or are stored separately). */
const NOISE_TAG = /^(arxiv|region|deploy|base_model|license|doi|dataset):|^(endpoints_compatible|autotrain_compatible|eval-results|text-generation-inference|conversational)$/;
const asArray = (v: string | string[] | undefined | null): string[] =>
v == null ? [] : (Array.isArray(v) ? v : [v]).filter((x): x is string => typeof x === "string" && x.length > 0);
export function parseRepoMetadata(info: HubModelInfo): RepoMetadata {
const tags = info.tags ?? [];
// Prefer the model card; fall back to "base_model:<relation>:<id>" / "base_model:<id>" tags.
let baseModels = asArray(info.cardData?.base_model);
if (baseModels.length === 0) {
baseModels = tags
.filter((t) => t.startsWith("base_model:"))
.map((t) => t.split(":").at(-1)!)
.filter((id) => id.includes("/"));
}
const license = asArray(info.cardData?.license)[0] ?? tags.find((t) => t.startsWith("license:"))?.slice(8) ?? null;
return {
author: info.author ?? info.id?.split("/")[0] ?? null,
baseModels: [...new Set(baseModels)],
architecture: info.gguf?.architecture ?? info.config?.model_type ?? null,
pipelineTag: info.pipeline_tag ?? null,
license,
hubTags: [...new Set(tags.filter((t) => !NOISE_TAG.test(t)))],
};
}
/**
* The model "family" for filtering: the org of the base model(s) (unsloth/Qwen3-8B-GGUF → "Qwen"),
* or the repo's own org for original models without a base model.
*/
export function modelFamilies(repoId: string, baseModels: string[] | null | undefined): string[] {
const orgs = (baseModels ?? []).map((b) => b.split("/")[0]).filter(Boolean);
return orgs.length > 0 ? [...new Set(orgs)] : [repoId.split("/")[0]];
}
+39
View File
@@ -0,0 +1,39 @@
import { eq, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
import { getRepoInfo } from "./client";
import type { RepoMetadata } from "./metadata";
/** Columns to write on `models` for fetched Hub metadata. */
export function metadataColumns(meta: RepoMetadata) {
return {
baseModels: meta.baseModels,
architecture: meta.architecture,
pipelineTag: meta.pipelineTag,
license: meta.license,
hubTags: meta.hubTags,
metadataFetchedAt: new Date(),
};
}
/**
* Fetch Hub metadata for models that don't have it yet (added before metadata existed).
* Returns how many were updated; failures are reported but don't stop the others.
*/
export async function backfillMetadata(onError: (repoId: string, err: unknown) => void): Promise<number> {
const missing = await db()
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha })
.from(models)
.where(isNull(models.metadataFetchedAt));
let updated = 0;
for (const m of missing) {
try {
const info = await getRepoInfo(m.repoId, m.pinnedSha);
await db().update(models).set(metadataColumns(info.metadata)).where(eq(models.id, m.id));
updated++;
} catch (err) {
onError(m.repoId, err);
}
}
return updated;
}
+35 -9
View File
@@ -1,12 +1,14 @@
import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { modelFiles, models } from "@/lib/db/schema";
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { modelFamilies } from "@/lib/hub/metadata";
import { quantGroup } from "@/lib/selection";
import type { Tag } from "@/lib/tags";
export type LibraryRow = Awaited<ReturnType<typeof listLibrary>>[number];
/** Models with their selected-file totals and a short "which quant" label. */
/** Models with selected-file totals, quant labels, Hub metadata and user tags. */
export async function listLibrary() {
const d = db();
const rows = await d
@@ -19,6 +21,11 @@ export async function listLibrary() {
status: models.status,
createdAt: models.createdAt,
downloadedAt: models.downloadedAt,
baseModels: models.baseModels,
architecture: models.architecture,
pipelineTag: models.pipelineTag,
license: models.license,
hubTags: models.hubTags,
fileCount: sql<number>`count(${modelFiles.id})`,
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
})
@@ -31,17 +38,24 @@ export async function listLibrary() {
.select({ modelId: modelFiles.modelId, path: modelFiles.path })
.from(modelFiles)
.where(eq(modelFiles.selected, true));
const quants = new Map<string, Set<string>>();
for (const f of selected) {
const g = quantGroup(f.path);
if (!g) continue;
if (!quants.has(f.modelId)) quants.set(f.modelId, new Set());
quants.get(f.modelId)!.add(g);
}
const quants = groupBy(selected, (f) => f.modelId, (f) => quantGroup(f.path));
const tagRows = await d
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name })
.from(modelTags)
.innerJoin(tags, eq(tags.id, modelTags.tagId))
.orderBy(asc(tags.slug));
const tagsByModel = new Map<string, Tag[]>();
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name }]);
return rows.map((r) => ({
...r,
author: r.repoId.split("/")[0],
families: modelFamilies(r.repoId, r.baseModels),
baseModels: r.baseModels ?? [],
hubTags: r.hubTags ?? [],
quants: [...(quants.get(r.id) ?? [])].sort(),
tags: tagsByModel.get(r.id) ?? [],
}));
}
@@ -56,3 +70,15 @@ export async function getModel(id: string) {
.orderBy(asc(modelFiles.path));
return { model, files };
}
function groupBy<T>(items: T[], key: (t: T) => string, value: (t: T) => string | null) {
const out = new Map<string, Set<string>>();
for (const item of items) {
const v = value(item);
if (v == null) continue;
const k = key(item);
if (!out.has(k)) out.set(k, new Set());
out.get(k)!.add(v);
}
return out;
}
+6 -1
View File
@@ -2,9 +2,11 @@ import "server-only";
import { and, eq, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { jobs, modelFiles, modelRevisions, models } from "@/lib/db/schema";
import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
import { checkFileAccess, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { isSelected, type SelectionRule } from "@/lib/selection";
import { deleteUnusedTags } from "@/lib/tags";
export class ModelError extends Error {
constructor(
@@ -67,6 +69,7 @@ export async function addModel(input: {
localPath: repoId,
includePatterns: input.rule.include,
excludePatterns: input.rule.exclude,
...metadataColumns(info.metadata),
}),
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
@@ -91,10 +94,12 @@ export async function removeModel(id: string): Promise<void> {
);
}
await d.batch([
d.delete(modelTags).where(eq(modelTags.modelId, id)),
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
d.delete(models).where(eq(models.id, id)),
]);
await deleteUnusedTags();
}
function chunk<T>(items: T[], size: number): T[][] {
+91
View File
@@ -0,0 +1,91 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { modelFamilies, parseRepoMetadata } from "./hub/metadata";
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search";
describe("parseRepoMetadata (real Hub responses, trimmed)", () => {
it("unsloth GGUF quant of Qwen", () => {
const m = parseRepoMetadata({
id: "unsloth/Qwen3-8B-GGUF",
author: "unsloth",
pipeline_tag: "text-generation",
tags: ["transformers", "gguf", "qwen3", "qwen", "unsloth", "base_model:Qwen/Qwen3-8B", "base_model:quantized:Qwen/Qwen3-8B", "license:apache-2.0", "endpoints_compatible", "conversational", "arxiv:2309.00071"],
cardData: { base_model: "Qwen/Qwen3-8B", license: "apache-2.0" },
gguf: { architecture: "qwen3" },
});
assert.deepEqual(m.baseModels, ["Qwen/Qwen3-8B"]);
assert.equal(m.architecture, "qwen3");
assert.equal(m.license, "apache-2.0");
assert.deepEqual(m.hubTags, ["transformers", "gguf", "qwen3", "qwen", "unsloth"]);
assert.deepEqual(modelFamilies("unsloth/Qwen3-8B-GGUF", m.baseModels), ["Qwen"]);
});
it("finetune with base_model as array and config.model_type", () => {
const m = parseRepoMetadata({
id: "TheDrummer/Cydonia-24B-v4.1",
author: "TheDrummer",
tags: ["safetensors", "mistral"],
cardData: { base_model: ["mistralai/Mistral-Small-3.2-24B-Instruct-2507"] },
config: { model_type: "mistral" },
});
assert.deepEqual(m.baseModels, ["mistralai/Mistral-Small-3.2-24B-Instruct-2507"]);
assert.equal(m.architecture, "mistral");
assert.deepEqual(modelFamilies("TheDrummer/Cydonia-24B-v4.1", m.baseModels), ["mistralai"]);
});
it("falls back to base_model tags; original models are their own family", () => {
const m = parseRepoMetadata({ id: "x/y", tags: ["base_model:finetune:Qwen/Qwen3-8B-Base"] });
assert.deepEqual(m.baseModels, ["Qwen/Qwen3-8B-Base"]);
assert.equal(m.author, "x");
assert.deepEqual(modelFamilies("Qwen/Qwen3-8B", []), ["Qwen"]);
});
});
const model = (over: Partial<SearchableModel>): SearchableModel => ({
repoId: "unsloth/Qwen3-8B-GGUF",
author: "unsloth",
families: ["Qwen"],
baseModels: ["Qwen/Qwen3-8B"],
architecture: "qwen3",
quants: ["Q4_K_M"],
tags: ["roleplay"],
hubTags: ["gguf"],
pipelineTag: "text-generation",
license: "apache-2.0",
status: "ready",
...over,
});
describe("matchesQuery", () => {
it("matches author, family, quant and tags case-insensitively, all terms required", () => {
const m = model({});
assert.ok(matchesQuery(m, "qwen"));
assert.ok(matchesQuery(m, "unsloth qwen"));
assert.ok(matchesQuery(m, "q4_k_m"));
assert.ok(matchesQuery(m, "ROLEPLAY"));
assert.ok(matchesQuery(m, " "));
assert.ok(!matchesQuery(m, "unsloth gemma"));
});
});
describe("filters and facet counts", () => {
const models = [
model({}),
model({ repoId: "bartowski/Qwen_Qwen3-8B-GGUF", author: "bartowski", quants: ["Q6_K"], tags: [] }),
model({ repoId: "unsloth/gemma-3-27b-it-GGUF", families: ["google"], quants: ["Q4_K_M"], tags: ["security"] }),
];
it("ORs within a facet and ANDs across facets", () => {
const f = { ...EMPTY_FILTERS, author: ["unsloth"], quant: ["Q4_K_M", "Q6_K"] };
assert.deepEqual(
models.filter((m) => matchesFilters(m, f)).map((m) => m.repoId),
["unsloth/Qwen3-8B-GGUF", "unsloth/gemma-3-27b-it-GGUF"],
);
});
it("counts a facet without applying its own selection", () => {
const f = { ...EMPTY_FILTERS, author: ["unsloth"] };
assert.deepEqual(facetCounts(models, "author", "", f), [["unsloth", 2], ["bartowski", 1]]);
assert.deepEqual(facetCounts(models, "family", "", f), [["google", 1], ["Qwen", 1]]);
});
});
+88
View File
@@ -0,0 +1,88 @@
// Library search and facet filtering (runs in the browser; the library is small).
export type SearchableModel = {
repoId: string;
author: string;
families: string[];
baseModels: string[];
architecture: string | null;
quants: string[];
tags: string[];
hubTags: string[];
pipelineTag: string | null;
license: string | null;
status: string;
};
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
export type Facet = (typeof FACETS)[number];
export type Filters = Record<Facet, string[]>;
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] };
export function facetValues(m: SearchableModel, facet: Facet): string[] {
switch (facet) {
case "author":
return [m.author];
case "family":
return m.families;
case "quant":
return m.quants;
case "tag":
return m.tags;
case "status":
return [m.status];
}
}
function haystack(m: SearchableModel): string {
return [
m.repoId,
m.author,
...m.families,
...m.baseModels,
m.architecture,
...m.quants,
...m.tags,
...m.hubTags,
m.pipelineTag,
m.license,
m.status,
]
.filter(Boolean)
.join(" ")
.toLowerCase();
}
/** Every whitespace-separated term must appear somewhere (case-insensitive substring). */
export function matchesQuery(m: SearchableModel, query: string): boolean {
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
if (terms.length === 0) return true;
const text = haystack(m);
return terms.every((t) => text.includes(t));
}
/** OR within a facet, AND across facets. Values compare case-insensitively. */
export function matchesFilters(m: SearchableModel, filters: Filters, except?: Facet): boolean {
return FACETS.every((facet) => {
const wanted = filters[facet];
if (facet === except || wanted.length === 0) return true;
const have = facetValues(m, facet).map((v) => v.toLowerCase());
return wanted.some((w) => have.includes(w.toLowerCase()));
});
}
/**
* Value counts for one facet, computed over the models that match the query and all *other*
* facets, so picking e.g. an author narrows the quant counts but not the author list itself.
*/
export function facetCounts(models: SearchableModel[], facet: Facet, query: string, filters: Filters) {
const counts = new Map<string, number>();
for (const m of models) {
if (!matchesQuery(m, query) || !matchesFilters(m, filters, facet)) continue;
for (const v of new Set(facetValues(m, facet))) counts.set(v, (counts.get(v) ?? 0) + 1);
}
// Keep selected values visible even if their count dropped to 0.
for (const v of filters[facet]) if (!counts.has(v)) counts.set(v, 0);
return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true }));
}
+71
View File
@@ -0,0 +1,71 @@
import "server-only";
import { and, asc, eq, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { modelTags, models, tags } from "@/lib/db/schema";
export const TAG_MAX_LENGTH = 40;
export class TagError extends Error {
constructor(
public code: "invalid" | "not_found",
message: string,
public status: number,
) {
super(message);
}
}
export type Tag = { id: string; name: string };
/** Trim and collapse whitespace; the slug (lowercase) decides uniqueness. */
export function normalizeTagName(raw: string): { name: string; slug: string } {
const name = raw.trim().replace(/\s+/g, " ");
if (!name) throw new TagError("invalid", "Tag name is empty.", 400);
if (name.length > TAG_MAX_LENGTH) throw new TagError("invalid", `Tag names are at most ${TAG_MAX_LENGTH} characters.`, 400);
return { name, slug: name.toLowerCase() };
}
/** All tags with how many models use them (for autocomplete). */
export async function listTags(): Promise<(Tag & { count: number })[]> {
return db()
.select({ id: tags.id, name: tags.name, count: sql<number>`count(${modelTags.modelId})` })
.from(tags)
.leftJoin(modelTags, eq(modelTags.tagId, tags.id))
.groupBy(tags.id)
.orderBy(asc(tags.slug));
}
export async function modelTagList(modelId: string): Promise<Tag[]> {
return db()
.select({ id: tags.id, name: tags.name })
.from(modelTags)
.innerJoin(tags, eq(tags.id, modelTags.tagId))
.where(eq(modelTags.modelId, modelId))
.orderBy(asc(tags.slug));
}
/** Attach a tag (created on first use; matched case-insensitively) to a model. */
export async function addTag(modelId: string, rawName: string): Promise<Tag> {
const { name, slug } = normalizeTagName(rawName);
const d = db();
const model = await d.query.models.findFirst({ columns: { id: true }, where: eq(models.id, modelId) });
if (!model) throw new TagError("not_found", "Model not found.", 404);
await d.insert(tags).values({ id: ulid(), name, slug }).onConflictDoNothing({ target: tags.slug });
const tag = await d.query.tags.findFirst({ columns: { id: true, name: true }, where: eq(tags.slug, slug) });
if (!tag) throw new Error("tag vanished after insert");
await d.insert(modelTags).values({ modelId, tagId: tag.id }).onConflictDoNothing();
return tag;
}
/** Detach a tag; tags no model uses anymore are deleted. */
export async function removeTag(modelId: string, tagId: string): Promise<void> {
const d = db();
await d.delete(modelTags).where(and(eq(modelTags.modelId, modelId), eq(modelTags.tagId, tagId)));
await deleteUnusedTags();
}
export async function deleteUnusedTags(): Promise<void> {
await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`);
}
+6
View File
@@ -9,6 +9,7 @@ import { db } from "@/lib/db/client";
import { runMigrations } from "@/lib/db/migrate";
import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { backfillMetadata } from "@/lib/hub/refresh";
import { DownloadRunner } from "./download";
import { log } from "./log";
import { settleModelStatus } from "./model-status";
@@ -269,6 +270,11 @@ async function main() {
if (hfVersion) log.info(`hf CLI: ${hfVersion}, xet ${env.HF_HUB_DISABLE_XET ? "disabled" : "enabled"}`);
else log.warn("hf CLI not found on PATH; downloads will fail until it is installed");
// Models added before Hub metadata was stored (search/filters need it).
backfillMetadata((repoId, err) => log.warn(`metadata for ${repoId} failed: ${err instanceof Error ? err.message : err}`))
.then((n) => n > 0 && log.info(`fetched Hub metadata for ${n} model(s)`))
.catch((err) => log.error("metadata backfill failed", err));
await heartbeat();
timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS));
timers.push(setInterval(() => void tick(), TICK_MS));