diff --git a/.env.example b/.env.example index 1ccfb5f..82fc1ec 100644 --- a/.env.example +++ b/.env.example @@ -1,32 +1,44 @@ -# Hugging Face token (server-side only; passed to the hf CLI via environment) +# --------------------------------------------------------------------------- +# Required +# --------------------------------------------------------------------------- + +# URL you open Kaname at in the browser. Your OIDC redirect URI is +# /api/auth/callback/pocket-id +AUTH_URL=http://localhost:3000 +# Random secret for session cookies: `openssl rand -base64 33` +AUTH_SECRET= + +# OIDC provider (e.g. Pocket ID): authorization code flow with PKCE +OIDC_ISSUER=https://auth.example.com +OIDC_CLIENT_ID= +OIDC_CLIENT_SECRET= +# Optional, comma-separated: only members of these groups (`groups` claim) can log in. +OIDC_ALLOWED_GROUPS= + +# Hugging Face token: read-only is enough. Needed for gated/private repos, recommended anyway +# (higher rate limits). Stays on the server; never sent to the browser or written to logs. HF_TOKEN= -# Where models are stored: // -MODELS_DIR=/models -# SQLite database (keep on a local volume, not NFS) -DATABASE_URL=file:/data/app.db + +# --------------------------------------------------------------------------- +# Folders on the Docker host (deploy/compose.yaml); both must be owned by uid 1000 +# --------------------------------------------------------------------------- + +# SQLite database, shared by web and worker. Must be on local disk, not NFS. +KANAME_DATA_DIR=./data +# Downloaded models. Can be a NAS share mounted on the host, e.g. /mnt/nas/models. +KANAME_MODELS_DIR=./models +# Host port of the web UI +WEB_PORT=3000 +# Image tag to run, e.g. 0.4.0 (default: latest) +KANAME_VERSION= + +# --------------------------------------------------------------------------- +# Optional tuning +# --------------------------------------------------------------------------- + MAX_CONCURRENT_DOWNLOADS=1 -# 0 disables the periodic update check +# Hub update check interval; 0 disables it UPDATE_CHECK_INTERVAL_HOURS=12 # 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk. # 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps. HF_HUB_DISABLE_XET=1 - -# Auth.js: generate with `npx auth secret` or `openssl rand -base64 33` -AUTH_SECRET= -# Public URL of this app; OIDC redirect URI is /api/auth/callback/pocket-id -AUTH_URL=https://models.example.com -OIDC_ISSUER=https://auth.example.com -OIDC_CLIENT_ID= -OIDC_CLIENT_SECRET= -# Optional, comma-separated. If set, only members of these groups (from the `groups` claim) can log in. -OIDC_ALLOWED_GROUPS= - -# --- deploy/compose.yaml only ------------------------------------------------- -# Image tag to run (default: latest) -KANAME_VERSION= -# Host folder for the SQLite DB, shared by web and worker. Local disk, not NFS. Owner uid 1000. -KANAME_DATA_DIR=./data -WEB_PORT=3000 -# NFS export for the models (NFSv4, writable by uid 1000) -NFS_SERVER=truenas.lan -NFS_EXPORT=/mnt/tank/models diff --git a/CHANGELOG.md b/CHANGELOG.md index ba345f0..eb6bb6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,33 @@ step 1 (Hugging Face downloader) is released as a minor version. ## [Unreleased] +## [0.4.0] - 2026-10-05 + +The app is now called **Kaname**; search, filters and tags. + +### Added + +- Library search: every word must match the repo, author, model family, base model, architecture, + quant, tags, Hub tags or status (e.g. `unsloth qwen`, `q4_k_m`, `roleplay`). +- Library filters for Author, Family, Quant, Tag and Status (multi-select with counts, combinable, + kept in the URL), removable filter chips and "N of M models". +- Hub metadata per model: base model(s), architecture, license, pipeline tag and Hub tags. The + "family" is the base model's org (an unsloth quant of Qwen3 → `Qwen`). Stored when a model is + added; the worker fetches it for existing models on startup. +- Custom tags: add/remove on the model page (with suggestions), set them when adding a model, + click a tag in the library to filter. Tags are case-insensitive and deleted when unused. +- Model page shows author, family, base model links, architecture, license and Hub tags. +- README rewritten around a four-step install, with a banner and screenshots. + +### Changed + +- Renamed the app from "Model Manager" to "Kaname". +- `deploy/compose.yaml`: models go to a host folder (`KANAME_MODELS_DIR`, default `./models`; + a NAS share mounted on the host works) instead of a Docker NFS volume, so the default setup + needs no NAS. `NFS_SERVER`/`NFS_EXPORT` are gone. +- `.env.example` is ordered by what you need to fill in; container-internal paths + (`DATABASE_URL`, `MODELS_DIR`) are no longer in it because the image defaults are correct. + ## [0.3.1] - 2026-10-05 Release pipeline, server deployment and a simpler library page. diff --git a/README.md b/README.md index 5a5f597..4daffd4 100644 --- a/README.md +++ b/README.md @@ -1,94 +1,145 @@ -# Model Manager +

+ Kaname: self-hosted model manager for Hugging Face +

-Self-hosted web UI for downloading and managing local LLMs from Hugging Face. -Downloads are done by the official `hf` CLI; the Hub API is used for metadata. +**Kaname** (要, "the pivot") is a self-hosted web app for downloading and managing local LLMs from +Hugging Face. Look up a repo, pick the quant you want, and Kaname downloads exactly those files with +the official `hf` CLI, pinned to a specific commit so every download is reproducible. -## Architecture +- **Pick files, not whole repos:** one-click quant selection for GGUF repos, or include/exclude globs. +- **Pinned and reproducible:** every model is pinned to the exact commit SHA you reviewed. +- **Downloads in the background:** live progress, speed and ETA per file; keeps going when you close + the browser; cancel any time. +- **Find things again:** search and filter by author, model family (e.g. Qwen, Gemma), quant, status + and your own tags like `roleplay` or `security`. +- **Homelab-friendly:** two containers, SQLite, OIDC single sign-on (e.g. Pocket ID), models on any + folder or NAS share. -- **web** (`next start`): Next.js App Router UI + API routes, OIDC login via Auth.js. -- **worker** (`src/worker`): owns the job queue, spawns `hf download`, tracks progress from bytes on - disk, applies DB migrations at startup. Only one worker runs at a time (DB lease). -- They talk only through the SQLite database (`DATABASE_URL`); the UI gets live updates via SSE - (`/api/stream`). +## Install -## Run with Docker (recommended) +You need Docker with Compose and an OIDC provider (e.g. [Pocket ID](https://pocket-id.org)). + +**1. Get the compose file and the config template** ```bash -cp .env.example .env # fill in HF_TOKEN, AUTH_SECRET, OIDC_*; AUTH_URL = URL you open in the browser -docker compose up --build +mkdir kaname && cd kaname +curl -fsSLo compose.yaml https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/deploy/compose.yaml +curl -fsSLo .env https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/.env.example ``` -Open `AUTH_URL` (e.g. http://localhost:3000). `WEB_PORT=3100 docker compose up` changes the host port. -Volumes: `data` (SQLite + hf home, keep on local disk) and `models` (downloaded models). +**2. Create an OIDC client** in your identity provider with the redirect URI +`/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`. +Request the `groups` scope if you want to restrict access by group. -OIDC redirect URI for the client in Pocket ID: `/api/auth/callback/pocket-id`. +**3. Fill in `.env`.** At minimum: `AUTH_URL` (the address you open in the browser), `AUTH_SECRET` +(`openssl rand -base64 33`), `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a +read-only `HF_TOKEN`. -## Releases and deployment - -Pushing a tag `vX.Y.Z` (must equal `version` in `package.json` and have a `## [X.Y.Z]` section in -`CHANGELOG.md`) runs `.gitea/workflows/release.yaml` on Gitea Actions: - -1. lint, typecheck, unit tests -2. builds the image and pushes `git.linxweiler.xyz/pascallinxweiler/kaname:X.Y.Z`, `:X.Y` and `:latest` -3. creates a Gitea release with the CHANGELOG section as notes - -Requirements: an `act_runner` registered for the repo/user with Docker access, and a repo secret -`REGISTRY_TOKEN` (personal access token with *package: read and write*). - -On the server you only need `deploy/compose.yaml` and a filled-in `.env` (from `.env.example`) in -one folder; no source code, no Dockerfile: +**4. Create the folders and start** ```bash -mkdir -p data && sudo chown 1000:1000 data # SQLite DB, shared by web and worker (local disk!) -docker compose pull && docker compose up -d +mkdir -p data models && sudo chown 1000:1000 data models +docker compose up -d ``` -Storage layout on the server: +Open your `AUTH_URL`, sign in, click **Add model**. That's it. -- `KANAME_DATA_DIR` (default `./data`): bind mount for the SQLite DB, mounted by both services. - Must be on local disk (SQLite breaks on NFS) and owned by uid 1000. -- `models`: NFS volume from `NFS_SERVER`/`NFS_EXPORT`, mounted only by the worker. Use NFSv4 - (hf needs file locks) and make the dataset writable for uid 1000 (owner 1000, or TrueNAS - *Mapall User/Group*). After changing NFS settings: `docker compose down && docker volume rm kaname_models`. +**Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g. +`KANAME_VERSION=0.4.0` in `.env`. The running version is shown next to the app name. -Pin a version with `KANAME_VERSION=0.4.0` in `.env`; the running version is shown next to the app -name in the header. +### Storing models on a NAS -The image picks its role from the first argument: `web` (default) or `worker`. Both run pending -DB migrations at startup (serialized with a file lock on `/data`), and the image has a built-in -healthcheck for both roles. +Mount the share on the Docker host and point `KANAME_MODELS_DIR` at it, e.g. in `/etc/fstab`: -## Local development +``` +truenas.lan:/mnt/tank/models /mnt/nas/models nfs4 rw,hard,noatime,_netdev 0 0 +``` + +```bash +# .env +KANAME_MODELS_DIR=/mnt/nas/models +``` + +- Use NFSv4: the `hf` CLI uses file locks. +- The share must be writable for uid 1000 (dataset owner 1000, or TrueNAS *Mapall User/Group*). +- Mount it before the containers start (`_netdev`), otherwise Docker uses the empty local folder. +- Keep `KANAME_DATA_DIR` on local disk: SQLite doesn't work reliably on NFS. + +## Configuration + +All settings live in `.env` (see [`.env.example`](.env.example)): + +| Variable | Default | | +| --- | --- | --- | +| `AUTH_URL` | | Public URL of Kaname (used for the OIDC redirect) | +| `AUTH_SECRET` | | Secret for session cookies | +| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | | OIDC provider (authorization code + PKCE) | +| `OIDC_ALLOWED_GROUPS` | *(anyone)* | Comma-separated groups from the `groups` claim | +| `HF_TOKEN` | | Hugging Face token (read-only is enough) | +| `KANAME_DATA_DIR` | `./data` | Host folder for the SQLite DB (local disk) | +| `KANAME_MODELS_DIR` | `./models` | Host folder for downloaded models | +| `WEB_PORT` | `3000` | Host port of the web UI | +| `KANAME_VERSION` | `latest` | Image tag to run | +| `MAX_CONCURRENT_DOWNLOADS` | `1` | Downloads running in parallel | +| `UPDATE_CHECK_INTERVAL_HOURS` | `12` | Hub update checks (`0` = off) | +| `HF_HUB_DISABLE_XET` | `1` | `0` uses Xet transfers (progress then only moves in large jumps) | + +Models end up in `///`, e.g. `models/unsloth/Qwen3-8B-GGUF/`. + +## Using it + +

+ Adding a model: quant quick-select +

+ +- **Add model:** enter a repo ID like `unsloth/Qwen3-8B-GGUF` (or paste the URL), click a quant, and + **Add & download**. You can add tags right there. +- **Search:** type anything: `unsloth qwen`, `q4_k_m`, `gemma`, `roleplay`. Every word has to match + somewhere (repo, author, base model family, architecture, quant, tags). +- **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so + you can bookmark a view. +- **Tags:** add or remove your own tags on a model's page; click a tag in the list to filter by it. +- **Jobs:** each download has a page with per-file progress and the full `hf` log. + +## How it works + +Two containers from the same image share one SQLite database: + +- **web:** Next.js UI and API, OIDC login (Auth.js); live updates via Server-Sent Events. +- **worker:** runs the download queue, spawns `hf download --revision --include `, and + measures progress from bytes on disk. Only one worker runs at a time. + +Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image): + +- Interrupted files are **not resumed**: a re-run skips finished files and restarts unfinished ones. + Kaname cleans up the leftover partial files. +- With Xet transfers the partial file only grows in large bursts, so Kaname disables Xet by default + to show accurate progress. +- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash + metadata after each download. + +## Development ```bash npm install -npm run dev # web (http://localhost:3000) + worker +cp .env.example .env # plus DATABASE_URL=file:./data/app.db and MODELS_DIR=./data/models +npm run dev # web on http://localhost:3000 + worker ``` -Use local paths in `.env` (`DATABASE_URL=file:./data/app.db`, `MODELS_DIR=./data/models`). -The worker needs the `hf` CLI on `PATH` (`pip install "huggingface_hub[hf_xet]==2.1.1"`); without it -everything but downloading works. Don't point a Windows-native web app and a containerized worker at -the same SQLite file: SQLite locking doesn't work across that boundary. +The worker needs `hf` on `PATH` (`pip install "huggingface_hub[hf_xet]==2.1.1"`). Without it, +everything but downloading works. `docker compose up --build` (root `compose.yaml`) builds and runs +the image locally. | Script | What it does | | --- | --- | | `npm run dev:web` / `npm run dev:worker` | run one side only | -| `npm run db:generate` | create a migration after changing `src/lib/db/schema.ts` | -| `npm run db:migrate` | apply migrations without starting the worker | -| `npm run build:worker` | bundle the worker to `dist/worker.mjs` (used in the image) | -| `npm test` | unit tests (Node test runner via tsx) | +| `npm test` | unit tests | | `npm run typecheck`, `npm run lint` | checks | +| `npm run db:generate` | new migration after changing `src/lib/db/schema.ts` | +| `npm run build:worker` | bundle worker + migrate script into `dist/` (used by the image) | -## How `hf download` behaves (huggingface_hub 2.1.1) - -Verified in a container; the image pins this version. Re-check before bumping it. - -- With `--local-dir`, partial files live in `/.cache/huggingface/download/` as - `...incomplete` and are moved into place when complete. -- **Partial files are not resumed.** A re-run skips completed files but restarts unfinished ones - from zero (new random name). The worker deletes leftover partials. -- With Xet enabled the partial file only grows in large bursts, so the worker sets - `HF_HUB_DISABLE_XET=1` by default for accurate progress (configurable in `.env`). -- SIGTERM stops a download (exit 143); SIGINT does not stop a Xet download. -- Exit code 0 doesn't guarantee the files are there (e.g. a pattern that matched nothing), so the - worker checks every expected file's size and metadata afterwards. +**Releases:** bump `version` in `package.json`, add a `## [X.Y.Z]` section to +[`CHANGELOG.md`](CHANGELOG.md), commit and push a `vX.Y.Z` tag. Gitea Actions +([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)) runs the checks, pushes +`git.linxweiler.xyz/pascallinxweiler/kaname:X.Y.Z` (+ `X.Y`, `latest`) and creates the release. +It needs an `act_runner` with Docker access and a `REGISTRY_TOKEN` repo secret (package read/write). diff --git a/deploy/compose.yaml b/deploy/compose.yaml index eb56880..f903f68 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -1,6 +1,6 @@ -# Server setup: put this file and a filled-in .env (from .env.example) in a folder, then -# mkdir -p data && sudo chown 1000:1000 data -# docker compose pull && docker compose up -d +# Kaname: put this file and a filled-in .env (from .env.example) in one folder, then +# mkdir -p data models && sudo chown 1000:1000 data models +# docker compose up -d name: kaname services: @@ -9,8 +9,8 @@ services: command: worker env_file: .env volumes: - - ${KANAME_DATA_DIR:-./data}:/data - - models:/models + - ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS) + - ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works) restart: unless-stopped web: @@ -20,15 +20,3 @@ services: volumes: - ${KANAME_DATA_DIR:-./data}:/data restart: unless-stopped - -volumes: - # Downloaded models on the NAS (only the worker mounts it). NFSv4 because hf uses file locks; - # "hard" makes writes wait while the NAS is unreachable instead of failing half-written. - # Docker keeps these options once the volume exists: after changing them, run - # `docker compose down && docker volume rm kaname_models` (files on the NAS are not touched). - models: - driver: local - driver_opts: - type: nfs - o: "addr=${NFS_SERVER:?set NFS_SERVER in .env},nfsvers=4.1,rw,hard,noatime" - device: ":${NFS_EXPORT:?set NFS_EXPORT in .env}" diff --git a/docs/banner.png b/docs/banner.png new file mode 100644 index 0000000..e5438f1 Binary files /dev/null and b/docs/banner.png differ diff --git a/docs/screenshots/add-model.png b/docs/screenshots/add-model.png new file mode 100644 index 0000000..32fffdf Binary files /dev/null and b/docs/screenshots/add-model.png differ diff --git a/docs/screenshots/library.png b/docs/screenshots/library.png new file mode 100644 index 0000000..173a33e Binary files /dev/null and b/docs/screenshots/library.png differ diff --git a/drizzle/0003_model_metadata_and_tags.sql b/drizzle/0003_model_metadata_and_tags.sql new file mode 100644 index 0000000..511983d --- /dev/null +++ b/drizzle/0003_model_metadata_and_tags.sql @@ -0,0 +1,24 @@ +CREATE TABLE `model_tags` ( + `model_id` text NOT NULL, + `tag_id` text NOT NULL, + `created_at` integer NOT NULL, + PRIMARY KEY(`model_id`, `tag_id`), + FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action, + FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE no action +); +--> statement-breakpoint +CREATE INDEX `model_tags_tag_idx` ON `model_tags` (`tag_id`);--> statement-breakpoint +CREATE TABLE `tags` ( + `id` text PRIMARY KEY NOT NULL, + `name` text NOT NULL, + `slug` text NOT NULL, + `created_at` integer NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX `tags_slug_uq` ON `tags` (`slug`);--> statement-breakpoint +ALTER TABLE `models` ADD `base_models` text;--> statement-breakpoint +ALTER TABLE `models` ADD `architecture` text;--> statement-breakpoint +ALTER TABLE `models` ADD `pipeline_tag` text;--> statement-breakpoint +ALTER TABLE `models` ADD `license` text;--> statement-breakpoint +ALTER TABLE `models` ADD `hub_tags` text;--> statement-breakpoint +ALTER TABLE `models` ADD `metadata_fetched_at` integer; \ No newline at end of file diff --git a/drizzle/meta/0003_snapshot.json b/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..32159f4 --- /dev/null +++ b/drizzle/meta/0003_snapshot.json @@ -0,0 +1,894 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "9c67e3d1-730e-4c71-ac1e-2ec7d0d37dea", + "prevId": "ccc02033-9cf0-4202-af94-36f060837602", + "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 + }, + "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": {} + }, + "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 + }, + "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 2f2783e..8524a1b 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1791210991713, "tag": "0002_worker_lease", "breakpoints": true + }, + { + "idx": 3, + "version": "6", + "when": 1791221700558, + "tag": "0003_model_metadata_and_tags", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 2bfc7e3..409f16e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaname", - "version": "0.3.1", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaname", - "version": "0.3.1", + "version": "0.4.0", "dependencies": { "@base-ui/react": "^1.8.0", "@libsql/client": "^0.18.0", diff --git a/package.json b/package.json index 3106a34..9a96417 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kaname", - "version": "0.3.1", + "version": "0.4.0", "private": true, "scripts": { "dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"", diff --git a/src/app/(app)/add-model-form.tsx b/src/app/(app)/add-model-form.tsx index 0643fc5..6c5771c 100644 --- a/src/app/(app)/add-model-form.tsx +++ b/src/app/(app)/add-model-form.tsx @@ -1,7 +1,7 @@ "use client"; import Link from "next/link"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; @@ -44,6 +44,15 @@ export function AddModelForm({ const [includeText, setIncludeText] = useState(""); const [excludeText, setExcludeText] = useState(""); const [submitting, setSubmitting] = useState(false); + const [tagsText, setTagsText] = useState(""); + const [knownTags, setKnownTags] = useState([]); + + useEffect(() => { + fetch("/api/tags") + .then((r) => (r.ok ? r.json() : [])) + .then((all: { name: string }[]) => setKnownTags(all.map((t) => t.name))) + .catch(() => {}); + }, []); async function lookup(e: React.FormEvent) { e.preventDefault(); @@ -56,6 +65,7 @@ export function AddModelForm({ setChecked(new Set()); setIncludeText(""); setExcludeText(""); + setTagsText(""); } catch (err) { setResult(null); setError(err instanceof Error ? err.message : String(err)); @@ -129,6 +139,7 @@ export function AddModelForm({ sha: result.sha, include: [...includePatterns, ...[...checked].sort().map(escapeGlob)], exclude: excludePatterns, + tags: parsePatternList(tagsText), }); toast.success(`${result.repoId} added, download queued`); onAdded(id); @@ -269,6 +280,23 @@ export function AddModelForm({ folder. Selected = checked or matching an include pattern, minus excludes.

+ +
+ + setTagsText(e.target.value)} + placeholder="roleplay, security" + list="known-tags" + /> + + {knownTags.map((t) => ( + +

Optional, comma-separated. Editable later on the model page.

+
diff --git a/src/app/(app)/facet-filter.tsx b/src/app/(app)/facet-filter.tsx new file mode 100644 index 0000000..e57cac8 --- /dev/null +++ b/src/app/(app)/facet-filter.tsx @@ -0,0 +1,51 @@ +"use client"; + +import { ChevronDownIcon } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; + +/** Multi-select dropdown for one facet, with per-value counts. */ +export function FacetFilter({ + label, + values, + selected, + onChange, + format = (v) => v, +}: { + label: string; + values: [string, number][]; + selected: string[]; + onChange: (next: string[]) => void; + format?: (value: string) => string; +}) { + const active = selected.length > 0; + return ( + + } + > + {label} + {active && {selected.length}} + + + + {values.map(([value, count]) => ( + onChange(on ? [...selected, value] : selected.filter((v) => v !== value))} + > + {format(value)} + {count} + + ))} + + + ); +} diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index b3add42..90bd041 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -16,7 +16,7 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
- Model Manager + Kaname {process.env.APP_VERSION ?? "dev"}
+ @@ -43,6 +48,30 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) { huggingface.co/{model.repoId} +
Author
+
{model.repoId.split("/")[0]}
+
Family
+
{modelFamilies(model.repoId, model.baseModels).join(", ")}
+
Base model
+
+ {(model.baseModels ?? []).length === 0 + ? "–" + : model.baseModels!.map((b) => ( + + {b} + + ))} +
+
Architecture
+
{model.architecture ?? "–"}
+
License
+
{model.license ?? "–"}
+ {(model.hubTags ?? []).length > 0 && ( + <> +
Hub tags
+
{model.hubTags!.join(", ")}
+ + )}
Tracked revision
{model.trackedRevision}
Pinned SHA
diff --git a/src/app/(app)/models/[id]/tag-editor.tsx b/src/app/(app)/models/[id]/tag-editor.tsx new file mode 100644 index 0000000..08c96be --- /dev/null +++ b/src/app/(app)/models/[id]/tag-editor.tsx @@ -0,0 +1,87 @@ +"use client"; + +import { XIcon } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useEffect, useId, useState } from "react"; +import { toast } from "sonner"; +import { Badge } from "@/components/ui/badge"; +import { Input } from "@/components/ui/input"; +import type { Tag } from "@/lib/tags"; + +/** Add/remove user tags on a model; suggests existing tags. */ +export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) { + const router = useRouter(); + const listId = useId(); + const [value, setValue] = useState(""); + const [busy, setBusy] = useState(false); + const [suggestions, setSuggestions] = useState([]); + + useEffect(() => { + fetch("/api/tags") + .then((r) => (r.ok ? r.json() : [])) + .then((all: Tag[]) => setSuggestions(all.map((t) => t.name))) + .catch(() => {}); + }, [tags]); + + async function add(name: string) { + if (!name.trim()) return; + setBusy(true); + const res = await fetch(`/api/models/${modelId}/tags`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name }), + }); + setBusy(false); + if (!res.ok) { + const body = await res.json().catch(() => ({})); + toast.error(body.error?.message ?? `Could not add tag (${res.status})`); + return; + } + setValue(""); + router.refresh(); + } + + async function remove(tag: Tag) { + const res = await fetch(`/api/models/${modelId}/tags/${tag.id}`, { method: "DELETE" }); + if (!res.ok) toast.error(`Could not remove tag (${res.status})`); + router.refresh(); + } + + const current = new Set(tags.map((t) => t.name.toLowerCase())); + return ( +
+ {tags.map((t) => ( + + {t.name} + + + ))} +
{ + e.preventDefault(); + void add(value); + }} + > + setValue(e.target.value)} + list={listId} + placeholder="Add tag…" + disabled={busy} + maxLength={40} + className="h-6 w-36 text-xs" + aria-label="Add tag" + /> + + {suggestions + .filter((s) => !current.has(s.toLowerCase())) + .map((s) => ( + +
+
+ ); +} diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 146e8f3..66f2f62 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -1,7 +1,7 @@ import { listLibrary } from "@/lib/library"; import { getWorkerStatus } from "@/lib/worker-status"; import { AddModelPanel } from "./add-model-panel"; -import { LibraryTable } from "./library-table"; +import { LibraryView } from "./library-view"; export const dynamic = "force-dynamic"; @@ -12,7 +12,7 @@ export default async function LibraryPage() {
{/* Opens by default while the library is empty. */} - {rows.length > 0 && } + {rows.length > 0 && }
); } diff --git a/src/app/api/models/[id]/tags/[tagId]/route.ts b/src/app/api/models/[id]/tags/[tagId]/route.ts new file mode 100644 index 0000000..b6bb7a8 --- /dev/null +++ b/src/app/api/models/[id]/tags/[tagId]/route.ts @@ -0,0 +1,10 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { removeTag } from "@/lib/tags"; + +/** Detach a tag from a model. */ +export const DELETE = withAuth>(async (_req, { params }) => { + const { id, tagId } = await params; + await removeTag(id, tagId); + return new NextResponse(null, { status: 204 }); +}); diff --git a/src/app/api/models/[id]/tags/route.ts b/src/app/api/models/[id]/tags/route.ts new file mode 100644 index 0000000..a187935 --- /dev/null +++ b/src/app/api/models/[id]/tags/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 { addTag, TagError } from "@/lib/tags"; + +const Body = z.object({ name: z.string() }); + +/** Attach a tag to a model (creates the tag on first use). */ +export const POST = withAuth>(async (req, { params }) => { + const { id } = await params; + try { + const { name } = Body.parse(await req.json()); + return NextResponse.json(await addTag(id, name), { status: 201 }); + } catch (err) { + if (err instanceof TagError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts index bf5aa35..50ad713 100644 --- a/src/app/api/models/route.ts +++ b/src/app/api/models/route.ts @@ -5,6 +5,7 @@ import { apiError, handleApiError } from "@/lib/api-errors"; import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client"; import { queueDownload } from "@/lib/jobs"; import { addModel, ModelError } from "@/lib/models"; +import { addTag, normalizeTagName, TagError } from "@/lib/tags"; const Body = z.object({ repoId: z.string().regex(REPO_ID_RE), @@ -13,22 +14,25 @@ const Body = z.object({ include: z.array(z.string().min(1).max(1024)).max(10_000), exclude: z.array(z.string().min(1).max(1024)).max(1_000), download: z.boolean().default(true), + tags: z.array(z.string()).max(50).default([]), }); /** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */ export const POST = withAuth(async (req) => { try { const body = Body.parse(await req.json()); + body.tags.forEach(normalizeTagName); // validate before anything is written const { id } = await addModel({ repoId: body.repoId, revision: body.revision, sha: body.sha, rule: { include: body.include, exclude: body.exclude }, }); + for (const tag of body.tags) await addTag(id, tag); const job = body.download ? await queueDownload(id) : null; return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 }); } catch (err) { - if (err instanceof ModelError) return apiError(err.status, err.code, err.message); + if (err instanceof ModelError || err instanceof TagError) return apiError(err.status, err.code, err.message); return handleApiError(err); } }); diff --git a/src/app/api/tags/route.ts b/src/app/api/tags/route.ts new file mode 100644 index 0000000..c37e22d --- /dev/null +++ b/src/app/api/tags/route.ts @@ -0,0 +1,8 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { listTags } from "@/lib/tags"; + +export const dynamic = "force-dynamic"; + +/** All user tags with usage counts. */ +export const GET = withAuth(async () => NextResponse.json(await listTags())); diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 6e5eea6..43c9aa9 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -9,7 +9,7 @@ const geist = Geist({ subsets: ["latin"], variable: "--font-sans" }); const geistMono = Geist_Mono({ subsets: ["latin"], variable: "--font-mono" }); export const metadata: Metadata = { - title: "Model Manager", + title: { default: "Kaname", template: "%s · Kaname" }, description: "Download and manage local LLMs from Hugging Face", }; diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index 21b821b..6b0fdf1 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -28,7 +28,7 @@ export default async function LoginPage({ searchParams }: PageProps<"/login">) {
- Model Manager + Kaname Sign in to manage local models. diff --git a/src/components/model-status-badge.tsx b/src/components/model-status-badge.tsx index 2bf82e4..907e07b 100644 --- a/src/components/model-status-badge.tsx +++ b/src/components/model-status-badge.tsx @@ -1,7 +1,7 @@ import { Badge } from "@/components/ui/badge"; import type { ModelStatus } from "@/lib/db/schema"; -const LABELS: Record = { +export const MODEL_STATUS: Record = { pending: { label: "not downloaded", variant: "outline" }, downloading: { label: "downloading", variant: "secondary" }, ready: { label: "ok", variant: "default" }, @@ -11,6 +11,6 @@ const LABELS: Record{label}; } diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index a5e9c3f..48e5582 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -75,12 +75,53 @@ export const models = sqliteTable( lastCheckError: text("last_check_error"), lastVerifiedAt: ts("last_verified_at"), downloadedAt: ts("downloaded_at"), + // Hub metadata (for search/filters), refreshed by the worker. Null until fetched. + /** e.g. ["Qwen/Qwen3-8B"] (cardData.base_model, or base_model:* tags). */ + baseModels: text("base_models", { mode: "json" }).$type(), + /** e.g. "qwen3" (gguf.architecture or config.model_type). */ + architecture: text("architecture"), + pipelineTag: text("pipeline_tag"), + license: text("license"), + /** Hub tags, minus noise like arxiv:/region:/deploy:. */ + hubTags: text("hub_tags", { mode: "json" }).$type(), + metadataFetchedAt: ts("metadata_fetched_at"), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)], ); +// --------------------------------------------------------------------------- +// User tags (e.g. "roleplay", "security") +// --------------------------------------------------------------------------- + +export const tags = sqliteTable( + "tags", + { + id: id(), + /** Display name as entered. */ + name: text("name").notNull(), + /** Lowercased, trimmed name; unique. */ + slug: text("slug").notNull(), + createdAt: createdAt(), + }, + (t) => [uniqueIndex("tags_slug_uq").on(t.slug)], +); + +export const modelTags = sqliteTable( + "model_tags", + { + modelId: text("model_id") + .notNull() + .references(() => models.id), + tagId: text("tag_id") + .notNull() + .references(() => tags.id), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.modelId, t.tagId] }), index("model_tags_tag_idx").on(t.tagId)], +); + /** History of SHAs a model has been pinned to. */ export const modelRevisions = sqliteTable( "model_revisions", diff --git a/src/lib/hub/client.ts b/src/lib/hub/client.ts index 1b08999..687f4ea 100644 --- a/src/lib/hub/client.ts +++ b/src/lib/hub/client.ts @@ -2,6 +2,7 @@ // Server-side only: it reads HF_TOKEN from the environment. Never import from client components. import { coreEnv } from "@/lib/env"; +import { parseRepoMetadata, type RepoMetadata } from "./metadata"; const HUB = "https://huggingface.co"; const TIMEOUT_MS = 20_000; @@ -48,6 +49,7 @@ export type RepoInfo = { gated: false | "auto" | "manual"; private: boolean; lastModified: string | null; + metadata: RepoMetadata; }; function headers(): HeadersInit { @@ -138,13 +140,14 @@ export async function getRepoInfo(repoId: string, revision: string): Promise[0]; return { repoId: j.id ?? repoId, sha: j.sha, gated: j.gated ?? false, private: j.private ?? false, lastModified: j.lastModified ?? null, + metadata: parseRepoMetadata(j), }; } diff --git a/src/lib/hub/metadata.ts b/src/lib/hub/metadata.ts new file mode 100644 index 0000000..5076cb2 --- /dev/null +++ b/src/lib/hub/metadata.ts @@ -0,0 +1,59 @@ +// Pure helpers that turn Hub model info into searchable metadata. Shared by web and worker. + +export type RepoMetadata = { + author: string | null; + baseModels: string[]; + architecture: string | null; + pipelineTag: string | null; + license: string | null; + hubTags: string[]; +}; + +type HubModelInfo = { + id?: string; + author?: string; + pipeline_tag?: string; + tags?: string[]; + cardData?: { base_model?: string | string[]; license?: string | string[] } | null; + gguf?: { architecture?: string } | null; + config?: { model_type?: string } | null; +}; + +/** Hub tags that carry no useful search signal (or are stored separately). */ +const NOISE_TAG = /^(arxiv|region|deploy|base_model|license|doi|dataset):|^(endpoints_compatible|autotrain_compatible|eval-results|text-generation-inference|conversational)$/; + +const asArray = (v: string | string[] | undefined | null): string[] => + v == null ? [] : (Array.isArray(v) ? v : [v]).filter((x): x is string => typeof x === "string" && x.length > 0); + +export function parseRepoMetadata(info: HubModelInfo): RepoMetadata { + const tags = info.tags ?? []; + + // Prefer the model card; fall back to "base_model::" / "base_model:" tags. + let baseModels = asArray(info.cardData?.base_model); + if (baseModels.length === 0) { + baseModels = tags + .filter((t) => t.startsWith("base_model:")) + .map((t) => t.split(":").at(-1)!) + .filter((id) => id.includes("/")); + } + + const license = asArray(info.cardData?.license)[0] ?? tags.find((t) => t.startsWith("license:"))?.slice(8) ?? null; + + return { + author: info.author ?? info.id?.split("/")[0] ?? null, + baseModels: [...new Set(baseModels)], + architecture: info.gguf?.architecture ?? info.config?.model_type ?? null, + pipelineTag: info.pipeline_tag ?? null, + license, + hubTags: [...new Set(tags.filter((t) => !NOISE_TAG.test(t)))], + }; +} + +/** + * The model "family" for filtering: the org of the base model(s) (unsloth/Qwen3-8B-GGUF → "Qwen"), + * or the repo's own org for original models without a base model. + */ +export function modelFamilies(repoId: string, baseModels: string[] | null | undefined): string[] { + const orgs = (baseModels ?? []).map((b) => b.split("/")[0]).filter(Boolean); + return orgs.length > 0 ? [...new Set(orgs)] : [repoId.split("/")[0]]; +} diff --git a/src/lib/hub/refresh.ts b/src/lib/hub/refresh.ts new file mode 100644 index 0000000..cc7e91f --- /dev/null +++ b/src/lib/hub/refresh.ts @@ -0,0 +1,39 @@ +import { eq, isNull } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { models } from "@/lib/db/schema"; +import { getRepoInfo } from "./client"; +import type { RepoMetadata } from "./metadata"; + +/** Columns to write on `models` for fetched Hub metadata. */ +export function metadataColumns(meta: RepoMetadata) { + return { + baseModels: meta.baseModels, + architecture: meta.architecture, + pipelineTag: meta.pipelineTag, + license: meta.license, + hubTags: meta.hubTags, + metadataFetchedAt: new Date(), + }; +} + +/** + * Fetch Hub metadata for models that don't have it yet (added before metadata existed). + * Returns how many were updated; failures are reported but don't stop the others. + */ +export async function backfillMetadata(onError: (repoId: string, err: unknown) => void): Promise { + const missing = await db() + .select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha }) + .from(models) + .where(isNull(models.metadataFetchedAt)); + let updated = 0; + for (const m of missing) { + try { + const info = await getRepoInfo(m.repoId, m.pinnedSha); + await db().update(models).set(metadataColumns(info.metadata)).where(eq(models.id, m.id)); + updated++; + } catch (err) { + onError(m.repoId, err); + } + } + return updated; +} diff --git a/src/lib/library.ts b/src/lib/library.ts index ef8d61d..70c9b0d 100644 --- a/src/lib/library.ts +++ b/src/lib/library.ts @@ -1,12 +1,14 @@ import "server-only"; import { and, asc, desc, eq, sql } from "drizzle-orm"; import { db } from "@/lib/db/client"; -import { modelFiles, models } from "@/lib/db/schema"; +import { modelFiles, models, modelTags, tags } from "@/lib/db/schema"; +import { modelFamilies } from "@/lib/hub/metadata"; import { quantGroup } from "@/lib/selection"; +import type { Tag } from "@/lib/tags"; export type LibraryRow = Awaited>[number]; -/** Models with their selected-file totals and a short "which quant" label. */ +/** Models with selected-file totals, quant labels, Hub metadata and user tags. */ export async function listLibrary() { const d = db(); const rows = await d @@ -19,6 +21,11 @@ export async function listLibrary() { status: models.status, createdAt: models.createdAt, downloadedAt: models.downloadedAt, + baseModels: models.baseModels, + architecture: models.architecture, + pipelineTag: models.pipelineTag, + license: models.license, + hubTags: models.hubTags, fileCount: sql`count(${modelFiles.id})`, totalBytes: sql`coalesce(sum(${modelFiles.size}), 0)`, }) @@ -31,17 +38,24 @@ export async function listLibrary() { .select({ modelId: modelFiles.modelId, path: modelFiles.path }) .from(modelFiles) .where(eq(modelFiles.selected, true)); - const quants = new Map>(); - for (const f of selected) { - const g = quantGroup(f.path); - if (!g) continue; - if (!quants.has(f.modelId)) quants.set(f.modelId, new Set()); - quants.get(f.modelId)!.add(g); - } + const quants = groupBy(selected, (f) => f.modelId, (f) => quantGroup(f.path)); + + const tagRows = await d + .select({ modelId: modelTags.modelId, id: tags.id, name: tags.name }) + .from(modelTags) + .innerJoin(tags, eq(tags.id, modelTags.tagId)) + .orderBy(asc(tags.slug)); + const tagsByModel = new Map(); + for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name }]); return rows.map((r) => ({ ...r, + author: r.repoId.split("/")[0], + families: modelFamilies(r.repoId, r.baseModels), + baseModels: r.baseModels ?? [], + hubTags: r.hubTags ?? [], quants: [...(quants.get(r.id) ?? [])].sort(), + tags: tagsByModel.get(r.id) ?? [], })); } @@ -56,3 +70,15 @@ export async function getModel(id: string) { .orderBy(asc(modelFiles.path)); return { model, files }; } + +function groupBy(items: T[], key: (t: T) => string, value: (t: T) => string | null) { + const out = new Map>(); + for (const item of items) { + const v = value(item); + if (v == null) continue; + const k = key(item); + if (!out.has(k)) out.set(k, new Set()); + out.get(k)!.add(v); + } + return out; +} diff --git a/src/lib/models.ts b/src/lib/models.ts index 52b78fd..789e1b0 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -2,9 +2,11 @@ import "server-only"; import { and, eq, sql } from "drizzle-orm"; import { ulid } from "ulid"; import { db } from "@/lib/db/client"; -import { jobs, modelFiles, modelRevisions, models } from "@/lib/db/schema"; +import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema"; import { checkFileAccess, getRepoInfo, listFiles } from "@/lib/hub/client"; +import { metadataColumns } from "@/lib/hub/refresh"; import { isSelected, type SelectionRule } from "@/lib/selection"; +import { deleteUnusedTags } from "@/lib/tags"; export class ModelError extends Error { constructor( @@ -67,6 +69,7 @@ export async function addModel(input: { localPath: repoId, includePatterns: input.rule.include, excludePatterns: input.rule.exclude, + ...metadataColumns(info.metadata), }), d.insert(modelRevisions).values({ modelId, sha: info.sha }), ...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)), @@ -91,10 +94,12 @@ export async function removeModel(id: string): Promise { ); } await d.batch([ + d.delete(modelTags).where(eq(modelTags.modelId, id)), d.delete(modelFiles).where(eq(modelFiles.modelId, id)), d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)), d.delete(models).where(eq(models.id, id)), ]); + await deleteUnusedTags(); } function chunk(items: T[], size: number): T[][] { diff --git a/src/lib/search.test.ts b/src/lib/search.test.ts new file mode 100644 index 0000000..a851683 --- /dev/null +++ b/src/lib/search.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { modelFamilies, parseRepoMetadata } from "./hub/metadata"; +import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search"; + +describe("parseRepoMetadata (real Hub responses, trimmed)", () => { + it("unsloth GGUF quant of Qwen", () => { + const m = parseRepoMetadata({ + id: "unsloth/Qwen3-8B-GGUF", + author: "unsloth", + pipeline_tag: "text-generation", + tags: ["transformers", "gguf", "qwen3", "qwen", "unsloth", "base_model:Qwen/Qwen3-8B", "base_model:quantized:Qwen/Qwen3-8B", "license:apache-2.0", "endpoints_compatible", "conversational", "arxiv:2309.00071"], + cardData: { base_model: "Qwen/Qwen3-8B", license: "apache-2.0" }, + gguf: { architecture: "qwen3" }, + }); + assert.deepEqual(m.baseModels, ["Qwen/Qwen3-8B"]); + assert.equal(m.architecture, "qwen3"); + assert.equal(m.license, "apache-2.0"); + assert.deepEqual(m.hubTags, ["transformers", "gguf", "qwen3", "qwen", "unsloth"]); + assert.deepEqual(modelFamilies("unsloth/Qwen3-8B-GGUF", m.baseModels), ["Qwen"]); + }); + + it("finetune with base_model as array and config.model_type", () => { + const m = parseRepoMetadata({ + id: "TheDrummer/Cydonia-24B-v4.1", + author: "TheDrummer", + tags: ["safetensors", "mistral"], + cardData: { base_model: ["mistralai/Mistral-Small-3.2-24B-Instruct-2507"] }, + config: { model_type: "mistral" }, + }); + assert.deepEqual(m.baseModels, ["mistralai/Mistral-Small-3.2-24B-Instruct-2507"]); + assert.equal(m.architecture, "mistral"); + assert.deepEqual(modelFamilies("TheDrummer/Cydonia-24B-v4.1", m.baseModels), ["mistralai"]); + }); + + it("falls back to base_model tags; original models are their own family", () => { + const m = parseRepoMetadata({ id: "x/y", tags: ["base_model:finetune:Qwen/Qwen3-8B-Base"] }); + assert.deepEqual(m.baseModels, ["Qwen/Qwen3-8B-Base"]); + assert.equal(m.author, "x"); + assert.deepEqual(modelFamilies("Qwen/Qwen3-8B", []), ["Qwen"]); + }); +}); + +const model = (over: Partial): SearchableModel => ({ + repoId: "unsloth/Qwen3-8B-GGUF", + author: "unsloth", + families: ["Qwen"], + baseModels: ["Qwen/Qwen3-8B"], + architecture: "qwen3", + quants: ["Q4_K_M"], + tags: ["roleplay"], + hubTags: ["gguf"], + pipelineTag: "text-generation", + license: "apache-2.0", + status: "ready", + ...over, +}); + +describe("matchesQuery", () => { + it("matches author, family, quant and tags case-insensitively, all terms required", () => { + const m = model({}); + assert.ok(matchesQuery(m, "qwen")); + assert.ok(matchesQuery(m, "unsloth qwen")); + assert.ok(matchesQuery(m, "q4_k_m")); + assert.ok(matchesQuery(m, "ROLEPLAY")); + assert.ok(matchesQuery(m, " ")); + assert.ok(!matchesQuery(m, "unsloth gemma")); + }); +}); + +describe("filters and facet counts", () => { + const models = [ + model({}), + model({ repoId: "bartowski/Qwen_Qwen3-8B-GGUF", author: "bartowski", quants: ["Q6_K"], tags: [] }), + model({ repoId: "unsloth/gemma-3-27b-it-GGUF", families: ["google"], quants: ["Q4_K_M"], tags: ["security"] }), + ]; + + it("ORs within a facet and ANDs across facets", () => { + const f = { ...EMPTY_FILTERS, author: ["unsloth"], quant: ["Q4_K_M", "Q6_K"] }; + assert.deepEqual( + models.filter((m) => matchesFilters(m, f)).map((m) => m.repoId), + ["unsloth/Qwen3-8B-GGUF", "unsloth/gemma-3-27b-it-GGUF"], + ); + }); + + it("counts a facet without applying its own selection", () => { + const f = { ...EMPTY_FILTERS, author: ["unsloth"] }; + assert.deepEqual(facetCounts(models, "author", "", f), [["unsloth", 2], ["bartowski", 1]]); + assert.deepEqual(facetCounts(models, "family", "", f), [["google", 1], ["Qwen", 1]]); + }); +}); diff --git a/src/lib/search.ts b/src/lib/search.ts new file mode 100644 index 0000000..61b06b1 --- /dev/null +++ b/src/lib/search.ts @@ -0,0 +1,88 @@ +// Library search and facet filtering (runs in the browser; the library is small). + +export type SearchableModel = { + repoId: string; + author: string; + families: string[]; + baseModels: string[]; + architecture: string | null; + quants: string[]; + tags: string[]; + hubTags: string[]; + pipelineTag: string | null; + license: string | null; + status: string; +}; + +export const FACETS = ["author", "family", "quant", "tag", "status"] as const; +export type Facet = (typeof FACETS)[number]; +export type Filters = Record; + +export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] }; + +export function facetValues(m: SearchableModel, facet: Facet): string[] { + switch (facet) { + case "author": + return [m.author]; + case "family": + return m.families; + case "quant": + return m.quants; + case "tag": + return m.tags; + case "status": + return [m.status]; + } +} + +function haystack(m: SearchableModel): string { + return [ + m.repoId, + m.author, + ...m.families, + ...m.baseModels, + m.architecture, + ...m.quants, + ...m.tags, + ...m.hubTags, + m.pipelineTag, + m.license, + m.status, + ] + .filter(Boolean) + .join(" ") + .toLowerCase(); +} + +/** Every whitespace-separated term must appear somewhere (case-insensitive substring). */ +export function matchesQuery(m: SearchableModel, query: string): boolean { + const terms = query.toLowerCase().split(/\s+/).filter(Boolean); + if (terms.length === 0) return true; + const text = haystack(m); + return terms.every((t) => text.includes(t)); +} + +/** OR within a facet, AND across facets. Values compare case-insensitively. */ +export function matchesFilters(m: SearchableModel, filters: Filters, except?: Facet): boolean { + return FACETS.every((facet) => { + const wanted = filters[facet]; + if (facet === except || wanted.length === 0) return true; + const have = facetValues(m, facet).map((v) => v.toLowerCase()); + return wanted.some((w) => have.includes(w.toLowerCase())); + }); +} + +/** + * Value counts for one facet, computed over the models that match the query and all *other* + * facets, so picking e.g. an author narrows the quant counts but not the author list itself. + */ +export function facetCounts(models: SearchableModel[], facet: Facet, query: string, filters: Filters) { + const counts = new Map(); + for (const m of models) { + if (!matchesQuery(m, query) || !matchesFilters(m, filters, facet)) continue; + for (const v of new Set(facetValues(m, facet))) counts.set(v, (counts.get(v) ?? 0) + 1); + } + // Keep selected values visible even if their count dropped to 0. + for (const v of filters[facet]) if (!counts.has(v)) counts.set(v, 0); + return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true })); +} diff --git a/src/lib/tags.ts b/src/lib/tags.ts new file mode 100644 index 0000000..9eadade --- /dev/null +++ b/src/lib/tags.ts @@ -0,0 +1,71 @@ +import "server-only"; +import { and, asc, eq, sql } from "drizzle-orm"; +import { ulid } from "ulid"; +import { db } from "@/lib/db/client"; +import { modelTags, models, tags } from "@/lib/db/schema"; + +export const TAG_MAX_LENGTH = 40; + +export class TagError extends Error { + constructor( + public code: "invalid" | "not_found", + message: string, + public status: number, + ) { + super(message); + } +} + +export type Tag = { id: string; name: string }; + +/** Trim and collapse whitespace; the slug (lowercase) decides uniqueness. */ +export function normalizeTagName(raw: string): { name: string; slug: string } { + const name = raw.trim().replace(/\s+/g, " "); + if (!name) throw new TagError("invalid", "Tag name is empty.", 400); + if (name.length > TAG_MAX_LENGTH) throw new TagError("invalid", `Tag names are at most ${TAG_MAX_LENGTH} characters.`, 400); + return { name, slug: name.toLowerCase() }; +} + +/** All tags with how many models use them (for autocomplete). */ +export async function listTags(): Promise<(Tag & { count: number })[]> { + return db() + .select({ id: tags.id, name: tags.name, count: sql`count(${modelTags.modelId})` }) + .from(tags) + .leftJoin(modelTags, eq(modelTags.tagId, tags.id)) + .groupBy(tags.id) + .orderBy(asc(tags.slug)); +} + +export async function modelTagList(modelId: string): Promise { + return db() + .select({ id: tags.id, name: tags.name }) + .from(modelTags) + .innerJoin(tags, eq(tags.id, modelTags.tagId)) + .where(eq(modelTags.modelId, modelId)) + .orderBy(asc(tags.slug)); +} + +/** Attach a tag (created on first use; matched case-insensitively) to a model. */ +export async function addTag(modelId: string, rawName: string): Promise { + const { name, slug } = normalizeTagName(rawName); + const d = db(); + const model = await d.query.models.findFirst({ columns: { id: true }, where: eq(models.id, modelId) }); + if (!model) throw new TagError("not_found", "Model not found.", 404); + + await d.insert(tags).values({ id: ulid(), name, slug }).onConflictDoNothing({ target: tags.slug }); + const tag = await d.query.tags.findFirst({ columns: { id: true, name: true }, where: eq(tags.slug, slug) }); + if (!tag) throw new Error("tag vanished after insert"); + await d.insert(modelTags).values({ modelId, tagId: tag.id }).onConflictDoNothing(); + return tag; +} + +/** Detach a tag; tags no model uses anymore are deleted. */ +export async function removeTag(modelId: string, tagId: string): Promise { + const d = db(); + await d.delete(modelTags).where(and(eq(modelTags.modelId, modelId), eq(modelTags.tagId, tagId))); + await deleteUnusedTags(); +} + +export async function deleteUnusedTags(): Promise { + await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`); +} diff --git a/src/worker/index.ts b/src/worker/index.ts index dc32dd4..1432af2 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -9,6 +9,7 @@ import { db } from "@/lib/db/client"; import { runMigrations } from "@/lib/db/migrate"; import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema"; import { coreEnv } from "@/lib/env"; +import { backfillMetadata } from "@/lib/hub/refresh"; import { DownloadRunner } from "./download"; import { log } from "./log"; import { settleModelStatus } from "./model-status"; @@ -269,6 +270,11 @@ async function main() { if (hfVersion) log.info(`hf CLI: ${hfVersion}, xet ${env.HF_HUB_DISABLE_XET ? "disabled" : "enabled"}`); else log.warn("hf CLI not found on PATH; downloads will fail until it is installed"); + // Models added before Hub metadata was stored (search/filters need it). + backfillMetadata((repoId, err) => log.warn(`metadata for ${repoId} failed: ${err instanceof Error ? err.message : err}`)) + .then((n) => n > 0 && log.info(`fetched Hub metadata for ${n} model(s)`)) + .catch((err) => log.error("metadata backfill failed", err)); + await heartbeat(); timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS)); timers.push(setInterval(() => void tick(), TICK_MS));