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

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

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

No files matched your search

+15 -1
View File
@@ -17,7 +17,15 @@ step 1 (Hugging Face downloader) is released as a minor version.
- **Model card**: the repo's README at the pinned commit, rendered (sanitized HTML, relative
links/images resolved to the Hub)
- **Jobs**: download history
- Custom tags are color-coded (color derived from the name, the same everywhere).
- Custom tags are color-coded: automatic color from the name, or one you pick in Settings.
- File labels in front of every file name: Model, MTP, Vision (mmproj), Draft, Adapter, imatrix,
Config, Tokenizer, Template, Docs, Image, Git (detected from the file name).
- Split files (`…-00001-of-00003.gguf`) are shown and selected as one entry with "N parts", the
combined size and a combined status, in the Files tab, Add model, Download more and progress lists.
- **Download more** in the Files tab: pick additional files (quick-select chips, checkboxes) and
download them; they're added to the model's selection. Files already on disk are skipped.
- **Settings** page (`/settings`), first section **Labels**: name and color per file label (with
reset), and rename, recolor or delete your tags. Stored in a new `settings` table.
- App icon (要).
- Sidebar with download status/actions, local copy details (commit, path, patterns) and a model
tree (base model → quantized/finetuned → this repo) listing other local models of the same base.
@@ -30,6 +38,12 @@ step 1 (Hugging Face downloader) is released as a minor version.
redirects to the canonical spelling). Old `/models/<id>` links redirect.
- The auth gate excludes only exact paths (`/login`, `/api/auth/…`), so org names like `loginx`
can't bypass it.
- Quant labels (library column, Quant filter, "Local copy") only count model weights, not MTP,
mmproj or imatrix files.
### Fixed
- Hydration error in progress bars on non-English browsers (locale-dependent `aria-valuetext`).
- Docs: full configuration reference and the NAS guide moved to the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki); the README keeps the quick install.
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE `settings` (
`key` text PRIMARY KEY NOT NULL,
`value` text NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `tags` ADD `color` text;
+946
View File
@@ -0,0 +1,946 @@
{
"version": "6",
"dialect": "sqlite",
"id": "84e7c88b-53c4-4eba-8f2f-7de08b494316",
"prevId": "0388c49a-d01a-4c5a-9694-0d844297213f",
"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": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"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
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_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": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"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
@@ -43,6 +43,13 @@
"when": 1791223474007,
"tag": "0005_refetch_metadata",
"breakpoints": true
},
{
"idx": 6,
"version": "6",
"when": 1791224932279,
"tag": "0006_settings_and_tag_color",
"breakpoints": true
}
]
}
+4 -2
View File
@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { groupJobFiles } from "@/lib/file-groups";
import { formatBytes, percent } from "@/lib/format";
const OPEN = ["queued", "downloading", "verifying"];
@@ -19,7 +20,7 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod
const [busy, setBusy] = useState(false);
const latest = snapshot?.jobs[0];
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const files = open ? (snapshot?.files ?? []) : [];
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
async function run(fn: () => Promise<void>) {
setBusy(true);
@@ -57,10 +58,11 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod
{files.length > 0 && (
<ul className="flex flex-col gap-1.5">
{files.map((f) => (
<li key={f.modelFileId} className="flex flex-col gap-1">
<li key={f.path} className="flex flex-col gap-1">
<div className="flex justify-between gap-2 text-xs">
<span className="truncate font-mono" title={f.path}>
{f.path}
{f.parts > 1 && <span className="text-muted-foreground"> · {f.parts} parts</span>}
</span>
<span className="shrink-0 text-muted-foreground tabular-nums">{formatBytes(f.expectedBytes)}</span>
</div>
@@ -0,0 +1,214 @@
"use client";
import { PlusIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
type Candidate = { path: string; size: number };
/**
* Files tab header: selection summary + on-disk progress, and a "Download more" panel to add
* files that aren't selected yet.
*/
export function FilesHeader({
modelId,
sha,
selectedCount,
totalBytes,
localCount,
localBytes,
candidates,
freeBytes,
busy,
}: {
modelId: string;
sha: string;
selectedCount: number;
totalBytes: number;
localCount: number;
localBytes: number;
candidates: Candidate[];
freeBytes: number | null;
/** A download is queued/running; adding files has to wait. */
busy: boolean;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [submitting, setSubmitting] = useState(false);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
for (const c of candidates) {
const g = quantGroup(c.path);
if (!g) continue;
const entry = m.get(g) ?? { paths: [], size: 0 };
entry.paths.push(c.path);
entry.size += c.size;
m.set(g, entry);
}
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [candidates]);
// Split files are one entry; its checkbox selects all parts.
const entries = useMemo(() => groupSplitFiles(candidates), [candidates]);
const pickedEntries = entries.filter((e) => e.parts.every((p) => picked.has(p.path))).length;
const pickedBytes = candidates.filter((c) => picked.has(c.path)).reduce((s, c) => s + c.size, 0);
const tooBig = freeBytes != null && pickedBytes > freeBytes;
function toggle(paths: string[], on: boolean) {
setPicked((prev) => {
const next = new Set(prev);
for (const p of paths) {
if (on) next.add(p);
else next.delete(p);
}
return next;
});
}
async function submit() {
setSubmitting(true);
try {
const res = await fetch(`/api/models/${modelId}/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ add: [...picked] }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not add files (${res.status})`);
return;
}
toast.success(`${body.added} file${body.added === 1 ? "" : "s"} added, download queued`);
setOpen(false);
setPicked(new Set());
router.refresh();
} finally {
setSubmitting(false);
}
}
return (
<div className="border-b">
<div className="flex flex-col gap-2 px-5 py-4">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-sm">
<span>
<span className="font-medium">
{selectedCount} selected file{selectedCount === 1 ? "" : "s"}
</span>
<span className="text-muted-foreground">
{" "}
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
</span>
</span>
<div className="flex items-center gap-3">
<span className="text-muted-foreground">
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
</span>
{candidates.length > 0 && (
<Button
size="sm"
variant={open ? "outline" : "default"}
onClick={() => setOpen((o) => !o)}
disabled={busy && !open}
title={busy ? "Wait until the current download has finished" : undefined}
>
{open ? (
"Close"
) : (
<>
<PlusIcon /> Download more
</>
)}
</Button>
)}
</div>
</div>
<Progress value={percent(localBytes, totalBytes)} />
</div>
{open && (
<div className="border-t bg-muted/30">
{groups.length > 0 && (
<div className="flex flex-col gap-1.5 px-5 pt-4">
<span className="text-xs text-muted-foreground">Quick select</span>
<div className="flex flex-wrap gap-1.5">
{groups.map(([name, g]) => {
const on = g.paths.every((p) => picked.has(p));
return (
<Button
key={name}
type="button"
size="xs"
variant={on ? "default" : "outline"}
onClick={() => toggle(g.paths, !on)}
title={g.paths.join("\n")}
>
{name}
<span className="opacity-70">{formatBytes(g.size)}</span>
</Button>
);
})}
</div>
</div>
)}
<ul className="mt-3 max-h-96 divide-y overflow-y-auto border-y bg-card">
{entries.map((e) => {
const paths = e.parts.map((p) => p.path);
const on = paths.every((p) => picked.has(p));
return (
<li key={e.path}>
<label className="grid cursor-pointer grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2 hover:bg-muted/50">
<Checkbox checked={on} onCheckedChange={(v) => toggle(paths, v === true)} />
<FileRoleBadge path={e.path} />
<span className="flex min-w-0 items-center gap-2" title={paths.join("\n")}>
<span className="truncate font-mono text-[13px]">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
</span>
<span className="text-right text-sm text-muted-foreground tabular-nums">{formatBytes(e.size)}</span>
</label>
</li>
);
})}
</ul>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-3 text-sm">
<span>
<span className="font-medium">
{pickedEntries} file{pickedEntries === 1 ? "" : "s"} · {formatBytes(pickedBytes)}
</span>
{freeBytes != null && (
<span className={tooBig ? "text-destructive" : "text-muted-foreground"}>
{" "}
({formatBytes(freeBytes)} free)
</span>
)}
</span>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" onClick={() => setPicked(new Set())} disabled={picked.size === 0}>
Clear
</Button>
<Button size="sm" onClick={submit} disabled={picked.size === 0 || submitting || busy}>
{submitting ? "Adding…" : pickedEntries === 0 ? "Download" : `Download ${pickedEntries} file${pickedEntries === 1 ? "" : "s"}`}
</Button>
</div>
</div>
</div>
)}
</div>
);
}
+77 -33
View File
@@ -11,10 +11,12 @@ import {
ShieldCheckIcon,
XCircleIcon,
} from "lucide-react";
import { Progress } from "@/components/ui/progress";
import { FileRoleBadge } from "@/components/labels";
import type { ModelFileState } from "@/lib/db/schema";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { formatBytes } from "@/lib/format";
import { type FileGroup, groupSplitFiles } from "@/lib/file-groups";
import { cn } from "@/lib/utils";
import { FilesHeader } from "./download-more";
type FileRow = { id: string; path: string; size: number; lfsSha256: string | null; state: ModelFileState };
@@ -47,35 +49,64 @@ function FileName({ path }: { path: string }) {
);
}
function Row({ file, href, muted, showState }: { file: FileRow; href: string; muted?: boolean; showState: boolean }) {
const state = STATE[file.state];
type Entry = FileGroup<FileRow>;
/** One status for a whole entry (all parts of a split file). */
function entryState(e: Entry): { state: ModelFileState; label: string } {
const states = e.parts.map((p) => p.state);
const done = states.filter((st) => st === "present" || st === "verified").length;
const worst = (["missing", "hash_mismatch", "size_mismatch"] as const).find((st) => states.includes(st));
if (worst) return { state: worst, label: STATE[worst].label };
if (done === states.length) {
const state = states.every((st) => st === "verified") ? "verified" : "present";
return { state, label: STATE[state].label };
}
if (done > 0) return { state: "pending", label: `${done} of ${states.length} parts` };
return { state: "pending", label: STATE.pending.label };
}
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
function Row({ entry, href, muted, showState }: { entry: Entry; href: string; muted?: boolean; showState: boolean }) {
const { state: stateKey, label } = entryState(entry);
const state = STATE[stateKey];
const split = entry.totalParts > 1;
return (
<li>
<a
href={href}
target="_blank"
rel="noreferrer"
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
className={cn(
// Fixed status column so sizes line up between selected and unselected rows.
"grid grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_minmax(0,1fr)_5rem_7.5rem]",
"grid grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_7.5rem]",
muted && "text-muted-foreground",
)}
>
<FileTypeIcon path={file.path} />
<FileTypeIcon path={entry.path} />
<FileRoleBadge path={entry.path} className={muted ? "opacity-70" : undefined} />
<span className="flex min-w-0 items-center gap-2">
<FileName path={file.path} />
{file.lfsSha256 && (
<FileName path={entry.path} />
{split && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{entry.parts.length === entry.totalParts
? `${entry.totalParts} parts`
: `${entry.parts.length} of ${entry.totalParts} parts`}
</span>
)}
{entry.parts[0].lfsSha256 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">LFS</span>
)}
</span>
<span className="hidden text-right text-sm tabular-nums sm:block">{formatBytes(file.size)}</span>
<span className="hidden text-right text-sm tabular-nums sm:block">{formatBytes(entry.size)}</span>
{showState ? (
<span className={cn("flex items-center justify-end gap-1.5 text-xs whitespace-nowrap", state.className)}>
{state.icon}
<span className="hidden md:inline">{state.label}</span>
<span className="hidden md:inline">{label}</span>
</span>
) : (
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(file.size)}</span>
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(entry.size)}</span>
)}
</a>
</li>
@@ -84,54 +115,67 @@ function Row({ file, href, muted, showState }: { file: FileRow; href: string; mu
/** "Files and versions"-style list: selected files with their local state, the rest collapsed. */
export function FilesTab({
modelId,
repoId,
sha,
selected,
others,
freeBytes,
busy,
}: {
modelId: string;
repoId: string;
sha: string;
selected: FileRow[];
others: FileRow[];
freeBytes: number | null;
busy: boolean;
}) {
const blob = (path: string) => `https://huggingface.co/${repoId}/blob/${sha}/${path}`;
const hub = `https://huggingface.co/${repoId}`;
// Split files link to their folder (all parts), single files to the file itself.
const href = (e: Entry) => {
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
};
const selectedEntries = groupSplitFiles(selected);
const otherEntries = groupSplitFiles(others);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const local = selected.filter((f) => f.state === "present" || f.state === "verified");
const localBytes = local.reduce((s, f) => s + f.size, 0);
const localEntries = selectedEntries.filter(isLocal);
const localBytes = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
return (
<div>
<div className="flex flex-col gap-2 px-5 py-4">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 text-sm">
<span>
<span className="font-medium">{selected.length} selected file{selected.length === 1 ? "" : "s"}</span>
<span className="text-muted-foreground"> · {formatBytes(totalBytes)} · commit {shortSha(sha)}</span>
</span>
<span className="text-muted-foreground">
{local.length} of {selected.length} on disk · {formatBytes(localBytes)}
</span>
</div>
<Progress value={percent(localBytes, totalBytes)} />
</div>
<FilesHeader
modelId={modelId}
sha={sha}
selectedCount={selectedEntries.length}
totalBytes={totalBytes}
localCount={localEntries.length}
localBytes={localBytes}
candidates={others.map((f) => ({ path: f.path, size: f.size }))}
freeBytes={freeBytes}
busy={busy}
/>
<ul className="divide-y border-t">
{selected.map((f) => (
<Row key={f.id} file={f} href={blob(f.path)} showState />
<ul className="divide-y">
{selectedEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} showState />
))}
</ul>
{others.length > 0 && (
{otherEntries.length > 0 && (
<details className="group border-t">
<summary className="flex cursor-pointer list-none items-center gap-2 px-5 py-3 text-sm hover:bg-muted/50">
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-open:rotate-90" />
<span className="font-medium">Not selected</span>
<span className="text-muted-foreground">
{others.length} file{others.length === 1 ? "" : "s"} · {formatBytes(others.reduce((s, f) => s + f.size, 0))}
{otherEntries.length} file{otherEntries.length === 1 ? "" : "s"} ·{" "}
{formatBytes(others.reduce((s, f) => s + f.size, 0))}
</span>
</summary>
<ul className="divide-y border-t">
{others.map((f) => (
<Row key={f.id} file={f} href={blob(f.path)} muted showState={false} />
{otherEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} muted showState={false} />
))}
</ul>
</details>
+18 -3
View File
@@ -24,8 +24,10 @@ import { formatBytes, shortSha } from "@/lib/format";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { getModelByRepo, relatedModels } from "@/lib/library";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
import { modelTagList } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
import { DownloadCard } from "./download-card";
import { FilesTab } from "./files-tab";
import { JobsTab } from "./jobs-tab";
@@ -89,16 +91,19 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const baseModels = model.baseModels ?? [];
const hubTags = model.hubTags ?? [];
const [tags, related, card] = await Promise.all([
const [tags, related, card, worker] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
]);
const selected = files.filter((f) => f.selected);
const others = files.filter((f) => !f.selected);
const selectedBytes = selected.reduce((s, f) => s + f.size, 0);
const quants = [...new Set(selected.map((f) => quantGroup(f.path)).filter(Boolean))] as string[];
const quants = [
...new Set(selected.filter((f) => fileRole(f.path) === "model").map((f) => quantGroup(f.path)).filter(Boolean)),
] as string[];
const formats = hubTags.filter((t) => FORMATS[t]).map((t) => FORMATS[t]);
const languages = hubTags.map(languageName).filter(Boolean) as string[];
@@ -206,7 +211,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
)}
</div>
)}
{tab === "files" && <FilesTab repoId={model.repoId} sha={model.pinnedSha} selected={selected} others={others} />}
{tab === "files" && (
<FilesTab
modelId={model.id}
repoId={model.repoId}
sha={model.pinnedSha}
selected={selected}
others={others}
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
busy={model.status === "downloading"}
/>
)}
{tab === "jobs" && (
<div className="px-2 pb-2">
<JobsTab modelId={model.id} />
+1 -1
View File
@@ -51,7 +51,7 @@ export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) {
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.id} name={t.name}>
<TagBadge key={t.id} name={t.name} color={t.color}>
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)} className="opacity-60 hover:opacity-100">
<XIcon className="size-3" />
</button>
+48 -31
View File
@@ -3,6 +3,7 @@
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@@ -10,6 +11,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, shortSha } from "@/lib/format";
import type { LookupResult } from "@/lib/hub/lookup";
import { escapeGlob, matchesAny, parsePatternList, quantGroup } from "@/lib/selection";
@@ -105,14 +107,19 @@ export function AddModelForm({
}, [files]);
const selected = files.filter((f) => f.selected);
// Split files are one row; its checkbox covers all parts.
const entries = useMemo(() => groupSplitFiles(files), [files]);
const selectedEntries = entries.filter((e) => e.parts.every((f) => f.selected)).length;
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
function toggle(path: string, on: boolean) {
function toggle(paths: string[], on: boolean) {
setChecked((prev) => {
const next = new Set(prev);
if (on) next.add(path);
else next.delete(path);
for (const path of paths) {
if (on) next.add(path);
else next.delete(path);
}
return next;
});
}
@@ -311,33 +318,43 @@ export function AddModelForm({
</TableRow>
</TableHeader>
<TableBody>
{files.map((f) => (
<TableRow key={f.path} data-state={f.selected ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={f.selected}
disabled={f.byPattern || f.excluded}
onCheckedChange={(v) => toggle(f.path, v === true)}
aria-label={`Select ${f.path}`}
title={
f.excluded
? "Excluded by a pattern"
: f.byPattern
? "Selected by an include pattern"
: undefined
}
/>
</TableCell>
<TableCell className="font-mono text-xs break-all whitespace-normal">
{f.path}
{f.excluded && <span className="ml-2 text-muted-foreground">(excluded)</span>}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{f.lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
))}
{entries.map((e) => {
const parts = e.parts;
const all = parts.every((f) => f.selected);
const some = !all && parts.some((f) => f.selected);
const byPattern = parts.every((f) => f.byPattern);
const excluded = parts.every((f) => f.excluded);
return (
<TableRow key={e.path} data-state={all ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={all}
indeterminate={some}
disabled={byPattern || excluded}
onCheckedChange={(v) => toggle(parts.map((f) => f.path), v === true)}
aria-label={`Select ${e.path}`}
title={excluded ? "Excluded by a pattern" : byPattern ? "Selected by an include pattern" : undefined}
/>
</TableCell>
<TableCell className="whitespace-normal">
<span className="flex items-center gap-2" title={e.totalParts > 1 ? parts.map((f) => f.path).join("\n") : undefined}>
<FileRoleBadge path={e.path} />
<span className="font-mono text-xs break-all">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
{excluded && <span className="text-xs text-muted-foreground">(excluded)</span>}
</span>
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(e.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{parts[0].lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
@@ -346,7 +363,7 @@ export function AddModelForm({
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
{selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)}
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{freeBytes != null && (
+9 -2
View File
@@ -2,14 +2,16 @@ import Link from "next/link";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
import { Button } from "@/components/ui/button";
import { LabelSettingsProvider } from "@/components/labels";
import { WorkerIndicator } from "@/components/worker-indicator";
import { getFileRoleStyles } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export default async function AppLayout({ children }: LayoutProps<"/">) {
const session = await auth();
if (!session?.user) redirect("/login");
const worker = await getWorkerStatus();
const [worker, fileRoles] = await Promise.all([getWorkerStatus(), getFileRoleStyles()]);
return (
<div className="flex min-h-screen flex-col overflow-x-clip">
@@ -23,6 +25,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<Link href="/" className="hover:text-foreground">
Library
</Link>
<Link href="/settings" className="hover:text-foreground">
Settings
</Link>
</nav>
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
@@ -42,7 +47,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
</div>
</div>
</header>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">{children}</main>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
<LabelSettingsProvider fileRoles={fileRoles}>{children}</LabelSettingsProvider>
</main>
</div>
);
}
+4 -3
View File
@@ -93,6 +93,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
};
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
@@ -123,7 +124,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
marker={facet === "tag" ? (v) => <TagDot name={v} /> : undefined}
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : undefined}
/>
))}
</div>
@@ -136,7 +137,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{FACETS.flatMap((facet) =>
filters[facet].map((v) => (
<Badge key={`${facet}:${v}`} variant="secondary" className="gap-1">
{facet === "tag" && <TagDot name={v} />}
{facet === "tag" && <TagDot name={v} color={tagColors.get(v)} />}
{FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v}
<button
type="button"
@@ -193,7 +194,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<TagBadge name={t.name} />
<TagBadge name={t.name} color={t.color} />
</button>
))}
</div>
@@ -0,0 +1,46 @@
"use client";
import { ChevronDownIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DOT_CLASS, LABEL_COLORS, type LabelColor } from "@/lib/colors";
import { cn } from "@/lib/utils";
/** Dropdown of the named label colors; optional "Automatic" entry (value null). */
export function ColorPicker({
value,
onChange,
allowAuto = false,
autoColor,
}: {
value: LabelColor | null;
onChange: (color: LabelColor | null) => void;
allowAuto?: boolean;
/** Color shown for the automatic option. */
autoColor?: LabelColor;
}) {
const shown = value ?? autoColor ?? "gray";
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="outline" size="sm" className="w-32 justify-start" />}>
<span className={cn("size-3 rounded-full", DOT_CLASS[shown])} />
<span className="flex-1 text-left capitalize">{value ?? "Automatic"}</span>
<ChevronDownIcon className="opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-72 min-w-40">
{allowAuto && (
<DropdownMenuItem onClick={() => onChange(null)}>
<span className={cn("size-3 rounded-full", DOT_CLASS[autoColor ?? "gray"])} />
Automatic
</DropdownMenuItem>
)}
{LABEL_COLORS.map((c) => (
<DropdownMenuItem key={c} onClick={() => onChange(c)}>
<span className={cn("size-3 rounded-full", DOT_CLASS[c])} />
<span className="capitalize">{c}</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,112 @@
"use client";
import { RotateCcwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { BADGE_CLASS } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRoleStyles } from "@/lib/file-roles";
import { cn } from "@/lib/utils";
import { ColorPicker } from "./color-picker";
/** Edit the label text and color shown in front of file names. */
export function FileLabelSettings({ initial }: { initial: FileRoleStyles }) {
const router = useRouter();
const [styles, setStyles] = useState(initial);
const [saving, setSaving] = useState(false);
const dirty = JSON.stringify(styles) !== JSON.stringify(initial);
function update(role: keyof FileRoleStyles, patch: Partial<FileRoleStyles[keyof FileRoleStyles]>) {
setStyles((prev) => ({ ...prev, [role]: { ...prev[role], ...patch } }));
}
async function save(next = styles) {
setSaving(true);
try {
const res = await fetch("/api/settings/labels", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileRoles: next }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not save (${res.status})`);
return;
}
setStyles(body.fileRoles);
toast.success("File labels saved");
router.refresh();
} finally {
setSaving(false);
}
}
const defaults = Object.fromEntries(
FILE_ROLE_ORDER.map((r) => [r, { label: FILE_ROLES[r].label, color: FILE_ROLES[r].color }]),
) as FileRoleStyles;
return (
<Card>
<CardHeader>
<CardTitle>File labels</CardTitle>
<CardDescription>
Shown in front of file names (Files tab, Add model). Kaname detects the type from the file name; here you
choose how each type is labeled and colored.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{FILE_ROLE_ORDER.map((role) => {
const s = styles[role];
const changed = s.label !== defaults[role].label || s.color !== defaults[role].color;
return (
<div key={role} className="grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[6rem_minmax(0,1fr)_10rem_8rem_2rem]">
<span
className={cn(
"inline-flex h-5 justify-self-start rounded-md border px-1.5 text-[11px] leading-[18px] font-medium",
BADGE_CLASS[s.color],
)}
>
{s.label || "…"}
</span>
<span className="min-w-0 text-xs text-muted-foreground">{FILE_ROLES[role].description}</span>
<Input
value={s.label}
maxLength={24}
onChange={(e) => update(role, { label: e.target.value })}
aria-label={`Label for ${FILE_ROLES[role].label}`}
className="h-8"
/>
<ColorPicker value={s.color} onChange={(c) => c && update(role, { color: c })} />
<Button
variant="ghost"
size="icon-sm"
disabled={!changed}
title="Reset to default"
aria-label="Reset to default"
onClick={() => update(role, defaults[role])}
>
<RotateCcwIcon />
</Button>
</div>
);
})}
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button variant="ghost" onClick={() => setStyles(initial)} disabled={!dirty || saving}>
Discard changes
</Button>
<Button variant="outline" onClick={() => save(defaults)} disabled={saving}>
Reset all to defaults
</Button>
<Button onClick={() => save()} disabled={!dirty || saving}>
{saving ? "Saving…" : "Save"}
</Button>
</div>
</CardContent>
</Card>
);
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { getFileRoleStyles } from "@/lib/settings";
import { listTags } from "@/lib/tags";
import { FileLabelSettings } from "./file-label-settings";
import { TagSettings } from "./tag-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Labels · Settings" };
export default async function LabelSettingsPage() {
const [fileRoles, tags] = await Promise.all([getFileRoleStyles(), listTags()]);
return (
<div className="flex flex-col gap-4">
<FileLabelSettings initial={fileRoles} />
<TagSettings tags={tags} />
</div>
);
}
@@ -0,0 +1,122 @@
"use client";
import { Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { TagBadge } from "@/components/tag-badge";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { autoTagColor, isLabelColor } from "@/lib/colors";
import type { Tag } from "@/lib/tags";
import { ColorPicker } from "./color-picker";
/** Rename, recolor or delete user tags. Changes save immediately. */
export function TagSettings({ tags }: { tags: (Tag & { count: number })[] }) {
return (
<Card>
<CardHeader>
<CardTitle>Tags</CardTitle>
<CardDescription>
Your own tags (added on a model page or when adding a model). Tags without a color get an automatic one.
</CardDescription>
</CardHeader>
<CardContent>
{tags.length === 0 ? (
<p className="text-sm text-muted-foreground">No tags yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tags.map((t) => (
<TagRow key={t.id} tag={t} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function TagRow({ tag }: { tag: Tag & { count: number } }) {
const router = useRouter();
const [name, setName] = useState(tag.name);
const [busy, setBusy] = useState(false);
async function patch(body: { name?: string; color?: string | null }) {
setBusy(true);
try {
const res = await fetch(`/api/tags/${tag.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
setName(tag.name);
return;
}
router.refresh();
} finally {
setBusy(false);
}
}
async function remove() {
const res = await fetch(`/api/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`Tag "${tag.name}" deleted`);
router.refresh();
}
const color = isLabelColor(tag.color) ? tag.color : null;
return (
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[8rem_minmax(0,1fr)_8rem_6rem_2rem]">
<TagBadge name={name || tag.name} color={tag.color} className="justify-self-start" />
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) => setName(e.target.value)}
onBlur={() => name.trim() && name !== tag.name && patch({ name })}
onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
aria-label={`Rename tag ${tag.name}`}
className="h-8"
/>
<ColorPicker value={color} onChange={(c) => patch({ color: c })} allowAuto autoColor={autoTagColor(tag.name)} />
<span className="text-xs text-muted-foreground tabular-nums">
{tag.count} model{tag.count === 1 ? "" : "s"}
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete tag ${tag.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete tag &ldquo;{tag.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>
It is removed from {tag.count} model{tag.count === 1 ? "" : "s"}. The models themselves are not touched.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [{ href: "/settings/labels", label: "Labels", icon: <TagsIcon className="size-4" /> }];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Settings</h1>
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
<SettingsNav sections={SECTIONS} />
<div className="min-w-0">{children}</div>
</div>
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function SettingsPage() {
redirect("/settings/labels");
}
+26
View File
@@ -0,0 +1,26 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
export function SettingsNav({ sections }: { sections: { href: string; label: string; icon: React.ReactNode }[] }) {
const pathname = usePathname();
return (
<nav className="flex gap-1 rounded-xl bg-card p-2 ring-1 ring-foreground/10 md:flex-col">
{sections.map((s) => (
<Link
key={s.href}
href={s.href}
className={cn(
"flex items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",
pathname === s.href ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:text-foreground",
)}
>
{s.icon}
{s.label}
</Link>
))}
</nav>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { addFilesToModel, ModelError } from "@/lib/models";
const Body = z.object({ add: z.array(z.string().min(1).max(1024)).min(1).max(10_000) });
/** Add files to a model's selection and queue their download. */
export const POST = withAuth<RouteContext<"/api/models/[id]/files">>(async (req, { params }) => {
const { id } = await params;
try {
const { add } = Body.parse(await req.json());
return NextResponse.json(await addFilesToModel(id, add), { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getFileRoleStyles, saveFileRoleStyles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Label text and color per file role (defaults merged with saved overrides). */
export const GET = withAuth(async () => NextResponse.json({ fileRoles: await getFileRoleStyles() }));
const Body = z.object({
fileRoles: z.record(z.string(), z.object({ label: z.string().optional(), color: z.string().optional() })),
});
/** Replace the saved overrides; send the full set (values equal to the default are dropped). */
export const PUT = withAuth(async (req) => {
try {
const { fileRoles } = Body.parse(await req.json());
return NextResponse.json({ fileRoles: await saveFileRoleStyles(fileRoles) });
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteTag, TagError, updateTag } from "@/lib/tags";
const Body = z.object({ name: z.string().optional(), color: z.string().nullable().optional() });
/** Rename a tag and/or change its color (null = automatic). */
export const PATCH = withAuth<RouteContext<"/api/tags/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await updateTag(id, Body.parse(await req.json())));
} catch (err) {
if (err instanceof TagError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Delete a tag everywhere. */
export const DELETE = withAuth<RouteContext<"/api/tags/[id]">>(async (_req, { params }) => {
const { id } = await params;
await deleteTag(id);
return new NextResponse(null, { status: 204 });
});
+17 -5
View File
@@ -1,9 +1,11 @@
import { FileRoleBadge } from "@/components/labels";
import { Progress } from "@/components/ui/progress";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { groupJobFiles } from "@/lib/file-groups";
import { formatBytes, percent } from "@/lib/format";
import type { JobFileSnapshot } from "@/lib/jobs";
/** Per-file progress of one job. */
/** Per-file progress of one job (split files as one entry). */
export function JobFilesTable({ files }: { files: JobFileSnapshot[] }) {
return (
<Table>
@@ -15,16 +17,26 @@ export function JobFilesTable({ files }: { files: JobFileSnapshot[] }) {
</TableRow>
</TableHeader>
<TableBody>
{files.map((f) => {
{groupJobFiles(files).map((f) => {
const pct = percent(f.doneBytes, f.expectedBytes);
return (
<TableRow key={f.modelFileId}>
<TableCell className="font-mono text-xs break-all whitespace-normal">{f.path}</TableCell>
<TableRow key={f.path}>
<TableCell className="whitespace-normal">
<span className="flex items-center gap-2">
<FileRoleBadge path={f.path} />
<span className="font-mono text-xs break-all">{f.path}</span>
{f.parts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{f.parts} parts
</span>
)}
</span>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Progress value={pct} className="flex-1" />
<span className="w-12 text-right text-xs text-muted-foreground tabular-nums">
{f.state === "failed" ? "missing" : `${pct.toFixed(0)}%`}
{f.failed ? "missing" : `${pct.toFixed(0)}%`}
</span>
</div>
</TableCell>
+40
View File
@@ -0,0 +1,40 @@
"use client";
import { createContext, useContext } from "react";
import { BADGE_CLASS } from "@/lib/colors";
import { FILE_ROLES, fileRole, type FileRoleStyles } from "@/lib/file-roles";
import { cn } from "@/lib/utils";
const defaults = Object.fromEntries(
Object.entries(FILE_ROLES).map(([role, r]) => [role, { label: r.label, color: r.color }]),
) as FileRoleStyles;
const LabelContext = createContext<FileRoleStyles>(defaults);
/** Provides the label settings (from the Settings page) to client components. */
export function LabelSettingsProvider({ fileRoles, children }: { fileRoles: FileRoleStyles; children: React.ReactNode }) {
return <LabelContext.Provider value={fileRoles}>{children}</LabelContext.Provider>;
}
export function useFileRoleStyles(): FileRoleStyles {
return useContext(LabelContext);
}
/** Label in front of a file name telling what the file is (Model, MTP, Vision, …). */
export function FileRoleBadge({ path, className }: { path: string; className?: string }) {
const styles = useFileRoleStyles();
const role = fileRole(path);
const style = styles[role];
return (
<span
title={FILE_ROLES[role].description}
className={cn(
"inline-flex h-5 min-w-16 shrink-0 items-center justify-center rounded-md border px-1.5 text-[11px] font-medium whitespace-nowrap",
BADGE_CLASS[style.color],
className,
)}
>
{style.label}
</span>
);
}
+10 -40
View File
@@ -1,55 +1,25 @@
import { autoTagColor, BADGE_CLASS, DOT_CLASS, isLabelColor, type LabelColor } from "@/lib/colors";
import { cn } from "@/lib/utils";
// Fixed palette (full class strings so Tailwind picks them up). A tag's color is derived from its
// name, so the same tag has the same color everywhere without storing anything.
const PALETTE = [
"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",
"border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
"border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
"border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300",
"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",
"border-cyan-500/30 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300",
"border-lime-500/30 bg-lime-500/10 text-lime-700 dark:text-lime-300",
"border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300",
"border-fuchsia-500/30 bg-fuchsia-500/10 text-fuchsia-700 dark:text-fuchsia-300",
"border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300",
];
const DOTS = [
"bg-sky-500",
"bg-emerald-500",
"bg-amber-500",
"bg-rose-500",
"bg-violet-500",
"bg-cyan-500",
"bg-lime-500",
"bg-orange-500",
"bg-fuchsia-500",
"bg-teal-500",
];
function colorIndex(name: string): number {
let h = 0;
for (const ch of name.trim().toLowerCase()) h = (h * 31 + ch.codePointAt(0)!) >>> 0;
return h % PALETTE.length;
}
export function tagColorClass(name: string): string {
return PALETTE[colorIndex(name)];
/** The tag's chosen color, or a stable automatic one derived from its name. */
export function tagColor(name: string, color?: string | null): LabelColor {
return isLabelColor(color) ? color : autoTagColor(name);
}
/** Small colored dot for a tag (e.g. in filter menus). */
export function TagDot({ name }: { name: string }) {
return <span className={cn("inline-block size-2 shrink-0 rounded-full", DOTS[colorIndex(name)])} />;
export function TagDot({ name, color }: { name: string; color?: string | null }) {
return <span className={cn("inline-block size-2 shrink-0 rounded-full", DOT_CLASS[tagColor(name, color)])} />;
}
/** A user tag, colored by its name. */
/** A user tag, in its color. */
export function TagBadge({
name,
color,
className,
children,
}: {
name: string;
color?: string | null;
className?: string;
children?: React.ReactNode;
}) {
@@ -57,7 +27,7 @@ export function TagBadge({
<span
className={cn(
"inline-flex h-5 items-center gap-1 rounded-full border px-2 text-xs font-medium whitespace-nowrap",
tagColorClass(name),
BADGE_CLASS[tagColor(name, color)],
className,
)}
>
+79
View File
@@ -0,0 +1,79 @@
// Named label colors. Class strings are spelled out in full so Tailwind generates them.
export const LABEL_COLORS = [
"gray",
"red",
"orange",
"amber",
"yellow",
"lime",
"green",
"emerald",
"teal",
"cyan",
"sky",
"blue",
"indigo",
"violet",
"purple",
"fuchsia",
"pink",
"rose",
] as const;
export type LabelColor = (typeof LABEL_COLORS)[number];
export function isLabelColor(v: unknown): v is LabelColor {
return typeof v === "string" && (LABEL_COLORS as readonly string[]).includes(v);
}
/** Pill: border + tinted background + readable text in both themes. */
export const BADGE_CLASS: Record<LabelColor, string> = {
gray: "border-zinc-500/30 bg-zinc-500/10 text-zinc-700 dark:text-zinc-300",
red: "border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-300",
orange: "border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300",
amber: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
yellow: "border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300",
lime: "border-lime-500/30 bg-lime-500/10 text-lime-700 dark:text-lime-300",
green: "border-green-500/30 bg-green-500/10 text-green-700 dark:text-green-300",
emerald: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
teal: "border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300",
cyan: "border-cyan-500/30 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300",
sky: "border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",
blue: "border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300",
indigo: "border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300",
violet: "border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",
purple: "border-purple-500/30 bg-purple-500/10 text-purple-700 dark:text-purple-300",
fuchsia: "border-fuchsia-500/30 bg-fuchsia-500/10 text-fuchsia-700 dark:text-fuchsia-300",
pink: "border-pink-500/30 bg-pink-500/10 text-pink-700 dark:text-pink-300",
rose: "border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300",
};
export const DOT_CLASS: Record<LabelColor, string> = {
gray: "bg-zinc-500",
red: "bg-red-500",
orange: "bg-orange-500",
amber: "bg-amber-500",
yellow: "bg-yellow-500",
lime: "bg-lime-500",
green: "bg-green-500",
emerald: "bg-emerald-500",
teal: "bg-teal-500",
cyan: "bg-cyan-500",
sky: "bg-sky-500",
blue: "bg-blue-500",
indigo: "bg-indigo-500",
violet: "bg-violet-500",
purple: "bg-purple-500",
fuchsia: "bg-fuchsia-500",
pink: "bg-pink-500",
rose: "bg-rose-500",
};
/** Colors used for tags that have no color set: picked from the name so they stay stable. */
const AUTO_TAG_COLORS: LabelColor[] = ["sky", "emerald", "amber", "rose", "violet", "cyan", "lime", "orange", "fuchsia", "teal"];
export function autoTagColor(name: string): LabelColor {
let h = 0;
for (const ch of name.trim().toLowerCase()) h = (h * 31 + ch.codePointAt(0)!) >>> 0;
return AUTO_TAG_COLORS[h % AUTO_TAG_COLORS.length];
}
+13 -1
View File
@@ -107,6 +107,8 @@ export const tags = sqliteTable(
name: text("name").notNull(),
/** Lowercased, trimmed name; unique. */
slug: text("slug").notNull(),
/** One of LABEL_COLORS; null = automatic color derived from the name. */
color: text("color"),
createdAt: createdAt(),
},
(t) => [uniqueIndex("tags_slug_uq").on(t.slug)],
@@ -183,7 +185,7 @@ export const modelFiles = sqliteTable(
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
export const JOB_PURPOSES = ["initial", "repair", "update"] as const;
export const JOB_PURPOSES = ["initial", "add", "repair", "update"] as const;
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
@@ -278,6 +280,16 @@ export const jobLogs = sqliteTable(
(t) => [index("job_logs_job_idx").on(t.jobId, t.id)],
);
// ---------------------------------------------------------------------------
// App settings (key/value, edited on the Settings page)
// ---------------------------------------------------------------------------
export const settings = sqliteTable("settings", {
key: text("key").primaryKey(),
value: text("value", { mode: "json" }).notNull(),
updatedAt: updatedAt(),
});
// ---------------------------------------------------------------------------
// Worker liveness
// ---------------------------------------------------------------------------
+61
View File
@@ -0,0 +1,61 @@
// Group split files ("model-00001-of-00003.gguf", …) into one entry for display and selection.
const SPLIT = /^(.*)-(\d{5})-of-(\d{5})(\.[^./]+)$/;
export type SplitInfo = { base: string; part: number; total: number };
/** "BF16/X-BF16-00001-of-00002.gguf" → { base: "BF16/X-BF16.gguf", part: 1, total: 2 }. */
export function splitInfo(path: string): SplitInfo | null {
const m = path.match(SPLIT);
if (!m) return null;
return { base: `${m[1]}${m[4]}`, part: Number(m[2]), total: Number(m[3]) };
}
export type FileGroup<T> = {
/** Display path: the file itself, or the shared name of a split file without the part suffix. */
path: string;
/** Files in this entry, in part order. */
parts: T[];
size: number;
/** Number of parts the split file has in total (1 for normal files). */
totalParts: number;
};
/** Merge split parts into one entry; other files stay as they are. Keeps first-seen order. */
export function groupSplitFiles<T extends { path: string; size: number }>(files: T[]): FileGroup<T>[] {
const groups: FileGroup<T>[] = [];
const byBase = new Map<string, FileGroup<T>>();
for (const f of files) {
const info = splitInfo(f.path);
if (!info) {
groups.push({ path: f.path, parts: [f], size: f.size, totalParts: 1 });
continue;
}
const key = `${info.base}#${info.total}`;
let g = byBase.get(key);
if (!g) {
g = { path: info.base, parts: [], size: 0, totalParts: info.total };
byBase.set(key, g);
groups.push(g);
}
g.parts.push(f);
g.size += f.size;
}
for (const g of groups) {
if (g.parts.length > 1) g.parts.sort((a, b) => (splitInfo(a.path)?.part ?? 0) - (splitInfo(b.path)?.part ?? 0));
}
return groups;
}
export type JobFileEntry = { path: string; expectedBytes: number; doneBytes: number; failed: boolean; parts: number };
/** Job progress per entry: split parts summed into one line. */
export function groupJobFiles(files: { path: string; expectedBytes: number; doneBytes: number; state: string }[]): JobFileEntry[] {
return groupSplitFiles(files.map((f) => ({ ...f, size: f.expectedBytes }))).map((g) => ({
path: g.path,
expectedBytes: g.size,
doneBytes: g.parts.reduce((s, p) => s + p.doneBytes, 0),
failed: g.parts.some((p) => p.state === "failed"),
parts: g.totalParts,
}));
}
+66
View File
@@ -0,0 +1,66 @@
// What a file in a model repo is for, guessed from its path. Shared by UI and server.
import type { LabelColor } from "./colors";
export type FileRole =
| "model"
| "mtp"
| "vision"
| "draft"
| "adapter"
| "imatrix"
| "config"
| "tokenizer"
| "template"
| "docs"
| "image"
| "git"
| "other";
/** Defaults; label and color can be changed in Settings. */
export const FILE_ROLES: Record<FileRole, { label: string; color: LabelColor; description: string }> = {
model: { label: "Model", color: "indigo", description: "Model weights" },
mtp: { label: "MTP", color: "amber", description: "Multi-token prediction head (speculative decoding draft)" },
vision: { label: "Vision", color: "fuchsia", description: "Multimodal projector (mmproj) for image input" },
draft: { label: "Draft", color: "orange", description: "Draft model for speculative decoding" },
adapter: { label: "Adapter", color: "violet", description: "LoRA / adapter weights" },
imatrix: { label: "imatrix", color: "gray", description: "Importance matrix used to make the quants; not needed to run the model" },
config: { label: "Config", color: "sky", description: "Model or generation config" },
tokenizer: { label: "Tokenizer", color: "teal", description: "Tokenizer / vocabulary" },
template: { label: "Template", color: "cyan", description: "Chat template" },
docs: { label: "Docs", color: "gray", description: "Documentation or license" },
image: { label: "Image", color: "pink", description: "Image (e.g. for the model card)" },
git: { label: "Git", color: "gray", description: "Git metadata" },
other: { label: "Other", color: "gray", description: "Other file" },
};
export const FILE_ROLE_ORDER = Object.keys(FILE_ROLES) as FileRole[];
export type FileRoleStyle = { label: string; color: LabelColor };
export type FileRoleStyles = Record<FileRole, FileRoleStyle>;
const WEIGHTS = /\.(gguf|safetensors|bin|pt|pth|ckpt|onnx|ggml|mlmodel|npz|h5)$/i;
export function fileRole(path: string): FileRole {
const lower = path.toLowerCase();
const name = lower.slice(lower.lastIndexOf("/") + 1);
const dirs = lower.split("/").slice(0, -1);
if (name.startsWith(".git")) return "git";
if (name.includes("imatrix")) return "imatrix";
if (name.includes("mmproj") || dirs.includes("mmproj")) return "vision";
if (name.startsWith("mtp-") || name.startsWith("mtp_") || dirs.includes("mtp")) return "mtp";
if (WEIGHTS.test(name)) {
if (name.includes("adapter")) return "adapter";
if (/(^|[-_.])draft([-_.]|$)/.test(name)) return "draft";
return "model";
}
if (/^tokenizer|^vocab|^merges\.txt$|^special_tokens_map\.json$|^added_tokens\.json$|\.tiktoken$|^tokenizer\.model$/.test(name)) {
return "tokenizer";
}
if (name.endsWith(".jinja") || name.includes("chat_template") || name === "template") return "template";
if (name.endsWith(".json") || name === "params" || name.endsWith(".yaml") || name.endsWith(".yml")) return "config";
if (/\.(md|txt|rst)$/.test(name) || name.startsWith("license") || name.startsWith("notice")) return "docs";
if (/\.(png|jpe?g|gif|webp|svg)$/.test(name)) return "image";
return "other";
}
+5 -3
View File
@@ -3,6 +3,7 @@ import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { modelFamilies } from "@/lib/hub/metadata";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
import type { Tag } from "@/lib/tags";
@@ -38,15 +39,16 @@ export async function listLibrary() {
.select({ modelId: modelFiles.modelId, path: modelFiles.path })
.from(modelFiles)
.where(eq(modelFiles.selected, true));
const quants = groupBy(selected, (f) => f.modelId, (f) => quantGroup(f.path));
// Only model weights count as a quant (not MTP heads, mmproj or imatrix files).
const quants = groupBy(selected, (f) => f.modelId, (f) => (fileRole(f.path) === "model" ? quantGroup(f.path) : null));
const tagRows = await d
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name })
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name, color: tags.color })
.from(modelTags)
.innerJoin(tags, eq(tags.id, modelTags.tagId))
.orderBy(asc(tags.slug));
const tagsByModel = new Map<string, Tag[]>();
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name }]);
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
return rows.map((r) => ({
...r,
+41 -3
View File
@@ -1,16 +1,17 @@
import "server-only";
import { and, eq, sql } from "drizzle-orm";
import { and, eq, inArray, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { isSelected, type SelectionRule } from "@/lib/selection";
import { queueDownload } from "@/lib/jobs";
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
import { deleteUnusedTags } from "@/lib/tags";
export class ModelError extends Error {
constructor(
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable",
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy",
message: string,
public status: number,
) {
@@ -107,3 +108,40 @@ function chunk<T>(items: T[], size: number): T[][] {
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
return out;
}
/**
* Add files to a model's selection and queue a download. The paths are added to the selection
* rule as exact includes; exclude patterns that would block one of them are dropped, then the
* rule is re-applied to the whole file list so `selected` always matches the stored rule.
*/
export async function addFilesToModel(modelId: string, paths: string[]): Promise<{ jobId: string; added: number }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const open = await d.query.jobs.findFirst({
columns: { id: true },
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", "downloading", "verifying"])),
});
if (open) throw new ModelError("busy", "A download for this model is still queued or running. Add files when it has finished.", 409);
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
const known = new Map(files.map((f) => [f.path, f]));
const wanted = [...new Set(paths)].filter((p) => known.has(p) && !known.get(p)!.selected);
if (wanted.length === 0) throw new ModelError("empty_selection", "No new files selected.", 400);
const rule: SelectionRule = {
include: [...model.includePatterns, ...wanted.map(escapeGlob)],
exclude: model.excludePatterns.filter((p) => !wanted.some((path) => matchesAny(path, [p]))),
};
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
await d.batch([
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude }).where(eq(models.id, modelId)),
...changed.map((f) =>
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
),
]);
const { jobId } = await queueDownload(modelId, "add");
return { jobId, added: changed.filter((f) => !f.selected).length };
}
+59
View File
@@ -1,5 +1,7 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { groupSplitFiles, splitInfo } from "./file-groups";
import { fileRole } from "./file-roles";
import { modelFamilies, parseRepoMetadata } from "./hub/metadata";
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search";
@@ -89,3 +91,60 @@ describe("filters and facet counts", () => {
assert.deepEqual(facetCounts(models, "family", "", f), [["google", 1], ["Qwen", 1]]);
});
});
describe("fileRole", () => {
it("classifies typical GGUF repo files", () => {
const cases: [string, string][] = [
["Qwen3.8-27B-UD-Q4_K_M.gguf", "model"],
["Q4_K_M/Qwen3-235B-A22B-Q4_K_M-00001-of-00003.gguf", "model"],
["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "mtp"],
["mmproj-BF16.gguf", "vision"],
["mmproj-model-f16.gguf", "vision"],
["imatrix_unsloth.gguf", "imatrix"],
["imatrix_unsloth.dat", "imatrix"],
["Qwen_Qwen3-8B.imatrix", "imatrix"],
["config.json", "config"],
["generation_config.json", "config"],
["params", "config"],
["tokenizer.json", "tokenizer"],
["tokenizer_config.json", "tokenizer"],
["merges.txt", "tokenizer"],
["chat_template.jinja", "template"],
["template", "template"],
["README.md", "docs"],
["LICENSE", "docs"],
[".gitattributes", "git"],
["model-00001-of-00004.safetensors", "model"],
["adapter_model.safetensors", "adapter"],
["images/banner.png", "image"],
];
for (const [path, role] of cases) assert.equal(fileRole(path), role, path);
});
});
describe("groupSplitFiles", () => {
it("merges split parts into one entry and leaves other files alone", () => {
const files = [
{ path: ".gitattributes", size: 1 },
{ path: "BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf", size: 20 },
{ path: "BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", size: 50 },
{ path: "Qwen3.8-27B-Q4_0.gguf", size: 16 },
];
const groups = groupSplitFiles(files);
assert.deepEqual(
groups.map((g) => [g.path, g.size, g.totalParts, g.parts.map((p) => p.path.slice(-18))]),
[
[".gitattributes", 1, 1, [".gitattributes"]],
["BF16/Qwen3.8-27B-BF16.gguf", 70, 2, ["00001-of-00002.gguf", "00002-of-00002.gguf"].map((s) => s.slice(-18))],
["Qwen3.8-27B-Q4_0.gguf", 16, 1, ["Qwen3.8-27B-Q4_0.gguf".slice(-18)]],
],
);
});
it("parses part numbers", () => {
assert.deepEqual(splitInfo("Q4_K_M/X-Q4_K_M-00003-of-00010.gguf"), { base: "Q4_K_M/X-Q4_K_M.gguf", part: 3, total: 10 });
assert.equal(splitInfo("model-00001-of-00004.safetensors")?.base, "model.safetensors");
assert.equal(splitInfo("Qwen3-8B-Q4_K_M.gguf"), null);
});
});
+69
View File
@@ -0,0 +1,69 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { isLabelColor } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
const FILE_ROLES_KEY = "labels.fileRoles";
export const FILE_ROLE_LABEL_MAX = 24;
type StoredRoles = Partial<Record<FileRole, { label?: string; color?: string }>>;
async function read<T>(key: string): Promise<T | null> {
try {
const row = await db().query.settings.findFirst({ where: eq(settings.key, key) });
return (row?.value as T) ?? null;
} catch {
return null; // table missing before the first migration
}
}
async function write(key: string, value: unknown) {
await db()
.insert(settings)
.values({ key, value })
.onConflictDoUpdate({ target: settings.key, set: { value, updatedAt: new Date() } });
}
/** Label text and color per file role: defaults merged with what was saved in Settings. */
export async function getFileRoleStyles(): Promise<FileRoleStyles> {
const stored = (await read<StoredRoles>(FILE_ROLES_KEY)) ?? {};
const out = {} as FileRoleStyles;
for (const role of FILE_ROLE_ORDER) {
const s = stored[role] ?? {};
out[role] = {
label: typeof s.label === "string" && s.label.trim() ? s.label.trim() : FILE_ROLES[role].label,
color: isLabelColor(s.color) ? s.color : FILE_ROLES[role].color,
};
}
return out;
}
export class SettingsError extends Error {
status = 400;
code = "invalid";
}
/** Save label/color overrides. Values equal to the default are not stored. */
export async function saveFileRoleStyles(input: Record<string, { label?: unknown; color?: unknown }>): Promise<FileRoleStyles> {
const stored: StoredRoles = {};
for (const [role, v] of Object.entries(input)) {
if (!(role in FILE_ROLES)) throw new SettingsError(`Unknown file label "${role}".`);
const def = FILE_ROLES[role as FileRole];
const entry: { label?: string; color?: string } = {};
if (v.label !== undefined) {
if (typeof v.label !== "string" || !v.label.trim() || v.label.trim().length > FILE_ROLE_LABEL_MAX) {
throw new SettingsError(`Label for "${role}" must be 1–${FILE_ROLE_LABEL_MAX} characters.`);
}
if (v.label.trim() !== def.label) entry.label = v.label.trim();
}
if (v.color !== undefined) {
if (!isLabelColor(v.color)) throw new SettingsError(`Unknown color "${String(v.color)}".`);
if (v.color !== def.color) entry.color = v.color;
}
if (entry.label || entry.color) stored[role as FileRole] = entry;
}
await write(FILE_ROLES_KEY, stored);
return getFileRoleStyles();
}
+32 -4
View File
@@ -2,6 +2,7 @@ import "server-only";
import { and, asc, eq, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { isLabelColor } from "@/lib/colors";
import { modelTags, models, tags } from "@/lib/db/schema";
export const TAG_MAX_LENGTH = 40;
@@ -16,7 +17,7 @@ export class TagError extends Error {
}
}
export type Tag = { id: string; name: string };
export type Tag = { id: string; name: string; color: string | null };
/** Trim and collapse whitespace; the slug (lowercase) decides uniqueness. */
export function normalizeTagName(raw: string): { name: string; slug: string } {
@@ -29,7 +30,7 @@ export function normalizeTagName(raw: string): { name: string; slug: string } {
/** All tags with how many models use them (for autocomplete). */
export async function listTags(): Promise<(Tag & { count: number })[]> {
return db()
.select({ id: tags.id, name: tags.name, count: sql<number>`count(${modelTags.modelId})` })
.select({ id: tags.id, name: tags.name, color: tags.color, count: sql<number>`count(${modelTags.modelId})` })
.from(tags)
.leftJoin(modelTags, eq(modelTags.tagId, tags.id))
.groupBy(tags.id)
@@ -38,7 +39,7 @@ export async function listTags(): Promise<(Tag & { count: number })[]> {
export async function modelTagList(modelId: string): Promise<Tag[]> {
return db()
.select({ id: tags.id, name: tags.name })
.select({ id: tags.id, name: tags.name, color: tags.color })
.from(modelTags)
.innerJoin(tags, eq(tags.id, modelTags.tagId))
.where(eq(modelTags.modelId, modelId))
@@ -53,7 +54,7 @@ export async function addTag(modelId: string, rawName: string): Promise<Tag> {
if (!model) throw new TagError("not_found", "Model not found.", 404);
await d.insert(tags).values({ id: ulid(), name, slug }).onConflictDoNothing({ target: tags.slug });
const tag = await d.query.tags.findFirst({ columns: { id: true, name: true }, where: eq(tags.slug, slug) });
const tag = await d.query.tags.findFirst({ columns: { id: true, name: true, color: true }, where: eq(tags.slug, slug) });
if (!tag) throw new Error("tag vanished after insert");
await d.insert(modelTags).values({ modelId, tagId: tag.id }).onConflictDoNothing();
return tag;
@@ -69,3 +70,30 @@ export async function removeTag(modelId: string, tagId: string): Promise<void> {
export async function deleteUnusedTags(): Promise<void> {
await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`);
}
/** Rename a tag and/or set its color (null = automatic). */
export async function updateTag(id: string, input: { name?: string; color?: string | null }): Promise<Tag> {
const d = db();
const tag = await d.query.tags.findFirst({ where: eq(tags.id, id) });
if (!tag) throw new TagError("not_found", "Tag not found.", 404);
const set: { name?: string; slug?: string; color?: string | null } = {};
if (input.name !== undefined) {
const { name, slug } = normalizeTagName(input.name);
const clash = await d.query.tags.findFirst({ columns: { id: true }, where: eq(tags.slug, slug) });
if (clash && clash.id !== id) throw new TagError("invalid", `A tag named "${name}" already exists.`, 409);
Object.assign(set, { name, slug });
}
if (input.color !== undefined) {
if (input.color !== null && !isLabelColor(input.color)) throw new TagError("invalid", "Unknown color.", 400);
set.color = input.color;
}
if (Object.keys(set).length > 0) await d.update(tags).set(set).where(eq(tags.id, id));
const updated = await d.query.tags.findFirst({ columns: { id: true, name: true, color: true }, where: eq(tags.id, id) });
return updated!;
}
/** Delete a tag and remove it from all models. */
export async function deleteTag(id: string): Promise<void> {
const d = db();
await d.batch([d.delete(modelTags).where(eq(modelTags.tagId, id)), d.delete(tags).where(eq(tags.id, id))]);
}