From df18415e02b149a24fbb4206f7bf1b79a98512da Mon Sep 17 00:00:00 2001 From: Pascal Linxweiler Date: Mon, 5 Oct 2026 20:42:03 +0200 Subject: [PATCH] Download more, file labels, split-file grouping, settings for labels and tags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- CHANGELOG.md | 16 +- drizzle/0006_settings_and_tag_color.sql | 7 + drizzle/meta/0006_snapshot.json | 946 ++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/app/(app)/[org]/[repo]/download-card.tsx | 6 +- src/app/(app)/[org]/[repo]/download-more.tsx | 214 ++++ src/app/(app)/[org]/[repo]/files-tab.tsx | 110 +- src/app/(app)/[org]/[repo]/page.tsx | 21 +- src/app/(app)/[org]/[repo]/tag-editor.tsx | 2 +- src/app/(app)/add-model-form.tsx | 79 +- src/app/(app)/layout.tsx | 11 +- src/app/(app)/library-view.tsx | 7 +- .../(app)/settings/labels/color-picker.tsx | 46 + .../settings/labels/file-label-settings.tsx | 112 +++ src/app/(app)/settings/labels/page.tsx | 18 + .../(app)/settings/labels/tag-settings.tsx | 122 +++ src/app/(app)/settings/layout.tsx | 16 + src/app/(app)/settings/page.tsx | 5 + src/app/(app)/settings/settings-nav.tsx | 26 + src/app/api/models/[id]/files/route.ts | 19 + src/app/api/settings/labels/route.ts | 25 + src/app/api/tags/[id]/route.ts | 25 + src/components/job-files-table.tsx | 22 +- src/components/labels.tsx | 40 + src/components/tag-badge.tsx | 50 +- src/lib/colors.ts | 79 ++ src/lib/db/schema.ts | 14 +- src/lib/file-groups.ts | 61 ++ src/lib/file-roles.ts | 66 ++ src/lib/library.ts | 8 +- src/lib/models.ts | 44 +- src/lib/search.test.ts | 59 ++ src/lib/settings.ts | 69 ++ src/lib/tags.ts | 36 +- 34 files changed, 2256 insertions(+), 132 deletions(-) create mode 100644 drizzle/0006_settings_and_tag_color.sql create mode 100644 drizzle/meta/0006_snapshot.json create mode 100644 src/app/(app)/[org]/[repo]/download-more.tsx create mode 100644 src/app/(app)/settings/labels/color-picker.tsx create mode 100644 src/app/(app)/settings/labels/file-label-settings.tsx create mode 100644 src/app/(app)/settings/labels/page.tsx create mode 100644 src/app/(app)/settings/labels/tag-settings.tsx create mode 100644 src/app/(app)/settings/layout.tsx create mode 100644 src/app/(app)/settings/page.tsx create mode 100644 src/app/(app)/settings/settings-nav.tsx create mode 100644 src/app/api/models/[id]/files/route.ts create mode 100644 src/app/api/settings/labels/route.ts create mode 100644 src/app/api/tags/[id]/route.ts create mode 100644 src/components/labels.tsx create mode 100644 src/lib/colors.ts create mode 100644 src/lib/file-groups.ts create mode 100644 src/lib/file-roles.ts create mode 100644 src/lib/settings.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7003bdf..a22ebaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/` 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. diff --git a/drizzle/0006_settings_and_tag_color.sql b/drizzle/0006_settings_and_tag_color.sql new file mode 100644 index 0000000..956458d --- /dev/null +++ b/drizzle/0006_settings_and_tag_color.sql @@ -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; \ No newline at end of file diff --git a/drizzle/meta/0006_snapshot.json b/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..a60dbe9 --- /dev/null +++ b/drizzle/meta/0006_snapshot.json @@ -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": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index ebd7d6e..7fee44e 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -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 } ] } \ No newline at end of file diff --git a/src/app/(app)/[org]/[repo]/download-card.tsx b/src/app/(app)/[org]/[repo]/download-card.tsx index ddad510..23291c8 100644 --- a/src/app/(app)/[org]/[repo]/download-card.tsx +++ b/src/app/(app)/[org]/[repo]/download-card.tsx @@ -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) { setBusy(true); @@ -57,10 +58,11 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod {files.length > 0 && (
    {files.map((f) => ( -
  • +
  • {f.path} + {f.parts > 1 && · {f.parts} parts} {formatBytes(f.expectedBytes)}
    diff --git a/src/app/(app)/[org]/[repo]/download-more.tsx b/src/app/(app)/[org]/[repo]/download-more.tsx new file mode 100644 index 0000000..31904df --- /dev/null +++ b/src/app/(app)/[org]/[repo]/download-more.tsx @@ -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>(new Set()); + const [submitting, setSubmitting] = useState(false); + + const groups = useMemo(() => { + const m = new Map(); + 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 ( +
    +
    +
    + + + {selectedCount} selected file{selectedCount === 1 ? "" : "s"} + + + {" "} + · {formatBytes(totalBytes)} · commit {shortSha(sha)} + + +
    + + {localCount} of {selectedCount} on disk · {formatBytes(localBytes)} + + {candidates.length > 0 && ( + + )} +
    +
    + +
    + + {open && ( +
    + {groups.length > 0 && ( +
    + Quick select +
    + {groups.map(([name, g]) => { + const on = g.paths.every((p) => picked.has(p)); + return ( + + ); + })} +
    +
    + )} + +
      + {entries.map((e) => { + const paths = e.parts.map((p) => p.path); + const on = paths.every((p) => picked.has(p)); + return ( +
    • + +
    • + ); + })} +
    + +
    + + + {pickedEntries} file{pickedEntries === 1 ? "" : "s"} · {formatBytes(pickedBytes)} + + {freeBytes != null && ( + + {" "} + ({formatBytes(freeBytes)} free) + + )} + +
    + + +
    +
    +
    + )} +
    + ); +} diff --git a/src/app/(app)/[org]/[repo]/files-tab.tsx b/src/app/(app)/[org]/[repo]/files-tab.tsx index 259e649..9965df6 100644 --- a/src/app/(app)/[org]/[repo]/files-tab.tsx +++ b/src/app/(app)/[org]/[repo]/files-tab.tsx @@ -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; + +/** 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 (
  • 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", )} > - + + - - {file.lfsSha256 && ( + + {split && ( + + {entry.parts.length === entry.totalParts + ? `${entry.totalParts} parts` + : `${entry.parts.length} of ${entry.totalParts} parts`} + + )} + {entry.parts[0].lfsSha256 && ( LFS )} - {formatBytes(file.size)} + {formatBytes(entry.size)} {showState ? ( {state.icon} - {state.label} + {label} ) : ( - {formatBytes(file.size)} + {formatBytes(entry.size)} )}
  • @@ -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 (
    -
    -
    - - {selected.length} selected file{selected.length === 1 ? "" : "s"} - · {formatBytes(totalBytes)} · commit {shortSha(sha)} - - - {local.length} of {selected.length} on disk · {formatBytes(localBytes)} - -
    - -
    + ({ path: f.path, size: f.size }))} + freeBytes={freeBytes} + busy={busy} + /> -
      - {selected.map((f) => ( - +
        + {selectedEntries.map((e) => ( + ))}
      - {others.length > 0 && ( + {otherEntries.length > 0 && (
      Not selected - {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))}
        - {others.map((f) => ( - + {otherEntries.map((e) => ( + ))}
      diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx index 484ac56..b3993e9 100644 --- a/src/app/(app)/[org]/[repo]/page.tsx +++ b/src/app/(app)/[org]/[repo]/page.tsx @@ -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 )}
    )} - {tab === "files" && } + {tab === "files" && ( + + )} {tab === "jobs" && (
    diff --git a/src/app/(app)/[org]/[repo]/tag-editor.tsx b/src/app/(app)/[org]/[repo]/tag-editor.tsx index c4d0453..3d265f6 100644 --- a/src/app/(app)/[org]/[repo]/tag-editor.tsx +++ b/src/app/(app)/[org]/[repo]/tag-editor.tsx @@ -51,7 +51,7 @@ export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) { return (
    {tags.map((t) => ( - + diff --git a/src/app/(app)/add-model-form.tsx b/src/app/(app)/add-model-form.tsx index ff3332a..0aef7e9 100644 --- a/src/app/(app)/add-model-form.tsx +++ b/src/app/(app)/add-model-form.tsx @@ -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({ - {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"} - - - ))} + {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 ( + + + 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} + /> + + + 1 ? parts.map((f) => f.path).join("\n") : undefined}> + + {e.path} + {e.totalParts > 1 && ( + + {e.totalParts} parts + + )} + {excluded && (excluded)} + + + {formatBytes(e.size)} + + {parts[0].lfsSha256 ? "LFS" : "git"} + + + ); + })} @@ -346,7 +363,7 @@ export function AddModelForm({
    - {selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)} + {selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)} {" "} selected {freeBytes != null && ( diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index d3c0608..5dd8718 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -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 (
    @@ -23,6 +25,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) { Library + + Settings +
    @@ -42,7 +47,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
    -
    {children}
    +
    + {children} +
    ); } diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx index 14d48df..059dc05 100644 --- a/src/app/(app)/library-view.tsx +++ b/src/app/(app)/library-view.tsx @@ -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) => : undefined} + marker={facet === "tag" ? (v) => : undefined} /> ))}
    @@ -136,7 +137,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) { {FACETS.flatMap((facet) => filters[facet].map((v) => ( - {facet === "tag" && } + {facet === "tag" && } {FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v} ))}
    diff --git a/src/app/(app)/settings/labels/color-picker.tsx b/src/app/(app)/settings/labels/color-picker.tsx new file mode 100644 index 0000000..f00b87d --- /dev/null +++ b/src/app/(app)/settings/labels/color-picker.tsx @@ -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 ( + + }> + + {value ?? "Automatic"} + + + + {allowAuto && ( + onChange(null)}> + + Automatic + + )} + {LABEL_COLORS.map((c) => ( + onChange(c)}> + + {c} + + ))} + + + ); +} diff --git a/src/app/(app)/settings/labels/file-label-settings.tsx b/src/app/(app)/settings/labels/file-label-settings.tsx new file mode 100644 index 0000000..bc00845 --- /dev/null +++ b/src/app/(app)/settings/labels/file-label-settings.tsx @@ -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) { + 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 ( + + + File labels + + 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. + + + +
    + {FILE_ROLE_ORDER.map((role) => { + const s = styles[role]; + const changed = s.label !== defaults[role].label || s.color !== defaults[role].color; + return ( +
    + + {s.label || "…"} + + {FILE_ROLES[role].description} + update(role, { label: e.target.value })} + aria-label={`Label for ${FILE_ROLES[role].label}`} + className="h-8" + /> + c && update(role, { color: c })} /> + +
    + ); + })} +
    +
    + + + +
    +
    +
    + ); +} diff --git a/src/app/(app)/settings/labels/page.tsx b/src/app/(app)/settings/labels/page.tsx new file mode 100644 index 0000000..d827c7b --- /dev/null +++ b/src/app/(app)/settings/labels/page.tsx @@ -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 ( +
    + + +
    + ); +} diff --git a/src/app/(app)/settings/labels/tag-settings.tsx b/src/app/(app)/settings/labels/tag-settings.tsx new file mode 100644 index 0000000..ce95e86 --- /dev/null +++ b/src/app/(app)/settings/labels/tag-settings.tsx @@ -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 ( + + + Tags + + Your own tags (added on a model page or when adding a model). Tags without a color get an automatic one. + + + + {tags.length === 0 ? ( +

    No tags yet.

    + ) : ( +
    + {tags.map((t) => ( + + ))} +
    + )} +
    +
    + ); +} + +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 ( +
    + + 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" + /> + patch({ color: c })} allowAuto autoColor={autoTagColor(tag.name)} /> + + {tag.count} model{tag.count === 1 ? "" : "s"} + + + }> + + + + + Delete tag “{tag.name}”? + + It is removed from {tag.count} model{tag.count === 1 ? "" : "s"}. The models themselves are not touched. + + + + Cancel + + Delete + + + + +
    + ); +} diff --git a/src/app/(app)/settings/layout.tsx b/src/app/(app)/settings/layout.tsx new file mode 100644 index 0000000..4d53499 --- /dev/null +++ b/src/app/(app)/settings/layout.tsx @@ -0,0 +1,16 @@ +import { TagsIcon } from "lucide-react"; +import { SettingsNav } from "./settings-nav"; + +const SECTIONS = [{ href: "/settings/labels", label: "Labels", icon: }]; + +export default function SettingsLayout({ children }: LayoutProps<"/settings">) { + return ( +
    +

    Settings

    +
    + +
    {children}
    +
    +
    + ); +} diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx new file mode 100644 index 0000000..5334fe5 --- /dev/null +++ b/src/app/(app)/settings/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from "next/navigation"; + +export default function SettingsPage() { + redirect("/settings/labels"); +} diff --git a/src/app/(app)/settings/settings-nav.tsx b/src/app/(app)/settings/settings-nav.tsx new file mode 100644 index 0000000..ce1433a --- /dev/null +++ b/src/app/(app)/settings/settings-nav.tsx @@ -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 ( + + ); +} diff --git a/src/app/api/models/[id]/files/route.ts b/src/app/api/models/[id]/files/route.ts new file mode 100644 index 0000000..2016168 --- /dev/null +++ b/src/app/api/models/[id]/files/route.ts @@ -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>(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); + } +}); diff --git a/src/app/api/settings/labels/route.ts b/src/app/api/settings/labels/route.ts new file mode 100644 index 0000000..0897d90 --- /dev/null +++ b/src/app/api/settings/labels/route.ts @@ -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); + } +}); diff --git a/src/app/api/tags/[id]/route.ts b/src/app/api/tags/[id]/route.ts new file mode 100644 index 0000000..a64f80e --- /dev/null +++ b/src/app/api/tags/[id]/route.ts @@ -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>(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>(async (_req, { params }) => { + const { id } = await params; + await deleteTag(id); + return new NextResponse(null, { status: 204 }); +}); diff --git a/src/components/job-files-table.tsx b/src/components/job-files-table.tsx index b93751b..cf2edc1 100644 --- a/src/components/job-files-table.tsx +++ b/src/components/job-files-table.tsx @@ -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 ( @@ -15,16 +17,26 @@ export function JobFilesTable({ files }: { files: JobFileSnapshot[] }) { - {files.map((f) => { + {groupJobFiles(files).map((f) => { const pct = percent(f.doneBytes, f.expectedBytes); return ( - - {f.path} + + + + + {f.path} + {f.parts > 1 && ( + + {f.parts} parts + + )} + +
    - {f.state === "failed" ? "missing" : `${pct.toFixed(0)}%`} + {f.failed ? "missing" : `${pct.toFixed(0)}%`}
    diff --git a/src/components/labels.tsx b/src/components/labels.tsx new file mode 100644 index 0000000..5389004 --- /dev/null +++ b/src/components/labels.tsx @@ -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(defaults); + +/** Provides the label settings (from the Settings page) to client components. */ +export function LabelSettingsProvider({ fileRoles, children }: { fileRoles: FileRoleStyles; children: React.ReactNode }) { + return {children}; +} + +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 ( + + {style.label} + + ); +} diff --git a/src/components/tag-badge.tsx b/src/components/tag-badge.tsx index 6c6a131..258fcb3 100644 --- a/src/components/tag-badge.tsx +++ b/src/components/tag-badge.tsx @@ -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 ; +export function TagDot({ name, color }: { name: string; color?: string | null }) { + return ; } -/** 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({ diff --git a/src/lib/colors.ts b/src/lib/colors.ts new file mode 100644 index 0000000..3d05094 --- /dev/null +++ b/src/lib/colors.ts @@ -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 = { + 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 = { + 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]; +} diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 2d6ab64..b20fd20 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -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 // --------------------------------------------------------------------------- diff --git a/src/lib/file-groups.ts b/src/lib/file-groups.ts new file mode 100644 index 0000000..d1cbfa0 --- /dev/null +++ b/src/lib/file-groups.ts @@ -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 = { + /** 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(files: T[]): FileGroup[] { + const groups: FileGroup[] = []; + const byBase = new Map>(); + 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, + })); +} diff --git a/src/lib/file-roles.ts b/src/lib/file-roles.ts new file mode 100644 index 0000000..d28119f --- /dev/null +++ b/src/lib/file-roles.ts @@ -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 = { + 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; + +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"; +} diff --git a/src/lib/library.ts b/src/lib/library.ts index 192f285..81294ab 100644 --- a/src/lib/library.ts +++ b/src/lib/library.ts @@ -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(); - 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, diff --git a/src/lib/models.ts b/src/lib/models.ts index 5bbd146..61c8507 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -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(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 }; +} diff --git a/src/lib/search.test.ts b/src/lib/search.test.ts index a851683..ffa73f8 100644 --- a/src/lib/search.test.ts +++ b/src/lib/search.test.ts @@ -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); + }); +}); diff --git a/src/lib/settings.ts b/src/lib/settings.ts new file mode 100644 index 0000000..ec4252a --- /dev/null +++ b/src/lib/settings.ts @@ -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>; + +async function read(key: string): Promise { + 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 { + const stored = (await read(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): Promise { + 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(); +} diff --git a/src/lib/tags.ts b/src/lib/tags.ts index 9eadade..e92666b 100644 --- a/src/lib/tags.ts +++ b/src/lib/tags.ts @@ -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`count(${modelTags.modelId})` }) + .select({ id: tags.id, name: tags.name, color: tags.color, count: sql`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 { 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 { 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 { export async function deleteUnusedTags(): Promise { 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 { + 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 { + const d = db(); + await d.batch([d.delete(modelTags).where(eq(modelTags.tagId, id)), d.delete(tags).where(eq(tags.id, id))]); +}