Release 0.4.0: Kaname, search, filters and tags
Release / release (push) Successful in 11m41s

- Rename the app to Kaname
- Hub metadata per model (base models, architecture, license, Hub tags),
  backfilled by the worker for existing models
- Library search across repo/author/family/quant/tags and multi-select
  facet filters (author, family, quant, tag, status) kept in the URL
- Custom tags (model page editor, on add, click-to-filter)
- README rewritten around a quick install, with banner and screenshots
- deploy/compose.yaml: models in a host folder (KANAME_MODELS_DIR)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 19:49:17 +02:00
1 parent 2167ea0950
commit 67191b3e16
37 files changed
+2028 -206

No files matched your search

+38 -26
View File
@@ -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
# <AUTH_URL>/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>/<org>/<repo>
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 <AUTH_URL>/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
+27
View File
@@ -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.
+116 -65
View File
@@ -1,94 +1,145 @@
# Model Manager
<p align="center">
<img src="docs/banner.png" alt="Kaname: self-hosted model manager for Hugging Face" width="100%" />
</p>
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
`<AUTH_URL>/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: `<AUTH_URL>/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 `<models folder>/<org>/<repo>/`, e.g. `models/unsloth/Qwen3-8B-GGUF/`.
## Using it
<p align="center">
<img src="docs/screenshots/add-model.png" alt="Adding a model: quant quick-select" width="100%" />
</p>
- **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 <sha> --include <files>`, 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 `<dir>/.cache/huggingface/download/` as
`<hash>.<etag>.<random>.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).
+5 -17
View File
@@ -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}"
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 705 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

+24
View File
@@ -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;
+894
View File
@@ -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": {}
}
}
+7
View File
@@ -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
}
]
}
+2 -2
View File
@@ -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",
+1 -1
View File
@@ -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\"",
+29 -1
View File
@@ -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<string[]>([]);
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.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="tags">Tags</Label>
<Input
id="tags"
value={tagsText}
onChange={(e) => setTagsText(e.target.value)}
placeholder="roleplay, security"
list="known-tags"
/>
<datalist id="known-tags">
{knownTags.map((t) => (
<option key={t} value={t} />
))}
</datalist>
<p className="text-xs text-muted-foreground">Optional, comma-separated. Editable later on the model page.</p>
</div>
</CardContent>
</Card>
+51
View File
@@ -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 (
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant={active ? "secondary" : "outline"} size="sm" disabled={values.length === 0} />}
>
{label}
{active && <span className="rounded bg-background/60 px-1 text-xs tabular-nums">{selected.length}</span>}
<ChevronDownIcon className="opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-auto min-w-48">
{values.map(([value, count]) => (
<DropdownMenuCheckboxItem
key={value}
checked={selected.includes(value)}
closeOnClick={false}
onCheckedChange={(on) => onChange(on ? [...selected, value] : selected.filter((v) => v !== value))}
>
<span className="flex-1">{format(value)}</span>
<span className="ml-4 text-xs text-muted-foreground tabular-nums">{count}</span>
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
+1 -1
View File
@@ -16,7 +16,7 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<header className="border-b">
<div className="mx-auto flex h-14 max-w-6xl items-center gap-6 px-4">
<Link href="/" className="flex items-baseline gap-1.5 font-semibold">
Model Manager
Kaname
<span className="text-xs font-normal text-muted-foreground">{process.env.APP_VERSION ?? "dev"}</span>
</Link>
<nav className="flex items-center gap-4 text-sm text-muted-foreground">
-75
View File
@@ -1,75 +0,0 @@
"use client";
import Link from "next/link";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import { formatBytes, shortSha } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
const OPEN = ["queued", "downloading", "verifying"];
export function LibraryTable({ rows }: { rows: LibraryRow[] }) {
const { snapshot } = useLive();
const openJobs = new Map<string, JobSnapshot>();
for (const j of snapshot?.jobs ?? []) {
if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j);
}
return (
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Repository</TableHead>
<TableHead>Selection</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((r) => {
const job = openJobs.get(r.id);
return (
<TableRow key={r.id}>
<TableCell className="font-medium">
<Link href={`/models/${r.id}`} className="hover:underline">
{r.repoId}
</Link>
</TableCell>
<TableCell className="text-sm">
{r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} files`}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell>
<code className="font-mono text-xs" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
</TableCell>
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
<LocalTime value={r.downloadedAt} />
</TableCell>
<TableCell>
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<ModelStatusBadge status={r.status} />
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
);
}
+229
View File
@@ -0,0 +1,229 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import {
EMPTY_FILTERS,
type Facet,
FACETS,
facetCounts,
type Filters,
matchesFilters,
matchesQuery,
type SearchableModel,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
const OPEN = ["queued", "downloading", "verifying"];
const FACET_LABEL: Record<Facet, string> = {
author: "Author",
family: "Family",
quant: "Quant",
tag: "Tag",
status: "Status",
};
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
function toSearchable(r: LibraryRow): SearchableModel {
return {
repoId: r.repoId,
author: r.author,
families: r.families,
baseModels: r.baseModels,
architecture: r.architecture,
quants: r.quants,
tags: r.tags.map((t) => t.name),
hubTags: r.hubTags,
pipelineTag: r.pipelineTag,
license: r.license,
status: r.status,
};
}
/** Search + facet filters (kept in the URL) over the library table. */
export function LibraryView({ rows }: { rows: LibraryRow[] }) {
const router = useRouter();
const pathname = usePathname();
const params = useSearchParams();
const [query, setQuery] = useState(() => params.get("q") ?? "");
const [filters, setFilters] = useState<Filters>(() => {
const f = { ...EMPTY_FILTERS };
for (const facet of FACETS) f[facet] = params.getAll(facet);
return f;
});
function sync(nextQuery: string, nextFilters: Filters) {
const p = new URLSearchParams();
if (nextQuery) p.set("q", nextQuery);
for (const facet of FACETS) for (const v of nextFilters[facet]) p.append(facet, v);
const qs = p.toString();
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
}
const updateQuery = (q: string) => {
setQuery(q);
sync(q, filters);
};
const updateFilter = (facet: Facet, values: string[]) => {
const next = { ...filters, [facet]: values };
setFilters(next);
sync(query, next);
};
const clearAll = () => {
setQuery("");
setFilters(EMPTY_FILTERS);
sync("", EMPTY_FILTERS);
};
const searchable = useMemo(() => rows.map(toSearchable), [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);
const { snapshot } = useLive();
const openJobs = new Map<string, JobSnapshot>();
for (const j of snapshot?.jobs ?? []) {
if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j);
}
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<div className="relative min-w-56 flex-1">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(e) => updateQuery(e.target.value)}
placeholder="Search repo, author, family, quant, tag…"
className="pl-8"
aria-label="Search models"
/>
</div>
{FACETS.map((facet) => (
<FacetFilter
key={facet}
label={FACET_LABEL[facet]}
values={facetCounts(searchable, facet, query, filters)}
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
/>
))}
</div>
{anyActive && (
<div className="flex flex-wrap items-center gap-1.5 text-sm">
<span className="text-muted-foreground">
{visible.length} of {rows.length} models
</span>
{FACETS.flatMap((facet) =>
filters[facet].map((v) => (
<Badge key={`${facet}:${v}`} variant="secondary" className="gap-1">
{FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v}
<button
type="button"
aria-label={`Remove filter ${v}`}
onClick={() => updateFilter(facet, filters[facet].filter((x) => x !== v))}
>
<XIcon className="size-3" />
</button>
</Badge>
)),
)}
<Button variant="ghost" size="xs" onClick={clearAll}>
Clear all
</Button>
</div>
)}
{visible.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>No matching models</CardTitle>
<CardDescription>Try a different search or remove a filter.</CardDescription>
</CardHeader>
</Card>
) : (
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Model</TableHead>
<TableHead>Selection</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{visible.map((r) => {
const job = openJobs.get(r.id);
const base = r.baseModels[0];
return (
<TableRow key={r.id}>
<TableCell className="whitespace-normal">
<Link href={`/models/${r.id}`} className="font-medium hover:underline">
{r.repoId}
</Link>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.tags.map((t) => (
<button
key={t.id}
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<Badge variant="outline">{t.name}</Badge>
</button>
))}
</div>
</TableCell>
<TableCell className="text-sm">
{r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} file${r.fileCount === 1 ? "" : "s"}`}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell className="hidden lg:table-cell">
<code className="font-mono text-xs" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
</TableCell>
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
<LocalTime value={r.downloadedAt} />
</TableCell>
<TableCell>
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<ModelStatusBadge status={r.status} />
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
)}
</div>
);
}
+29
View File
@@ -4,9 +4,12 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { modelFamilies } from "@/lib/hub/metadata";
import { getModel } from "@/lib/library";
import { modelTagList } from "@/lib/tags";
import { ModelLive } from "./model-live";
import { RemoveModelButton } from "./remove-model-button";
import { TagEditor } from "./tag-editor";
export const dynamic = "force-dynamic";
@@ -15,6 +18,7 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
const data = await getModel(id);
if (!data) notFound();
const { model, files } = data;
const modelTags = await modelTagList(model.id);
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
@@ -25,6 +29,7 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
<ModelStatusBadge status={model.status} />
<div className="ml-auto">{model.status === "pending" && <RemoveModelButton id={model.id} />}</div>
</div>
<TagEditor modelId={model.id} tags={modelTags} />
<Card>
<CardHeader>
@@ -43,6 +48,30 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
huggingface.co/{model.repoId}
</a>
</dd>
<dt className="text-muted-foreground">Author</dt>
<dd>{model.repoId.split("/")[0]}</dd>
<dt className="text-muted-foreground">Family</dt>
<dd>{modelFamilies(model.repoId, model.baseModels).join(", ")}</dd>
<dt className="text-muted-foreground">Base model</dt>
<dd className="flex flex-col">
{(model.baseModels ?? []).length === 0
? "–"
: model.baseModels!.map((b) => (
<a key={b} href={`https://huggingface.co/${b}`} target="_blank" rel="noreferrer" className="underline">
{b}
</a>
))}
</dd>
<dt className="text-muted-foreground">Architecture</dt>
<dd>{model.architecture ?? "–"}</dd>
<dt className="text-muted-foreground">License</dt>
<dd>{model.license ?? "–"}</dd>
{(model.hubTags ?? []).length > 0 && (
<>
<dt className="text-muted-foreground">Hub tags</dt>
<dd className="text-xs text-muted-foreground">{model.hubTags!.join(", ")}</dd>
</>
)}
<dt className="text-muted-foreground">Tracked revision</dt>
<dd className="font-mono">{model.trackedRevision}</dd>
<dt className="text-muted-foreground">Pinned SHA</dt>
+87
View File
@@ -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<string[]>([]);
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 (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<Badge key={t.id} variant="secondary" className="gap-1">
{t.name}
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)}>
<XIcon className="size-3" />
</button>
</Badge>
))}
<form
onSubmit={(e) => {
e.preventDefault();
void add(value);
}}
>
<Input
value={value}
onChange={(e) => setValue(e.target.value)}
list={listId}
placeholder="Add tag…"
disabled={busy}
maxLength={40}
className="h-6 w-36 text-xs"
aria-label="Add tag"
/>
<datalist id={listId}>
{suggestions
.filter((s) => !current.has(s.toLowerCase()))
.map((s) => (
<option key={s} value={s} />
))}
</datalist>
</form>
</div>
);
}
+2 -2
View File
@@ -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() {
<div className="flex flex-col gap-4">
{/* Opens by default while the library is empty. */}
<AddModelPanel freeBytes={worker.online ? worker.modelsDirFreeBytes : null} defaultOpen={rows.length === 0} />
{rows.length > 0 && <LibraryTable rows={rows} />}
{rows.length > 0 && <LibraryView rows={rows} />}
</div>
);
}
@@ -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<RouteContext<"/api/models/[id]/tags/[tagId]">>(async (_req, { params }) => {
const { id, tagId } = await params;
await removeTag(id, tagId);
return new NextResponse(null, { status: 204 });
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { 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<RouteContext<"/api/models/[id]/tags">>(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);
}
});
+5 -1
View File
@@ -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);
}
});
+8
View File
@@ -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()));
+1 -1
View File
@@ -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",
};
+1 -1
View File
@@ -28,7 +28,7 @@ export default async function LoginPage({ searchParams }: PageProps<"/login">) {
<main className="flex min-h-screen items-center justify-center p-4">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-lg">Model Manager</CardTitle>
<CardTitle className="text-lg">Kaname</CardTitle>
<CardDescription>Sign in to manage local models.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
+2 -2
View File
@@ -1,7 +1,7 @@
import { Badge } from "@/components/ui/badge";
import type { ModelStatus } from "@/lib/db/schema";
const LABELS: Record<ModelStatus, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
export const MODEL_STATUS: Record<ModelStatus, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
pending: { label: "not downloaded", variant: "outline" },
downloading: { label: "downloading", variant: "secondary" },
ready: { label: "ok", variant: "default" },
@@ -11,6 +11,6 @@ const LABELS: Record<ModelStatus, { label: string; variant: "default" | "seconda
};
export function ModelStatusBadge({ status }: { status: ModelStatus }) {
const { label, variant } = LABELS[status];
const { label, variant } = MODEL_STATUS[status];
return <Badge variant={variant}>{label}</Badge>;
}
+41
View File
@@ -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<string[]>(),
/** 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<string[]>(),
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",
+4 -1
View File
@@ -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<Rep
gated?: false | "auto" | "manual";
private?: boolean;
lastModified?: string;
};
} & Parameters<typeof parseRepoMetadata>[0];
return {
repoId: j.id ?? repoId,
sha: j.sha,
gated: j.gated ?? false,
private: j.private ?? false,
lastModified: j.lastModified ?? null,
metadata: parseRepoMetadata(j),
};
}
+59
View File
@@ -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:<relation>:<id>" / "base_model:<id>" 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]];
}
+39
View File
@@ -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<number> {
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;
}
+35 -9
View File
@@ -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<ReturnType<typeof listLibrary>>[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<number>`count(${modelFiles.id})`,
totalBytes: sql<number>`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<string, Set<string>>();
for (const f of selected) {
const g = quantGroup(f.path);
if (!g) continue;
if (!quants.has(f.modelId)) quants.set(f.modelId, new Set());
quants.get(f.modelId)!.add(g);
}
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<string, Tag[]>();
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<T>(items: T[], key: (t: T) => string, value: (t: T) => string | null) {
const out = new Map<string, Set<string>>();
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;
}
+6 -1
View File
@@ -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<void> {
);
}
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<T>(items: T[], size: number): T[][] {
+91
View File
@@ -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>): 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]]);
});
});
+88
View File
@@ -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<Facet, string[]>;
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<string, number>();
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 }));
}
+71
View File
@@ -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<number>`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<Tag[]> {
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<Tag> {
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<void> {
const d = db();
await d.delete(modelTags).where(and(eq(modelTags.modelId, modelId), eq(modelTags.tagId, tagId)));
await deleteUnusedTags();
}
export async function deleteUnusedTags(): Promise<void> {
await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`);
}
+6
View File
@@ -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));