Milestone (b): repo lookup and file selection

- Hub API client: resolve revision to SHA, paginated recursive file tree,
  gated-access probe, readable error mapping
- Add-model page with quant quick-select, fnmatch-compatible include/exclude
  globs, selection summary and free-space hint
- Models stored pinned to the reviewed SHA with full file list and selection rule
- Library list, model detail page, remove (never-downloaded models only)
- Worker reports MODELS_DIR free space; unit tests for selection logic

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 15:39:45 +02:00
1 parent 891e496157
commit 8f7ac60ccf
35 files changed
+2567 -19

No files matched your search

+27
View File
@@ -6,6 +6,33 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.2.0] - 2026-10-05
Milestone (b): repo lookup and file selection.
### Added
- "Add model" page: look up a Hub repo by ID or pasted URL (`/tree/<rev>` URLs pick up the
revision), resolve the revision to its commit SHA and list all files with sizes.
- File selection with checkboxes, quick-select chips per GGUF quant (flat repos, split files and
folder-per-quant repos), and include/exclude glob fields with the same matching rules as
`hf download` (Python `fnmatch`, `*` crosses folders, trailing `/` = whole folder).
- Live selection summary (file count, total size) with free space on the models volume.
- Models are stored pinned to the reviewed commit SHA, with the full file list (size, git blob
SHA-1, LFS SHA-256) and the selection rule; checkbox picks are stored as escaped exact-path globs
so the rule can be re-applied to newer revisions.
- Library list (repo, selected quant, size, pinned `revision@sha`, status) and a model detail page.
- Removing a model that was never downloaded.
- Hub API client (`src/lib/hub`) with clear errors: invalid repo ID, repo not found (or private),
revision not found, gated repo without token / without granted access (checked up front with a
HEAD request), invalid token, rate limit, network errors.
- Worker reports free/total space of `MODELS_DIR` with its heartbeat (migration `0001`).
- Unit tests for glob matching and quant grouping (`npm test`, Node's built-in runner).
### Changed
- `.gitattributes` keeps LF line endings in the repo (the app runs in Linux containers).
## [0.1.0] - 2026-10-05
Milestone (a): project skeleton and OIDC login.
+1
View File
@@ -28,4 +28,5 @@ Other scripts:
| `npm run dev:web` / `npm run dev:worker` | run one side only |
| `npm run db:generate` | create a migration after changing `src/lib/db/schema.ts` |
| `npm run db:migrate` | apply migrations without starting the worker |
| `npm test` | unit tests (Node test runner via tsx) |
| `npm run typecheck`, `npm run lint` | checks |
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `worker_state` ADD `models_dir_free_bytes` integer;--> statement-breakpoint
ALTER TABLE `worker_state` ADD `models_dir_total_bytes` integer;
+725
View File
@@ -0,0 +1,725 @@
{
"version": "6",
"dialect": "sqlite",
"id": "4e7ad000-61ee-41cc-94ab-ce600f479a95",
"prevId": "d6f6feea-3dd0-41f3-82af-fe63d09ca635",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+7
View File
@@ -8,6 +8,13 @@
"when": 1791206191116,
"tag": "0000_init",
"breakpoints": true
},
{
"idx": 1,
"version": "6",
"when": 1791207195702,
"tag": "0001_worker_disk_space",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.1.0",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.1.0",
"version": "0.2.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.1.0",
"version": "0.2.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -12,7 +12,8 @@
"lint": "eslint",
"typecheck": "next typegen && tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts"
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
"test": "tsx --test \"src/**/*.test.ts\""
},
"dependencies": {
"@base-ui/react": "^1.8.0",
+3
View File
@@ -22,6 +22,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<Link href="/" className="hover:text-foreground">
Library
</Link>
<Link href="/models/new" className="hover:text-foreground">
Add model
</Link>
</nav>
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
+91
View File
@@ -0,0 +1,91 @@
import { notFound } from "next/navigation";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes, formatDate } from "@/lib/format";
import { getModel } from "@/lib/library";
import { RemoveModelButton } from "./remove-model-button";
export const dynamic = "force-dynamic";
export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
const { id } = await params;
const data = await getModel(id);
if (!data) notFound();
const { model, files } = data;
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold break-all">{model.repoId}</h1>
<ModelStatusBadge status={model.status} />
<div className="ml-auto">{model.status === "pending" && <RemoveModelButton id={model.id} />}</div>
</div>
<Card>
<CardHeader>
<CardTitle>Details</CardTitle>
<CardDescription>Downloading starts in the next milestone.</CardDescription>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm">
<dt className="text-muted-foreground">Hub</dt>
<dd>
<a
href={`https://huggingface.co/${model.repoId}/tree/${model.pinnedSha}`}
target="_blank"
rel="noreferrer"
className="underline"
>
huggingface.co/{model.repoId}
</a>
</dd>
<dt className="text-muted-foreground">Tracked revision</dt>
<dd className="font-mono">{model.trackedRevision}</dd>
<dt className="text-muted-foreground">Pinned SHA</dt>
<dd className="font-mono break-all">{model.pinnedSha}</dd>
<dt className="text-muted-foreground">Local path</dt>
<dd className="font-mono break-all">$MODELS_DIR/{model.localPath}</dd>
<dt className="text-muted-foreground">Include</dt>
<dd className="font-mono text-xs break-all">{model.includePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Exclude</dt>
<dd className="font-mono text-xs break-all">{model.excludePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Added</dt>
<dd>{formatDate(model.createdAt)}</dd>
</dl>
</CardContent>
</Card>
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>
Selected files · {selected.length} · {formatBytes(totalBytes)}
</CardTitle>
<CardDescription>
{files.length - selected.length} other files in the repo are not selected.
</CardDescription>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>File</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>State</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{selected.map((f) => (
<TableRow key={f.id}>
<TableCell className="font-mono text-xs break-all whitespace-normal">{f.path}</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="text-sm text-muted-foreground">{f.state}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</div>
);
}
@@ -0,0 +1,57 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
/** Removes a not-yet-downloaded model from the library (DB only, no files exist yet). */
export function RemoveModelButton({ id }: { id: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function remove() {
setBusy(true);
const res = await fetch(`/api/models/${id}`, { method: "DELETE" });
if (res.ok) {
toast.success("Removed from library");
router.push("/");
router.refresh();
} else {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Remove failed (${res.status})`);
setBusy(false);
}
}
return (
<AlertDialog>
<AlertDialogTrigger render={<Button variant="destructive" size="sm" />}>Remove</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove from library?</AlertDialogTitle>
<AlertDialogDescription>
Nothing has been downloaded yet, so this only removes the entry.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove} disabled={busy}>
Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
+343
View File
@@ -0,0 +1,343 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes, shortSha } from "@/lib/format";
import type { LookupResult } from "@/lib/hub/lookup";
import { escapeGlob, matchesAny, parsePatternList, quantGroup } from "@/lib/selection";
type ApiErrorBody = { error?: { code: string; message: string } };
async function postJson<T>(url: string, body: unknown): Promise<T> {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = (await res.json().catch(() => ({}))) as T & ApiErrorBody;
if (!res.ok) throw new Error(json.error?.message ?? `Request failed (${res.status})`);
return json;
}
export function AddModelForm({ freeBytes }: { freeBytes: number | null }) {
const router = useRouter();
const [repo, setRepo] = useState("");
const [revision, setRevision] = useState("main");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<LookupResult | null>(null);
const [checked, setChecked] = useState<Set<string>>(new Set());
const [includeText, setIncludeText] = useState("");
const [excludeText, setExcludeText] = useState("");
const [submitting, setSubmitting] = useState(false);
async function lookup(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
try {
const r = await postJson<LookupResult>("/api/hub/lookup", { repo, revision });
setResult(r);
setRevision(r.revision);
setChecked(new Set());
setIncludeText("");
setExcludeText("");
} catch (err) {
setResult(null);
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const files = useMemo(() => {
if (!result) return [];
return result.files.map((f) => {
const byPattern = matchesAny(f.path, includePatterns);
const excluded = matchesAny(f.path, excludePatterns);
return {
...f,
group: quantGroup(f.path),
byPattern,
excluded,
selected: (checked.has(f.path) || byPattern) && !excluded,
};
});
}, [result, checked, includePatterns, excludePatterns]);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
for (const f of files) {
if (!f.group) continue;
const g = m.get(f.group) ?? { paths: [], size: 0 };
g.paths.push(f.path);
g.size += f.size;
m.set(f.group, g);
}
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [files]);
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
function toggle(path: string, on: boolean) {
setChecked((prev) => {
const next = new Set(prev);
if (on) next.add(path);
else next.delete(path);
return next;
});
}
function toggleGroup(paths: string[]) {
setChecked((prev) => {
const next = new Set(prev);
const allOn = paths.every((p) => next.has(p));
for (const p of paths) {
if (allOn) next.delete(p);
else next.add(p);
}
return next;
});
}
async function addToLibrary() {
if (!result) return;
setSubmitting(true);
try {
const { id } = await postJson<{ id: string }>("/api/models", {
repoId: result.repoId,
revision: result.revision,
sha: result.sha,
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
exclude: excludePatterns,
});
toast.success(`${result.repoId} added to the library`);
router.push(`/models/${id}`);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
setSubmitting(false);
}
}
return (
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Hugging Face repository</CardTitle>
<CardDescription>Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={lookup} className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor="repo">Repo ID</Label>
<Input
id="repo"
value={repo}
onChange={(e) => setRepo(e.target.value)}
placeholder="unsloth/Qwen3-8B-GGUF"
autoComplete="off"
spellCheck={false}
required
/>
</div>
<div className="flex flex-col gap-1.5 sm:w-48">
<Label htmlFor="revision">Revision</Label>
<Input
id="revision"
value={revision}
onChange={(e) => setRevision(e.target.value)}
placeholder="main"
spellCheck={false}
/>
</div>
<Button type="submit" disabled={loading || !repo.trim()}>
{loading ? "Looking up…" : "Look up"}
</Button>
</form>
{error && (
<p role="alert" className="mt-3 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</p>
)}
</CardContent>
</Card>
{result && (
<>
<Card>
<CardHeader>
<CardTitle className="flex flex-wrap items-center gap-2">
<a
href={`https://huggingface.co/${result.repoId}`}
target="_blank"
rel="noreferrer"
className="hover:underline"
>
{result.repoId}
</a>
{result.gated && <Badge variant="outline">gated ({result.gated}), access OK</Badge>}
</CardTitle>
<CardDescription>
{result.revision} →{" "}
<code className="font-mono" title={result.sha}>
{shortSha(result.sha)}
</code>
{" · "}
{result.files.length} files · {formatBytes(result.files.reduce((s, f) => s + f.size, 0))} total
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{result.existingModelId && (
<p className="rounded-md bg-muted px-3 py-2 text-sm">
This repo is already in the library.{" "}
<Link href={`/models/${result.existingModelId}`} className="underline">
Open it
</Link>
</p>
)}
{groups.length > 0 && (
<div className="flex flex-col gap-1.5">
<Label>Quick select a quant</Label>
<div className="flex flex-wrap gap-1.5">
{groups.map(([name, g]) => {
const on = g.paths.every((p) => checked.has(p));
return (
<Button
key={name}
type="button"
size="sm"
variant={on ? "default" : "outline"}
onClick={() => toggleGroup(g.paths)}
title={g.paths.join("\n")}
>
{name}
<span className="text-xs opacity-70">{formatBytes(g.size)}</span>
</Button>
);
})}
</div>
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="include">Include patterns</Label>
<Input
id="include"
value={includeText}
onChange={(e) => setIncludeText(e.target.value)}
placeholder="*Q4_K_M*, *.json"
spellCheck={false}
className="font-mono"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="exclude">Exclude patterns</Label>
<Input
id="exclude"
value={excludeText}
onChange={(e) => setExcludeText(e.target.value)}
placeholder="*mmproj*"
spellCheck={false}
className="font-mono"
/>
</div>
<p className="text-xs text-muted-foreground sm:col-span-2">
Comma-separated globs, same rules as <code>hf download --include/--exclude</code>:{" "}
<code>*</code> also matches <code>/</code>, a trailing <code>/</code> matches a whole
folder. Selected = checked or matching an include pattern, minus excludes.
</p>
</div>
</CardContent>
</Card>
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10" />
<TableHead>File</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden w-20 sm:table-cell">Storage</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{files.map((f) => (
<TableRow key={f.path} data-state={f.selected ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={f.selected}
disabled={f.byPattern || f.excluded}
onCheckedChange={(v) => toggle(f.path, v === true)}
aria-label={`Select ${f.path}`}
title={
f.excluded
? "Excluded by a pattern"
: f.byPattern
? "Selected by an include pattern"
: undefined
}
/>
</TableCell>
<TableCell className="font-mono text-xs break-all whitespace-normal">
{f.path}
{f.excluded && <span className="ml-2 text-muted-foreground">(excluded)</span>}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{f.lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
<div className="sticky bottom-0 -mx-4 border-t bg-background/95 px-4 py-3 backdrop-blur">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
{selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{freeBytes != null && (
<span className={notEnoughSpace ? "ml-2 text-destructive" : "ml-2 text-muted-foreground"}>
({formatBytes(freeBytes)} free on the models volume)
</span>
)}
</div>
<div className="ml-auto flex gap-2">
<Button type="button" variant="ghost" onClick={() => setChecked(new Set())}>
Clear
</Button>
<Button
type="button"
onClick={addToLibrary}
disabled={selected.length === 0 || submitting || !!result.existingModelId}
>
{submitting ? "Adding…" : "Add to library"}
</Button>
</div>
</div>
</div>
</>
)}
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { getWorkerStatus } from "@/lib/worker-status";
import { AddModelForm } from "./add-model-form";
export const dynamic = "force-dynamic";
export default async function AddModelPage() {
const worker = await getWorkerStatus();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Add model</h1>
<AddModelForm freeBytes={worker.online ? worker.modelsDirFreeBytes : null} />
</div>
);
}
+67 -8
View File
@@ -1,15 +1,74 @@
import Link from "next/link";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes, formatDate, shortSha } from "@/lib/format";
import { listLibrary } from "@/lib/library";
export const dynamic = "force-dynamic";
export default async function LibraryPage() {
const rows = await listLibrary();
export default function LibraryPage() {
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Library</h1>
<Card>
<CardHeader>
<CardTitle>No models yet</CardTitle>
<CardDescription>Adding models from Hugging Face comes in the next milestone.</CardDescription>
</CardHeader>
</Card>
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Library</h1>
<Link href="/models/new" className={buttonVariants()}>
Add model
</Link>
</div>
{rows.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>No models yet</CardTitle>
<CardDescription>Add a Hugging Face repo to get started.</CardDescription>
</CardHeader>
</Card>
) : (
<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>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((r) => (
<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">
{formatDate(r.downloadedAt)}
</TableCell>
<TableCell>
<ModelStatusBadge status={r.status} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
)}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { handleApiError } from "@/lib/api-errors";
import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup";
const Body = z.object({
repo: z.string().trim().min(1),
revision: z.string().trim().optional(),
});
/** Resolve a repo + revision to a commit SHA and list its files with sizes. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
const { repoId, revision: urlRevision } = normalizeRepoInput(body.repo);
const revision = body.revision || urlRevision || "main";
return NextResponse.json(await lookupRepo(repoId, revision));
} catch (err) {
return handleApiError(err);
}
});
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { ModelError, removeModel } from "@/lib/models";
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await removeModel(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
import { addModel, ModelError } from "@/lib/models";
const Body = z.object({
repoId: z.string().regex(REPO_ID_RE),
revision: z.string().trim().min(1).max(255),
sha: z.string().regex(SHA_RE, "must be a full 40-character commit SHA"),
include: z.array(z.string().min(1).max(1024)).max(10_000),
exclude: z.array(z.string().min(1).max(1024)).max(1_000),
});
/** Add a model to the library, pinned to the SHA the user reviewed. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
const { id } = await addModel({
repoId: body.repoId,
revision: body.revision,
sha: body.sha,
rule: { include: body.include, exclude: body.exclude },
});
return NextResponse.json({ id }, { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+16
View File
@@ -0,0 +1,16 @@
import { Badge } from "@/components/ui/badge";
import type { ModelStatus } from "@/lib/db/schema";
const LABELS: 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" },
incomplete: { label: "missing files", variant: "destructive" },
failed: { label: "failed", variant: "destructive" },
deleting: { label: "deleting", variant: "secondary" },
};
export function ModelStatusBadge({ status }: { status: ModelStatus }) {
const { label, variant } = LABELS[status];
return <Badge variant={variant}>{label}</Badge>;
}
+187
View File
@@ -0,0 +1,187 @@
"use client"
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: AlertDialogPrimitive.Backdrop.Props) {
return (
<AlertDialogPrimitive.Backdrop
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: AlertDialogPrimitive.Popup.Props & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Popup
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn(
"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof Button>) {
return (
<Button
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: AlertDialogPrimitive.Close.Props &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<AlertDialogPrimitive.Close
data-slot="alert-dialog-cancel"
className={cn(className)}
render={<Button variant={variant} size={size} />}
{...props}
/>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}
+28
View File
@@ -0,0 +1,28 @@
"use client"
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"
import { cn } from "cn"
import { CheckIcon } from "lucide-react"
function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
>
<CheckIcon
/>
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }
+19
View File
@@ -0,0 +1,19 @@
import * as React from "react"
import { Input as InputPrimitive } from "@base-ui/react/input"
import { cn } from "cn"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<InputPrimitive
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }
+19
View File
@@ -0,0 +1,19 @@
"use client"
import * as React from "react"
import { cn } from "cn"
function Label({ className, ...props }: React.ComponentProps<"label">) {
return (
<label
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+13
View File
@@ -0,0 +1,13 @@
import { cn } from "cn"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
}
export { Skeleton }
+115
View File
@@ -0,0 +1,115 @@
"use client"
import * as React from "react"
import { cn } from "cn"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+65
View File
@@ -0,0 +1,65 @@
"use client"
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
import { cn } from "cn"
function TooltipProvider({
delay = 0,
...props
}: TooltipPrimitive.Provider.Props) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delay={delay}
{...props}
/>
)
}
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
}
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
side = "top",
sideOffset = 4,
align = "center",
alignOffset = 0,
children,
...props
}: TooltipPrimitive.Popup.Props &
Pick<
TooltipPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Positioner
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
className="isolate z-50"
>
<TooltipPrimitive.Popup
data-slot="tooltip-content"
className={cn(
"z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
</TooltipPrimitive.Popup>
</TooltipPrimitive.Positioner>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
+29
View File
@@ -0,0 +1,29 @@
import "server-only";
import { NextResponse } from "next/server";
import { z } from "zod";
import { HubError } from "@/lib/hub/client";
export type ApiError = { error: { code: string; message: string } };
export function apiError(status: number, code: string, message: string) {
return NextResponse.json<ApiError>({ error: { code, message } }, { status });
}
const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
invalid_repo_id: 400,
repo_not_found: 404,
revision_not_found: 404,
gated_no_token: 403,
gated_no_access: 403,
rate_limited: 429,
network: 502,
};
/** Turn known errors into JSON responses; rethrow anything unexpected. */
export function handleApiError(err: unknown) {
if (err instanceof HubError) return apiError(HUB_STATUS[err.code] ?? 502, err.code, err.message);
if (err instanceof z.ZodError) {
return apiError(400, "invalid_request", err.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));
}
throw err;
}
+3
View File
@@ -241,6 +241,9 @@ export const workerState = sqliteTable("worker_state", {
id: text("id").primaryKey(), // "worker"
pid: integer("pid"),
hfVersion: text("hf_version"),
/** Free/total bytes on the filesystem holding MODELS_DIR (the web app has no access to it). */
modelsDirFreeBytes: integer("models_dir_free_bytes"),
modelsDirTotalBytes: integer("models_dir_total_bytes"),
startedAt: ts("started_at").notNull(),
heartbeatAt: ts("heartbeat_at").notNull(),
});
+23
View File
@@ -0,0 +1,23 @@
const UNITS = ["B", "KB", "MB", "GB", "TB", "PB"];
/** Decimal units (like the Hub UI): 4_793_624_384 -> "4.79 GB". */
export function formatBytes(bytes: number | null | undefined): string {
if (bytes == null || !Number.isFinite(bytes)) return "–";
if (bytes < 1000) return `${bytes} B`;
let v = bytes;
let i = 0;
while (v >= 1000 && i < UNITS.length - 1) {
v /= 1000;
i++;
}
return `${v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)} ${UNITS[i]}`;
}
export function shortSha(sha: string | null | undefined): string {
return sha ? sha.slice(0, 7) : "–";
}
export function formatDate(d: Date | string | number | null | undefined): string {
if (d == null) return "–";
return new Date(d).toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short" });
}
+202
View File
@@ -0,0 +1,202 @@
// Minimal Hugging Face Hub API client (metadata only; downloads go through the `hf` CLI).
// Server-side only: it reads HF_TOKEN from the environment. Never import from client components.
import { coreEnv } from "@/lib/env";
const HUB = "https://huggingface.co";
const TIMEOUT_MS = 20_000;
const USER_AGENT = "kaname-model-manager";
export const REPO_ID_RE = /^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/;
export const SHA_RE = /^[0-9a-f]{40}$/;
export type HubErrorCode =
| "invalid_repo_id"
| "invalid_token"
| "repo_not_found" // or private without access
| "revision_not_found"
| "gated_no_token"
| "gated_no_access"
| "rate_limited"
| "network"
| "unknown";
export class HubError extends Error {
constructor(
public code: HubErrorCode,
message: string,
public status?: number,
) {
super(message);
this.name = "HubError";
}
}
export type HubFile = {
path: string;
size: number;
/** Git blob SHA-1. */
blobOid: string;
/** SHA-256 of the content, for LFS/Xet files. */
lfsSha256: string | null;
xetHash: string | null;
};
export type RepoInfo = {
repoId: string;
sha: string;
gated: false | "auto" | "manual";
private: boolean;
lastModified: string | null;
};
function headers(): HeadersInit {
const h: Record<string, string> = { "User-Agent": USER_AGENT };
const token = coreEnv().HF_TOKEN;
if (token) h.Authorization = `Bearer ${token}`;
return h;
}
async function hubFetch(url: string, init: RequestInit = {}): Promise<Response> {
try {
return await fetch(url, {
...init,
headers: { ...headers(), ...init.headers },
cache: "no-store",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
throw new HubError("network", `Could not reach huggingface.co (${reason}).`);
}
}
/** Is the configured token valid? Only called after a 401, to tell a bad token from a missing repo. */
async function tokenIsValid(): Promise<boolean> {
const res = await hubFetch(`${HUB}/api/whoami-v2`);
return res.ok;
}
async function toHubError(res: Response, repoId: string, revision?: string): Promise<HubError> {
const code = res.headers.get("x-error-code");
const hasToken = Boolean(coreEnv().HF_TOKEN);
if (code === "RevisionNotFound") {
return new HubError("revision_not_found", `Revision "${revision}" not found in ${repoId}.`, res.status);
}
if (code === "GatedRepo") {
return hasToken
? new HubError(
"gated_no_access",
`${repoId} is gated and this token's account has not been granted access. Request access at ${HUB}/${repoId}.`,
res.status,
)
: new HubError(
"gated_no_token",
`${repoId} is gated. Set HF_TOKEN for an account that has accepted the terms at ${HUB}/${repoId}.`,
res.status,
);
}
if (res.status === 429) {
return new HubError("rate_limited", "Hugging Face rate limit hit. Try again in a minute.", res.status);
}
// The Hub answers 401 (without an error code) for missing repos when unauthenticated,
// and 401 for any request when the token is invalid.
if (res.status === 401 || res.status === 404 || code === "RepoNotFound") {
if (res.status === 401 && hasToken && !(await tokenIsValid())) {
return new HubError("invalid_token", "HF_TOKEN is invalid or expired.", res.status);
}
return new HubError(
"repo_not_found",
hasToken
? `Repository ${repoId} not found, or this token has no access to it.`
: `Repository ${repoId} not found. If it is private, set HF_TOKEN.`,
res.status,
);
}
const msg = res.headers.get("x-error-message") ?? res.statusText;
return new HubError("unknown", `Hugging Face API error ${res.status}: ${msg}`, res.status);
}
function assertRepoId(repoId: string) {
if (!REPO_ID_RE.test(repoId) || repoId.split("/").some((p) => p === "." || p === "..")) {
throw new HubError("invalid_repo_id", `"${repoId}" is not a valid repo ID (expected "org/name").`);
}
}
const enc = (s: string) => encodeURIComponent(s);
const repoPath = (repoId: string) => repoId.split("/").map(enc).join("/");
/** Resolve a branch, tag or commit to its full commit SHA, plus basic repo info. */
export async function getRepoInfo(repoId: string, revision: string): Promise<RepoInfo> {
assertRepoId(repoId);
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}`);
if (!res.ok) throw await toHubError(res, repoId, revision);
const j = (await res.json()) as {
id: string;
sha: string;
gated?: false | "auto" | "manual";
private?: boolean;
lastModified?: string;
};
return {
repoId: j.id ?? repoId,
sha: j.sha,
gated: j.gated ?? false,
private: j.private ?? false,
lastModified: j.lastModified ?? null,
};
}
type TreeEntry = {
type: "file" | "directory";
path: string;
size: number;
oid: string;
lfs?: { oid: string; size: number };
xetHash?: string;
};
/** All files (recursive) at a commit. Follows the Link header for pagination. */
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
assertRepoId(repoId);
const files: HubFile[] = [];
let url: string | null =
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
while (url) {
const res = await hubFetch(url);
if (!res.ok) throw await toHubError(res, repoId, sha);
for (const e of (await res.json()) as TreeEntry[]) {
if (e.type !== "file") continue;
files.push({
path: e.path,
size: e.size,
blobOid: e.oid,
lfsSha256: e.lfs?.oid ?? null,
xetHash: e.xetHash ?? null,
});
}
url = nextLink(res.headers.get("link"));
}
return files.sort((a, b) => a.path.localeCompare(b.path));
}
function nextLink(link: string | null): string | null {
if (!link) return null;
for (const part of link.split(",")) {
const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/);
if (m) return m[1];
}
return null;
}
/**
* For gated repos the file list is public, but downloads need accepted terms.
* Probe one file with a HEAD request (no body is downloaded) to find out early.
*/
export async function checkFileAccess(repoId: string, sha: string, path: string): Promise<void> {
const url = `${HUB}/${repoPath(repoId)}/resolve/${enc(sha)}/${path.split("/").map(enc).join("/")}`;
const res = await hubFetch(url, { method: "HEAD", redirect: "manual" });
if (res.ok || (res.status >= 300 && res.status < 400)) return;
throw await toHubError(res, repoId, sha);
}
+57
View File
@@ -0,0 +1,57 @@
import "server-only";
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
import { checkFileAccess, getRepoInfo, type HubFile, listFiles, type RepoInfo } from "./client";
export type LookupResult = {
repoId: string;
revision: string;
sha: string;
gated: RepoInfo["gated"];
lastModified: string | null;
files: HubFile[];
/** Set when this repo is already in the library. */
existingModelId: string | null;
};
/**
* Accept "org/name", or a pasted Hub URL like https://huggingface.co/org/name/tree/main.
* Returns the repo id and, if the URL contained one, the revision.
*/
export function normalizeRepoInput(input: string): { repoId: string; revision?: string } {
let s = input.trim();
const url = s.match(/^https?:\/\/(?:www\.)?huggingface\.co\/(.+)$/i);
if (url) s = url[1];
s = s.replace(/[?#].*$/, "").replace(/\/+$/, "");
const parts = s.split("/");
const repoId = parts.slice(0, 2).join("/");
const revision = parts[2] === "tree" || parts[2] === "blob" ? parts[3] : undefined;
return { repoId, revision };
}
/** Repo metadata + file list at the resolved commit, with an early access check for gated repos. */
export async function lookupRepo(repoId: string, revision: string): Promise<LookupResult> {
const info = await getRepoInfo(repoId, revision);
const files = await listFiles(info.repoId, info.sha);
if (info.gated && files.length > 0) {
const smallest = files.reduce((a, b) => (b.size < a.size ? b : a));
await checkFileAccess(info.repoId, info.sha, smallest.path);
}
const existing = await db().query.models.findFirst({
columns: { id: true },
where: and(eq(models.repoType, "model"), eq(models.repoId, info.repoId)),
});
return {
repoId: info.repoId,
revision,
sha: info.sha,
gated: info.gated,
lastModified: info.lastModified,
files,
existingModelId: existing?.id ?? null,
};
}
+58
View File
@@ -0,0 +1,58 @@
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 { quantGroup } from "@/lib/selection";
export type LibraryRow = Awaited<ReturnType<typeof listLibrary>>[number];
/** Models with their selected-file totals and a short "which quant" label. */
export async function listLibrary() {
const d = db();
const rows = await d
.select({
id: models.id,
repoId: models.repoId,
trackedRevision: models.trackedRevision,
pinnedSha: models.pinnedSha,
remoteSha: models.remoteSha,
status: models.status,
createdAt: models.createdAt,
downloadedAt: models.downloadedAt,
fileCount: sql<number>`count(${modelFiles.id})`,
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
})
.from(models)
.leftJoin(modelFiles, and(eq(modelFiles.modelId, models.id), eq(modelFiles.selected, true)))
.groupBy(models.id)
.orderBy(desc(models.createdAt));
const selected = await d
.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);
}
return rows.map((r) => ({
...r,
quants: [...(quants.get(r.id) ?? [])].sort(),
}));
}
export async function getModel(id: string) {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) return null;
const files = await d
.select()
.from(modelFiles)
.where(eq(modelFiles.modelId, id))
.orderBy(asc(modelFiles.path));
return { model, files };
}
+104
View File
@@ -0,0 +1,104 @@
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 { checkFileAccess, getRepoInfo, listFiles } from "@/lib/hub/client";
import { isSelected, type SelectionRule } from "@/lib/selection";
export class ModelError extends Error {
constructor(
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable",
message: string,
public status: number,
) {
super(message);
}
}
const INSERT_CHUNK = 500;
/**
* Add a model pinned to `sha`. The file list is re-fetched from the Hub at that commit
* (the client's copy isn't trusted) and the selection rule is applied server-side.
*/
export async function addModel(input: {
repoId: string;
revision: string;
sha: string;
rule: SelectionRule;
}): Promise<{ id: string }> {
const info = await getRepoInfo(input.repoId, input.sha);
const repoId = info.repoId;
const existing = await db().query.models.findFirst({
columns: { id: true },
where: and(eq(models.repoType, "model"), eq(models.repoId, repoId)),
});
if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409);
const files = await listFiles(repoId, info.sha);
const selectedFiles = files.filter((f) => isSelected(f.path, input.rule));
if (selectedFiles.length === 0) {
throw new ModelError("empty_selection", "No files selected.", 400);
}
if (info.gated) {
const smallest = selectedFiles.reduce((a, b) => (b.size < a.size ? b : a));
await checkFileAccess(repoId, info.sha, smallest.path);
}
const d = db();
const modelId = ulid();
const fileRows = files.map((f) => ({
modelId,
path: f.path,
size: f.size,
blobOid: f.blobOid,
lfsSha256: f.lfsSha256,
selected: isSelected(f.path, input.rule),
}));
// One atomic batch: model, its first pinned revision and the full file list.
await d.batch([
d.insert(models).values({
id: modelId,
repoId,
trackedRevision: input.revision,
pinnedSha: info.sha,
localPath: repoId,
includePatterns: input.rule.include,
excludePatterns: input.rule.exclude,
}),
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
]);
return { id: modelId };
}
/** Remove a model from the library. Only allowed before anything was downloaded (for now). */
export async function removeModel(id: string): Promise<void> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const [{ n }] = await d
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(eq(jobs.modelId, id));
if (model.status !== "pending" || n > 0) {
throw new ModelError(
"not_removable",
"Only models that were never downloaded can be removed yet. Deleting downloaded models comes in a later milestone.",
409,
);
}
await d.batch([
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
d.delete(models).where(eq(models.id, id)),
]);
}
function chunk<T>(items: T[], size: number): T[][] {
const out: T[][] = [];
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
return out;
}
+86
View File
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { escapeGlob, isSelected, matchesAny, parsePatternList, quantGroup } from "./selection";
describe("matchesAny (Python fnmatch semantics)", () => {
it("* matches across folders", () => {
assert.ok(matchesAny("Q4_K_M/model-00001-of-00003.gguf", ["*.gguf"]));
assert.ok(matchesAny("a/b/c.json", ["*c.json"]));
});
it("is anchored and case-sensitive", () => {
assert.ok(!matchesAny("model.gguf.bak", ["*.gguf"]));
assert.ok(!matchesAny("Model-Q4_K_M.GGUF", ["*.gguf"]));
});
it("? and character classes", () => {
assert.ok(matchesAny("Q4_0.gguf", ["Q?_0.gguf"]));
assert.ok(matchesAny("Q5_0.gguf", ["Q[45]_0.gguf"]));
assert.ok(!matchesAny("Q6_0.gguf", ["Q[45]_0.gguf"]));
assert.ok(matchesAny("Q6_0.gguf", ["Q[!45]_0.gguf"]));
});
it("trailing slash selects a folder", () => {
assert.ok(matchesAny("Q4_K_M/x-00001-of-00002.gguf", ["Q4_K_M/"]));
assert.ok(!matchesAny("Q4_K_S/x-00001-of-00002.gguf", ["Q4_K_M/"]));
});
it("unclosed [ is literal", () => {
assert.ok(matchesAny("a[b", ["a[b"]));
});
it("regex metacharacters in paths are literal", () => {
assert.ok(matchesAny("model (v2)+.gguf", ["model (v2)+.gguf"]));
assert.ok(!matchesAny("modelXgguf", ["model.gguf"]));
});
});
describe("escapeGlob", () => {
it("matches exactly the literal path", () => {
const weird = "dir/file[1]*?.gguf";
assert.ok(matchesAny(weird, [escapeGlob(weird)]));
assert.ok(!matchesAny("dir/file1xx.gguf", [escapeGlob(weird)]));
assert.equal(escapeGlob("plain/path.gguf"), "plain/path.gguf");
});
});
describe("isSelected", () => {
it("include minus exclude, empty include selects nothing", () => {
const rule = { include: ["*Q4_K_M*", "*.json"], exclude: ["*mmproj*"] };
assert.ok(isSelected("Qwen3-8B-Q4_K_M.gguf", rule));
assert.ok(isSelected("config.json", rule));
assert.ok(!isSelected("mmproj-Q4_K_M.gguf", rule));
assert.ok(!isSelected("README.md", rule));
assert.ok(!isSelected("anything", { include: [], exclude: [] }));
});
});
describe("parsePatternList", () => {
it("splits on commas and newlines, trims", () => {
assert.deepEqual(parsePatternList(" *.gguf, *.json\nREADME.md ,, "), ["*.gguf", "*.json", "README.md"]);
});
});
describe("quantGroup", () => {
it("flat GGUF repos", () => {
assert.equal(quantGroup("Qwen3-8B-Q4_K_M.gguf"), "Q4_K_M");
assert.equal(quantGroup("Qwen3-8B-UD-Q4_K_XL.gguf"), "UD-Q4_K_XL");
assert.equal(quantGroup("Qwen3-8B-UD-IQ1_S.gguf"), "UD-IQ1_S");
assert.equal(quantGroup("Qwen3-8B-IQ4_NL.gguf"), "IQ4_NL");
assert.equal(quantGroup("Qwen3-8B-BF16.gguf"), "BF16");
assert.equal(quantGroup("Qwen_Qwen3-8B-bf16.gguf"), "bf16");
assert.equal(quantGroup("Qwen3-8B-Q8_0.gguf"), "Q8_0");
});
it("split files group together", () => {
assert.equal(quantGroup("Model-Q4_K_M-00001-of-00002.gguf"), "Q4_K_M");
assert.equal(quantGroup("Model-Q4_K_M-00002-of-00002.gguf"), "Q4_K_M");
});
it("folder-per-quant repos use the folder", () => {
assert.equal(quantGroup("Q4_K_M/Qwen3-235B-A22B-Q4_K_M-00001-of-00003.gguf"), "Q4_K_M");
assert.equal(quantGroup("UD-Q2_K_XL/x-00001-of-00002.gguf"), "UD-Q2_K_XL");
});
it("mmproj is its own group", () => {
assert.equal(quantGroup("mmproj-F16.gguf"), "mmproj-F16");
assert.equal(quantGroup("mmproj-model-f16.gguf"), "mmproj-f16");
});
it("non-GGUF files have no group", () => {
assert.equal(quantGroup("README.md"), null);
assert.equal(quantGroup("Qwen_Qwen3-8B.imatrix"), null);
assert.equal(quantGroup("docs/notes.txt"), null);
});
});
+99
View File
@@ -0,0 +1,99 @@
// File selection rules, shared by the UI, the API and the worker.
//
// Matching follows huggingface_hub's `filter_repo_objects` (what `hf download --include/--exclude`
// uses): Python `fnmatch` against the full repo path, where `*` also matches "/", and a pattern
// ending in "/" matches everything below that folder.
const regexCache = new Map<string, RegExp>();
/** Translate a Python fnmatch pattern to a RegExp (same semantics as fnmatch.translate). */
export function fnmatchToRegExp(pattern: string): RegExp {
const cached = regexCache.get(pattern);
if (cached) return cached;
let re = "";
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
if (c === "*") {
re += ".*";
} else if (c === "?") {
re += ".";
} else if (c === "[") {
let j = i + 1;
if (pattern[j] === "!") j++;
if (pattern[j] === "]") j++;
while (j < pattern.length && pattern[j] !== "]") j++;
if (j >= pattern.length) {
re += "\\[";
} else {
let body = pattern.slice(i + 1, j).replace(/\\/g, "\\\\");
if (body.startsWith("!")) body = "^" + body.slice(1);
else if (body.startsWith("^")) body = "\\" + body;
re += `[${body}]`;
i = j;
}
} else {
re += c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
}
}
const compiled = new RegExp(`^(?:${re})$`, "s");
regexCache.set(pattern, compiled);
return compiled;
}
function normalizePattern(p: string): string {
return p.endsWith("/") ? p + "*" : p;
}
export function matchesAny(path: string, patterns: readonly string[]): boolean {
return patterns.some((p) => fnmatchToRegExp(normalizePattern(p)).test(path));
}
/** Escape a literal path so fnmatch matches exactly that path (glob chars become [x] classes). */
export function escapeGlob(path: string): string {
return path.replace(/[*?[]/g, (c) => `[${c}]`);
}
export type SelectionRule = { include: string[]; exclude: string[] };
/**
* A file is selected if it matches an include pattern and no exclude pattern.
* Unlike the CLI, an empty include list selects nothing (selection is always explicit).
*/
export function isSelected(path: string, rule: SelectionRule): boolean {
return matchesAny(path, rule.include) && !matchesAny(path, rule.exclude);
}
/** Parse a user-entered pattern field: comma or newline separated. */
export function parsePatternList(input: string): string[] {
return input
.split(/[,\n]/)
.map((s) => s.trim())
.filter(Boolean);
}
// ---------------------------------------------------------------------------
// Quant grouping for GGUF repos
// ---------------------------------------------------------------------------
const QUANT_SUFFIX =
/[-_.]((?:UD-)?(?:I?Q\d(?:_[A-Z0-9]+)*|BF16|F16|F32|MXFP4(?:_MOE)?|TQ\d_\d))$/i;
const SPLIT_SUFFIX = /-\d{5}-of-\d{5}$/;
/**
* Group key for quick-selecting one quant: the top-level folder for folder-per-quant repos
* ("Q4_K_M/...-00001-of-00003.gguf"), otherwise the quant tag parsed from a .gguf file name
* ("Qwen3-8B-UD-Q4_K_XL.gguf" -> "UD-Q4_K_XL"). Returns null for files that aren't quants.
*/
export function quantGroup(path: string): string | null {
const slash = path.indexOf("/");
if (slash > 0) {
const dir = path.slice(0, slash);
return path.toLowerCase().endsWith(".gguf") ? dir : null;
}
if (!path.toLowerCase().endsWith(".gguf")) return null;
const base = path.slice(0, -".gguf".length).replace(SPLIT_SUFFIX, "");
const m = base.match(QUANT_SUFFIX);
const tag = m ? m[1] : base;
return base.toLowerCase().startsWith("mmproj") ? `mmproj-${tag}` : tag;
}
+14 -2
View File
@@ -10,19 +10,31 @@ export type WorkerStatus = {
online: boolean;
heartbeatAt: string | null;
hfVersion: string | null;
modelsDirFreeBytes: number | null;
modelsDirTotalBytes: number | null;
};
const OFFLINE: WorkerStatus = {
online: false,
heartbeatAt: null,
hfVersion: null,
modelsDirFreeBytes: null,
modelsDirTotalBytes: null,
};
export async function getWorkerStatus(): Promise<WorkerStatus> {
try {
const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
if (!row) return { online: false, heartbeatAt: null, hfVersion: null };
if (!row) return OFFLINE;
return {
online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS,
heartbeatAt: row.heartbeatAt.toISOString(),
hfVersion: row.hfVersion,
modelsDirFreeBytes: row.modelsDirFreeBytes,
modelsDirTotalBytes: row.modelsDirTotalBytes,
};
} catch {
// Table missing (worker never ran migrations yet) or DB unavailable.
return { online: false, heartbeatAt: null, hfVersion: null };
return OFFLINE;
}
}
+20 -5
View File
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
import { mkdir, statfs } from "node:fs/promises";
import { promisify } from "node:util";
import { inArray } from "drizzle-orm";
import { db } from "@/lib/db/client";
@@ -38,20 +39,34 @@ async function recoverInterruptedJobs() {
log.warn(`marked ${stale.length} job(s) as interrupted`);
}
async function diskSpace(dir: string) {
try {
const s = await statfs(dir);
return { modelsDirFreeBytes: s.bavail * s.bsize, modelsDirTotalBytes: s.blocks * s.bsize };
} catch {
return { modelsDirFreeBytes: null, modelsDirTotalBytes: null };
}
}
async function heartbeat(startedAt: Date, hfVersion: string | null) {
const now = new Date();
const values = {
pid: process.pid,
hfVersion,
startedAt,
heartbeatAt: now,
...(await diskSpace(coreEnv().MODELS_DIR)),
};
await db()
.insert(workerState)
.values({ id: "worker", pid: process.pid, hfVersion, startedAt, heartbeatAt: now })
.onConflictDoUpdate({
target: workerState.id,
set: { pid: process.pid, hfVersion, startedAt, heartbeatAt: now },
});
.values({ id: "worker", ...values })
.onConflictDoUpdate({ target: workerState.id, set: values });
}
async function main() {
const env = coreEnv();
log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}`);
await mkdir(env.MODELS_DIR, { recursive: true });
await runMigrations();
log.info("database migrated");