diff --git a/CHANGELOG.md b/CHANGELOG.md index 742ee75..dbfab8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/` 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. diff --git a/README.md b/README.md index 6475cb7..8720b7d 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/drizzle/0001_worker_disk_space.sql b/drizzle/0001_worker_disk_space.sql new file mode 100644 index 0000000..b4a92b4 --- /dev/null +++ b/drizzle/0001_worker_disk_space.sql @@ -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; \ No newline at end of file diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json new file mode 100644 index 0000000..a80a66e --- /dev/null +++ b/drizzle/meta/0001_snapshot.json @@ -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": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 33715ad..d25addd 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1791206191116, "tag": "0000_init", "breakpoints": true + }, + { + "idx": 1, + "version": "6", + "when": 1791207195702, + "tag": "0001_worker_disk_space", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 6a987fb..10306d0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 9779d78..25593b0 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index f00b8c0..1867f0f 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -22,6 +22,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) { Library + + Add model +
diff --git a/src/app/(app)/models/[id]/page.tsx b/src/app/(app)/models/[id]/page.tsx new file mode 100644 index 0000000..c1bdb89 --- /dev/null +++ b/src/app/(app)/models/[id]/page.tsx @@ -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 ( +
+
+

{model.repoId}

+ +
{model.status === "pending" && }
+
+ + + + Details + Downloading starts in the next milestone. + + +
+
Hub
+
+ + huggingface.co/{model.repoId} + +
+
Tracked revision
+
{model.trackedRevision}
+
Pinned SHA
+
{model.pinnedSha}
+
Local path
+
$MODELS_DIR/{model.localPath}
+
Include
+
{model.includePatterns.join(", ") || "–"}
+
Exclude
+
{model.excludePatterns.join(", ") || "–"}
+
Added
+
{formatDate(model.createdAt)}
+
+
+
+ + + + + Selected files · {selected.length} · {formatBytes(totalBytes)} + + + {files.length - selected.length} other files in the repo are not selected. + + + + + + File + Size + State + + + + {selected.map((f) => ( + + {f.path} + {formatBytes(f.size)} + {f.state} + + ))} + +
+
+
+ ); +} diff --git a/src/app/(app)/models/[id]/remove-model-button.tsx b/src/app/(app)/models/[id]/remove-model-button.tsx new file mode 100644 index 0000000..204b1fe --- /dev/null +++ b/src/app/(app)/models/[id]/remove-model-button.tsx @@ -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 ( + + }>Remove + + + Remove from library? + + Nothing has been downloaded yet, so this only removes the entry. + + + + Cancel + + Remove + + + + + ); +} diff --git a/src/app/(app)/models/new/add-model-form.tsx b/src/app/(app)/models/new/add-model-form.tsx new file mode 100644 index 0000000..1df538b --- /dev/null +++ b/src/app/(app)/models/new/add-model-form.tsx @@ -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(url: string, body: unknown): Promise { + const res = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + const json = (await res.json().catch(() => ({}))) as T & ApiErrorBody; + if (!res.ok) throw new Error(json.error?.message ?? `Request failed (${res.status})`); + return json; +} + +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(null); + const [result, setResult] = useState(null); + + const [checked, setChecked] = useState>(new Set()); + const [includeText, setIncludeText] = useState(""); + const [excludeText, setExcludeText] = useState(""); + const [submitting, setSubmitting] = useState(false); + + async function lookup(e: React.FormEvent) { + e.preventDefault(); + setLoading(true); + setError(null); + try { + const r = await postJson("/api/hub/lookup", { repo, revision }); + setResult(r); + setRevision(r.revision); + 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(); + 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 ( +
+ + + Hugging Face repository + Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL. + + +
+
+ + setRepo(e.target.value)} + placeholder="unsloth/Qwen3-8B-GGUF" + autoComplete="off" + spellCheck={false} + required + /> +
+
+ + setRevision(e.target.value)} + placeholder="main" + spellCheck={false} + /> +
+ +
+ {error && ( +

+ {error} +

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

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

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

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

+
+
+
+ + + + + + + File + Size + Storage + + + + {files.map((f) => ( + + + 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 + } + /> + + + {f.path} + {f.excluded && (excluded)} + + {formatBytes(f.size)} + + {f.lfsSha256 ? "LFS" : "git"} + + + ))} + +
+
+ +
+
+
+ + {selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)} + {" "} + selected + {freeBytes != null && ( + + ({formatBytes(freeBytes)} free on the models volume) + + )} +
+
+ + +
+
+
+ + )} +
+ ); +} diff --git a/src/app/(app)/models/new/page.tsx b/src/app/(app)/models/new/page.tsx new file mode 100644 index 0000000..6d57a46 --- /dev/null +++ b/src/app/(app)/models/new/page.tsx @@ -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 ( +
+

Add model

+ +
+ ); +} diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 60fb728..198781d 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -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 (
-

Library

- - - No models yet - Adding models from Hugging Face comes in the next milestone. - - +
+

Library

+ + Add model + +
+ + {rows.length === 0 ? ( + + + No models yet + Add a Hugging Face repo to get started. + + + ) : ( + + + + + Repository + Selection + Size + Pinned + Downloaded + Status + + + + {rows.map((r) => ( + + + + {r.repoId} + + + + {r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} files`} + + {formatBytes(r.totalBytes)} + + + {r.trackedRevision}@{shortSha(r.pinnedSha)} + + + + {formatDate(r.downloadedAt)} + + + + + + ))} + +
+
+ )}
); } diff --git a/src/app/api/hub/lookup/route.ts b/src/app/api/hub/lookup/route.ts new file mode 100644 index 0000000..f7e0533 --- /dev/null +++ b/src/app/api/hub/lookup/route.ts @@ -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); + } +}); diff --git a/src/app/api/models/[id]/route.ts b/src/app/api/models/[id]/route.ts new file mode 100644 index 0000000..aadfe53 --- /dev/null +++ b/src/app/api/models/[id]/route.ts @@ -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>(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; + } +}); diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts new file mode 100644 index 0000000..0d9ce70 --- /dev/null +++ b/src/app/api/models/route.ts @@ -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); + } +}); diff --git a/src/components/model-status-badge.tsx b/src/components/model-status-badge.tsx new file mode 100644 index 0000000..2bf82e4 --- /dev/null +++ b/src/components/model-status-badge.tsx @@ -0,0 +1,16 @@ +import { Badge } from "@/components/ui/badge"; +import type { ModelStatus } from "@/lib/db/schema"; + +const LABELS: Record = { + 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 {label}; +} diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx new file mode 100644 index 0000000..4d88edf --- /dev/null +++ b/src/components/ui/alert-dialog.tsx @@ -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 +} + +function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) { + return ( + + ) +} + +function AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) { + return ( + + ) +} + +function AlertDialogOverlay({ + className, + ...props +}: AlertDialogPrimitive.Backdrop.Props) { + return ( + + ) +} + +function AlertDialogContent({ + className, + size = "default", + ...props +}: AlertDialogPrimitive.Popup.Props & { + size?: "default" | "sm" +}) { + return ( + + + + + ) +} + +function AlertDialogHeader({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDialogFooter({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDialogMedia({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogAction({ + className, + ...props +}: React.ComponentProps) { + return ( +