Compare commits

...
34 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 4f05ee165c Release 0.14.2: steady download progress
Release / release (push) Successful in 6m29s
A progress sample that missed a partial file showed 0 B while hf kept
downloading. Walk the download cache tolerating vanished folders and
never let a file's progress go backwards within a run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:03:33 +02:00
Pascal LinxweilerandClaude Opus 5.5 22a54f731d Release 0.14.1: use Xet for files over 50 GB
Release / release (push) Successful in 3m27s
huggingface_hub 2.1.1 refuses files over MAX_HTTP_DOWNLOAD_SIZE (50 GB)
without Xet; Kaname disables Xet by default for steady progress, so such
downloads failed. A download that includes a file over the limit now
runs hf with Xet enabled and says so in the job log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:39:41 +02:00
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5 Release 0.14.0: quality eval
Release / release (push) Successful in 3m17s
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:36 +02:00
Pascal LinxweilerandClaude Opus 5.5 716bd8f2f0 Release 0.13.0: agent API for deployments and benchmarks
Release / release (push) Successful in 3m0s
Scopes deployments:read/write and benchmarks:read/run; /api/v1 endpoints
for runtimes, deployments (create with dry run, edit, start, stop, delete
own ones), benchmark runs, A/B, sweeps and comparisons; ?wait= on all
status endpoints. Guardrails: approval, agent deployments at once, one
GPU job at a time, time limits, sweep variants, runtime and argument
allowlists, host port range, memory/CPU caps, protected deployments with
a VRAM check. Requested-by filters, approval bars, per-token activity log,
scope editing, docs/agent/SKILL-tuning.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:11:06 +02:00
Pascal LinxweilerandClaude Opus 5.5 e007a35143 Release 0.12.0: Intel GPU support
Release / release (push) Successful in 3m40s
Intel/AMD GPU telemetry in benchmark runs (hwmon power/temperature,
amdgpu sysfs, Intel VRAM/utilization from DRM fdinfo via a minimal
host-PID probe container), temperature for all GPUs, VRAM estimate for
NVIDIA and Intel/AMD in the deployment form, /dev/dri group IDs added to
Intel/AMD runtime containers, Intel llama.cpp presets seeded on first
detection, ZES_ENABLE_SYSMAN=1 for the SYCL preset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:47:00 +02:00
Pascal LinxweilerandClaude Opus 5.5 ee6c623e2a Release 0.11.0: benchmark metadata and system info
Release / release (push) Successful in 3m25s
Every run records GPUs (PCIe link under load and maximum, ReBAR, P2P),
runtime image/tag/digest and the engine version the server reports,
model, quant, KV cache, context and concurrency, plus a whitelisted
system summary and a description. Shown on the run page, compare and
sweep views; passed to BetterBench as notes and to the launch80 preview
as sections. Settings -> Hardware for manual values.

Also: scripts/intel-probe.sh (read-only diagnostics for Intel hosts),
and --quick is no longer passed together with --passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 981c4170fc Agent skill: kaname helper script, declared env vars, less polling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:24:51 +02:00
Pascal LinxweilerandClaude Opus 5.5 93edb198d8 Release 0.10.0: API for agents
Release / release (push) Successful in 3m14s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:14:45 +02:00
Pascal LinxweilerandClaude Opus 5.5 7b1c8070b3 API for agents: tokens, /api/v1, guardrails, approval
- Scoped bearer tokens (models:read, downloads:create), stored as SHA-256, managed in
  Settings -> API tokens. Only /api/v1 accepts them; the rest stays OIDC-only.
- /api/v1: Hub lookup, library list with the search filters, download requests through the
  existing add-model/queue path (idempotent), compact job status, disk space.
- Guardrails: approval mode (default approve), max size per request, minimum free space incl.
  reserved bytes, max open agent jobs, author allowlist. Approve/reject in the UI; "requested by"
  shown and filterable.
- docs/api.md (incl. Traefik forward-auth bypass), docs/agent/SKILL.md, DB-backed API tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:14:45 +02:00
Pascal LinxweilerandClaude Opus 5.5 2532f2f2b3 Release 0.9.0: benchmarks
Release / release (push) Successful in 3m49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:29:30 +02:00
Pascal LinxweilerandClaude Opus 5.5 85af566b93 Downloads: speed limit in Settings
hf has no bandwidth option, so the worker pauses hf (SIGSTOP/SIGCONT) whenever it is ahead of a
token bucket over bytes on disk. The limit is shared by all running downloads and re-read every
5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:04:48 +02:00
Pascal LinxweilerandClaude Opus 5.5 b623b16a6d Benchmarks: paired A/B runs, sweeps, resource usage
- A/B with betterbench ab between two deployments of the same model, with verdict, confidence
  interval and caveats.
- Sweeps vary one or two deployment settings, deploy, benchmark and remove each variant, and
  compare them in one table.
- Every run records CPU, RAM, VRAM, GPU utilization and power.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:04:40 +02:00
Pascal LinxweilerandClaude Opus 5.5 9e167a44f6 Benchmarks with BetterBench, launch80-style reports and publishing, GPU support
- Benchmarks: BetterBench 0.6.1 (pinned by checksum) runs against a running
  deployment, one at a time; quick/full/custom passes, phase selection, live
  step and output, cancel, run again, compare runs side by side.
- Report page after launch80's bench.betterbench.v1: headline tiles,
  "Read these first" caveats (quick, sample gate, max_tokens truncation,
  batched streams, failures, skipped depths, prefix-cache hits), charts, full
  tables with daggered under-sampled cells, method text. All figures come from
  BetterBench's own report functions.
- Publish to launch80 as a double opt-in: L80 dry run builds the exact payload
  for inspection, an explicit confirmation publishes that file (L80 CLI 0.4.0
  pinned by checksum, L80_TOKEN worker-only). Endpoint and host never leave.
- GPUs: runtime accelerator (CPU, NVIDIA, /dev/dri, ROCm) with presets for the
  official CUDA/Vulkan/Intel/ROCm builds; NVIDIA GPUs probed via nvidia-smi in
  a short-lived container; per-deployment GPU picking, -ngl, split mode,
  tensor split, MoE offload, vLLM tensor parallel and GPU memory share.
- llama.cpp --cache-ram option (1 GiB for new deployments) and a memory
  estimate that counts it and the KV cache: the 8 GiB default made containers
  thrash at their memory limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:54:38 +02:00
Pascal LinxweilerandClaude Opus 5.5 f0b4adda63 Release 0.8.0: deployments
Release / release (push) Successful in 3m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:30:14 +02:00
Pascal LinxweilerandClaude Opus 5.5 ea1f18cc74 Deployments: API keys, deploy from the library, reorganized form
- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:28:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 66e6a8c4f7 Deployments: llama.cpp web UI toggle, clearer start failures, log fixes
- Web UI option for llama.cpp deployments (--no-webui when off); the deployment
  page links to it on the published host port.
- Follow container logs after the start with tail=all: following a created
  container returned an already-closed stream, so startup output was lost.
- Failed starts name the cause from the log (vLLM ValueError, llama.cpp error
  lines) before the last output.
- A deployment's vLLM dtype replaces the runtime's --dtype instead of repeating it.
- vLLM memory estimate: 3 GiB overhead (measured ~6.9 GiB for SmolLM2-135M
  with a 4 GiB KV cache).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:01:52 +02:00
Pascal LinxweilerandClaude Opus 5.5 8b74fa69db Deployments: serve a model with a runtime container
- deployments + deployment_logs tables; desired/actual state reconciled by
  the worker (create/start/stop/remove via the socket proxy, /health wait,
  log follower, stats, memory guard, adopt/remove containers on restart).
- Pure command builder for llama-server and vllm serve (mmproj, MTP draft,
  KV cache types, dtype, KV cache size) with tests; file candidates per
  engine with tests.
- New main menu entry Deployments: list, new/edit form (runtime -> model
  and files -> launch options, live command preview), detail page with
  stats, log, endpoint and a streaming chat smoke test.

Not yet tested end-to-end against real containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:31:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 4f7ae1fc8c Fix image pull progress never being written
`void query` doesn't execute a Drizzle query (it runs on then/await), so
pull progress stayed at "Starting" until the pull finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:39:15 +02:00
Pascal LinxweilerandClaude Opus 5.5 a756eb3794 Release workflow: drop setup-node's npm cache
The act_runner cache server isn't reachable from job containers
(getCacheEntry ETIMEDOUT), so restoring and saving the cache timed out
for ~4.5 min each, ~9 of the ~12 minutes per release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:30:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 930126c5eb Release 0.7.0: runtimes and Docker connection
Release / release (push) Successful in 11m56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:27:18 +02:00
Pascal LinxweilerandClaude Opus 5.5 b68b4a2b23 Runtimes: Docker connection via socket proxy, runtime images, host info
- docker-proxy service (tecnativa/docker-socket-proxy) in both compose
  files; worker uses it via DOCKER_HOST with a dependency-free client.
- runtimes table with presets (llama.cpp CPU, vLLM CPU) and custom
  images; validation of image refs, env, args, devices (/dev/dri, /dev/kfd).
- Worker reports Docker/CPU/memory facts and detects its network and
  models mount; pulls images with progress; image state per runtime.
- Settings -> Runtimes page with host card, list, editor, pull/update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:24:59 +02:00
Pascal LinxweilerandClaude Opus 5.5 76683ffd7b Release 0.6.0: delete, verify/repair, update checks
Release / release (push) Successful in 11m55s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:02:22 +02:00
Pascal LinxweilerandClaude Opus 5.5 7864a492c9 Delete, verify/deep verify, repair and update checks
- Delete any model (incl. failed ones); the worker removes the repo's
  files (keeps foreign files and empty-folder cleanup), then the rows.
- Verify (existence, size, hf metadata) and deep verify (SHA-256 /
  git blob SHA-1 against the Hub) with missing/mismatch/extra report.
- Repair = download of the selection; broken files are deleted first
  because hf skips files whose metadata matches without checking them.
- Hub check resolves the tracked revision and stores which selected
  files a newer commit changes/adds/removes; Update pins it (old commit
  kept in model_revisions), downloads, then removes dropped files.
- Worker runs verify/delete jobs next to downloads (2 local slots).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:00:55 +02:00
Pascal LinxweilerandClaude Opus 5.5 c2c239bf16 Release 0.5.0: model pages, file labels, recommended files, import, Hub checks
Release / release (push) Successful in 11m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 00:12:41 +02:00
Pascal LinxweilerandClaude Opus 5.5 0247f257fb Recommended files with a quant; floating selection bar
Picking model weights in Add model or Download more also selects the
files that usually go with them (chat template, MTP head, mmproj, ...),
shown in a strip where each can be unchecked. Variants are matched by
quant, otherwise the best single one; kinds already selected aren't
added twice. Which kinds is set in Settings -> Downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:10:53 +02:00
Pascal LinxweilerandClaude Opus 5.5 145818f149 Import models that are already in the models folder
The worker scans MODELS_DIR (startup, every 2 min, on "Rescan") for
<org>/<name> folders that no model uses and stores them in local_folders.
The library lists them; Import opens Add model prefilled with the folder,
the commit hf recorded and the files on disk preselected. The import job
runs hf download into the existing folder: hf 2.1.1 hashes files it didn't
download itself, keeps matching ones and re-downloads the rest (verified
in Docker, including a corrupted file being replaced).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:01:58 +02:00
Pascal LinxweilerandClaude Opus 5.5 3603742637 Flag models deleted from the Hub; tag picker, tags in settings, account menu
- Worker checks each model's repo and pinned commit on the Hub every
  UPDATE_CHECK_INTERVAL_HOURS and after failed downloads; missing repos or
  commits are flagged (badge, banner, Status filter) and block new
  downloads. Local files are never touched. "Check now" on the model page.
- Tag picker dropdown ("Create new tag…" first, then existing tags) on the
  model page and in Add model.
- Settings: separate File labels and Tags pages; create tags there. Unused
  tags are no longer deleted automatically.
- Header: app icon, nav with active state, account menu with the OIDC
  profile picture, theme switch and sign out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 22:53:57 +02:00
Pascal LinxweilerandClaude Opus 5.5 df18415e02 Download more, file labels, split-file grouping, settings for labels and tags
- Files tab: "Download more" adds files to a model's selection and queues them
- Colored file labels (Model, MTP, Vision/mmproj, imatrix, Config, …)
- Split GGUF/safetensors parts shown and selected as one entry everywhere
- Settings page with a Labels section: file label names/colors, tag
  rename/recolor/delete; new settings table and tags.color
- Quants only count model weights

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:42:03 +02:00
Pascal LinxweilerandClaude Opus 5.5 5211ec9064 Fix hydration mismatch in progress bars on non-English browsers
Base UI formats aria-valuetext with the runtime locale (server: "50%", German browser: "50 %"). Pin the Progress wrapper to en-US.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:26:56 +02:00
Pascal LinxweilerandClaude Opus 5.5 6dc9527682 Model page: Files tab first with a new file list, colored tags, single Hub link
- Files is the default tab: icon/size/LFS/state per file, on-disk summary, unselected files collapsed
- Custom tags color-coded by name (editor, library, filter chips and menu)
- Header: only the Hugging Face link (top right); README link moved to the end of the model card
- App icon; proxy lets /icon.svg through

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:24:23 +02:00
Pascal LinxweilerandClaude Opus 5.5 5fadd64367 Model page: header, content and sidebar as consistent cards
Tabs become a segmented control in the content card header; drop the full-bleed header band and the page-wide tab line; files tab without nested boxes; download card heading matches the other sidebar cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:16:00 +02:00
Pascal LinxweilerandClaude Opus 5.5 1527fcd830 Hugging Face style model pages at /<org>/<name>
- Model URLs are the repo path (case-insensitive, canonical redirect);
  /models/<id> redirects
- Header with avatar, org/name + copy, task/format/arch/language/license
  pills, user tags, cross-links to the Hub (files @ sha, commits, community,
  base model) and tabs: rendered model card at the pinned commit, files, jobs
- Sidebar: download card, local copy, model tree with related local models
- Metadata gains author avatar and base relation (refetched once)
- Proxy matcher excludes only exact /login and /api/auth/ paths

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:12:39 +02:00
Pascal LinxweilerandClaude Opus 5.5 d16bd6dfee README: move NAS guide and config reference to the wiki
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:53:39 +02:00
Pascal LinxweilerandClaude Opus 5.5 67191b3e16 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>
2026-10-05 19:49:17 +02:00
327 changed files with 57053 additions and 674 deletions

No files matched your search

+43 -26
View File
@@ -1,32 +1,49 @@
# 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
# Optional: launch80.com publish token (comes with the launch80 Supporter role). Lets you publish a
# benchmark run as a public launch80 page, after a preview and an explicit confirmation. Stays on
# the server; never sent to the browser or written to logs.
L80_TOKEN=
# ---------------------------------------------------------------------------
# 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
# How often the worker checks every model on the Hub (still there? newer commit?); 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
+2 -1
View File
@@ -14,10 +14,11 @@ jobs:
steps:
- uses: actions/checkout@v4
# No `cache: npm`: the runner's cache server isn't reachable from job containers here, and the
# restore + save timeouts cost ~9 minutes per run. `npm ci` alone takes ~20 s.
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- name: Resolve version and image name
run: |
+500 -1
View File
@@ -4,7 +4,506 @@ All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.14.2] - 2026-10-22
### Fixed
- A running download's progress could jump back and forth between the real value and 0 B while
`hf` kept downloading. A single progress reading that missed the partial file (a folder changing
while the worker listed it, or a stale size on a network share) counted as nothing downloaded.
Folders that vanish mid-listing are now skipped instead of failing the whole listing, and a file's
progress no longer goes backwards during a run.
## [0.14.1] - 2026-10-22
### Fixed
- Downloads with a file over 50 GB failed with "The file is too large to be downloaded using the
regular download method". `hf` (huggingface_hub 2.1.1) only downloads such files over Xet, which
Kaname turns off by default for steady progress; a download that includes one now uses Xet (noted
in the job log; its progress grows in bursts).
## [0.14.0] - 2026-10-21
A quality eval next to the speed benchmarks: a short, deterministic check of tool calling, coding and
long-context retrieval, so a launch option that makes a model faster but worse shows up.
No changes to `compose.yaml` or `.env`. The new column is added on start.
### Added
- **Quality eval** as a run type (deployment page → Benchmark → Quality), run against a deployment
with greedy decoding, a fixed seed and thinking turned off:
- **tool calling**: 12 requests; one tool call with valid JSON, the right function and arguments;
- **coding**: 8 short Python functions, checked by unit tests in a throwaway container from Kaname's
own image (no network, read-only, unprivileged user, no capabilities, CPU/memory/process limits);
- **long-context retrieval**: a code hidden at 10/50/90 % depth in texts of 25/50/100 % of the
context, sized with the server's own tokenizer.
The score (0–100) is the mean pass rate of the sections that could run; a server that refuses tool
calls doesn't count as 0. The eval set is versioned data in the repo (`src/evals/v1`), and every
result records its version (`kaname-eval-1`).
- The run page shows the score, each section and every item with the reason it failed. Compare views
get a "Quality" group; the benchmark list shows the score; sweeps can run the eval on every variant
("Also run the quality eval") and show it as a column.
- API: `POST /api/v1/benchmarks` with `kind: "eval"` (optional `sections`), `quality` in run, sweep
and compare answers, `"quality": true` for sweeps; the same guardrails as other runs.
- The tuning skill checks quality after speed and reports both.
## [0.13.0] - 2026-10-21
The agent API can now deploy and benchmark models, so an AI agent can tune launch options for the
hardware: within guardrails you set, only on deployments its own token created, and by default only
after you approve each start, run and sweep.
No changes to `compose.yaml` or `.env`. The new columns and table are added on start. Existing
tokens keep their scopes; grant the new ones with **Scopes** in Settings → API tokens.
### Added
- **Token scopes** `deployments:read`, `deployments:write`, `benchmarks:read`, `benchmarks:run`, and
editing an existing token's scopes.
- **`/api/v1` for deployments** ([docs/api.md](docs/api.md)):
- `GET /api/v1/runtimes`: pulled runtimes, what they serve, whether agents may use them and which
extra arguments; the host's GPUs.
- `GET /api/v1/deployments`, `GET /api/v1/deployments/{id}`: state, endpoint, options, the engine
version and slots, live CPU/RAM; the log with `?log=N`.
- `POST /api/v1/deployments` with the same validation, memory/VRAM estimate and `docker run`
command as the form (returned in the answer); `dryRun: true` only checks. Unknown fields are
refused instead of ignored.
- `PATCH`, `POST …/start`, `POST …/stop`, `DELETE` for the token's own deployments.
- **`/api/v1` for benchmarks**: `POST /api/v1/benchmarks` (run or A/B, quick or full, phases,
description), `GET /api/v1/benchmarks/{id}` with a compact result (headline numbers, the run's
hardware/runtime/model setup, GPU and RAM use; the full summary with `?full=1`), cancel, a list,
`GET /api/v1/benchmarks/compare?ids=` (what differs, what's the same), and sweeps
(`POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}`, cancel).
- **`?wait=<seconds>`** (max 900) on the job, deployment, run and sweep status endpoints: the request
returns once the state settles, so agents make one call instead of polling. Things that wait for
approval answer right away.
- **Guardrails for API deployments and benchmarks** (Settings → API tokens): approval (default: ask
me), agent deployments at once (1), one agent run or sweep at a time and no agent start while one
runs, time limits per run and sweep (30 min / 3 h, enforced by the worker), max sweep variants (8),
a runtime allowlist, an allowlist of extra argument flags per engine (values can't be paths or
URLs; the error names the argument), host ports only within a range (none by default), and caps
for memory and CPUs (agent deployments always get a memory limit).
- **Protected deployments**: the Protect button on a deployment's page. Agents can't edit, stop,
delete or benchmark it, nor start anything on the same GPUs that would crowd it out of VRAM
(estimated).
- **Approval** for agent starts, runs and sweeps on the deployment, run and sweep pages; "awaiting
approval" in the lists.
- Everything an agent creates shows **requested by &lt;token&gt;**, with a filter in the deployment
and benchmark lists; an **activity log** per token (Settings → API tokens) lists every request,
including refusals with their error code.
- **Agent skill for tuning** ([docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md)): check the
limits, pick a runtime, deploy (dry run first), wait until ready, benchmark, change one variable at a
time (or sweep), compare, report a compact table, stop the deployment; no polling loops, stop when
something needs approval, never work around a guardrail.
### Changed
- The download skill and messages use `?wait=` instead of "check again later".
## [0.12.0] - 2026-10-21
Intel GPU support (Arc A- and B-series, Arc Pro): telemetry during benchmarks, presets, render group
handling and a VRAM estimate for NVIDIA and Intel alike. Host prerequisites are on the wiki page
"Intel GPUs".
No changes to `compose.yaml` or `.env`.
### Added
- **GPU telemetry for Intel and AMD** in benchmark runs, A/B and sweeps, with the same fields as
NVIDIA (VRAM in use, utilization, power, temperature):
- power and temperature from the GPU's hwmon sensors (energy counter or power reading);
- AMD: VRAM in use and busy percent from sysfs;
- Intel: VRAM in use and utilization summed from every process's DRM fdinfo (the only place the
`xe`/`i915` drivers report them), read by a probe container that runs only during the run: host
PID namespace, `SYS_PTRACE` and `DAC_READ_SEARCH` only, no network, read-only, removed at the
end. Utilization is the busiest engine class, like `intel_gpu_top`.
- **Temperature** for every GPU (NVIDIA too), shown in the run's resources and, with GPU power, as
sweep table columns.
- **VRAM estimate** in the deployment form for NVIDIA and Intel/AMD: weights, KV cache and compute
buffers for llama.cpp with all layers on the GPU, the reserved share for vLLM, against the GPUs'
VRAM, with a hint when it doesn't fit.
- **Render group handling**: the worker reads the group IDs of the host's `/dev/dri` nodes (render,
video) and adds them to Intel/AMD runtime containers, so images that don't run as root can use the
GPU.
- The llama.cpp **Intel SYCL and Vulkan runtimes are added** the first time an Intel GPU is detected.
### Changed
- The llama.cpp Intel (SYCL) preset sets `ZES_ENABLE_SYSMAN=1`, so llama.cpp sees free VRAM (needed
by `-ngl auto`). Preset descriptions mention the B-series.
- GPU figures a source doesn't report are now shown as "—" instead of 0.
## [0.11.0] - 2026-10-20
Every benchmark run now records what it ran on: GPUs with their PCIe link and Resizable BAR, the
runtime image and the engine version the server reports, model, quant and KV cache type, context and
concurrency, plus a system summary and your own description. All of it is shown on the run page, in
compare views and sweep tables, and goes to BetterBench and the launch80 preview.
No changes to `compose.yaml` or `.env`. The new columns are added on start.
### Added
- **Run metadata**, recorded when a run starts (single runs, A/B and sweep variants):
- GPU count, name and VRAM; PCIe link, current and maximum (e.g. "Gen4 x8 of Gen5 x16"), read
from sysfs at the card's upstream port (behind on-card switches like Intel's Arc B-series) or
from `nvidia-smi`; peer-to-peer between GPUs (`nvidia-smi topo -p2p`, "n/a" with one GPU);
Resizable BAR (on when a BAR covers the VRAM).
- GPUs slow their link down when idle, so the current link is sampled during the run and the
fastest one seen under load is recorded ("at idle" when it couldn't be sampled).
- Runtime image, tag and registry digest, and the engine version the server reports once it's
ready (llama.cpp `/props` build, vLLM `/version`, falling back to the startup log). Runtimes have
an optional **engine name** for forks (e.g. `vllm-radiance`).
- Model, quant and KV cache type (e.g. "Q4_K_M with q8_0 KV cache"), context length and
concurrency (llama.cpp slots as reported by the server, vLLM max sequences).
- **System summary** per run: CPU model, cores and threads, RAM, the disk holding the models
folder, OS and kernel, GPU driver versions, VM or bare metal with GPU passthrough, Kaname version.
Only these whitelisted facts; never the hostname, IP addresses, users or paths.
- **Description** per run: set it when starting a run or edit it on the run page.
- Everything goes to BetterBench as `--note`s (in `results.json` and its report) and into the
launch80 dry-run preview as page sections (description, hardware and runtime, system), visible in
the preview before anything is sent.
- **Settings → Hardware**: what was detected, with manual values for what detection can't see (in a
VM the PCIe link is the one the VM sees; new GPUs missing from the PCI ID list). New runs use them.
- The run page shows the metadata; compare views get a "Hardware & runtime" section and a prefill
row in the headline; sweep tables list the setup shared by all variants and show what differs as
columns.
- `scripts/intel-probe.sh`: read-only diagnostics for Intel GPU hosts (link, BARs, hwmon, DRM
fdinfo, `/dev/dri` groups), for the upcoming Intel GPU support.
### Changed
- The image includes the PCI ID database (`pci.ids`) for GPU names.
### Fixed
- A run or sweep with both "quick" and an explicit number of passes failed (BetterBench refuses
`--quick` with `--passes`); the passes now win.
- Agent skill (`docs/agent/SKILL.md`) works with how Hermes Agent runs commands: a `kaname` helper
script (`docs/agent/kaname`) instead of a shell function that didn't survive between commands,
`KANAME_URL`/`KANAME_TOKEN` declared in the frontmatter, and far less polling (none while a
request waits for approval, one check around the ETA while downloading).
## [0.10.0] - 2026-10-20
An API for AI agents: a token-authenticated `/api/v1` lets a program look up models, request
downloads and follow them, within guardrails you set and, by default, only after you approve each
request.
No changes to `compose.yaml` or `.env`. If Kaname is behind a forward-auth proxy, let `/api/v1/`
through without forward auth (example in [docs/api.md](docs/api.md)). The new table is created on
start.
### Added
- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), name,
scopes `models:read` and `downloads:create`, last used, revoke. Sent as
`Authorization: Bearer kn_…`; only `/api/v1` accepts them, and it accepts nothing else (the rest of
Kaname stays OIDC-only). No token can delete models or files, change settings, or manage runtimes
or tokens.
- **`/api/v1`**, compact JSON with actionable error messages ([docs/api.md](docs/api.md)):
- `GET /api/v1`: the token's name, scopes and the guardrails.
- `GET /api/v1/hub/lookup?repo=`: commit SHA, quants and files with sizes (the Add model lookup).
- `GET /api/v1/models`: the library with its search and filters (author, family, quant, tag,
status, requested by) and the size on disk; `GET /api/v1/models/{id}`.
- `POST /api/v1/downloads`: repo + pinned commit + a quant (weights plus the recommended companion
files, as in Add model) or include globs, optional tags. Uses the same add-model and queue code
as the UI. Repeating a request returns the existing model and job instead of queueing a
duplicate; for a model already in the library it adds the missing files.
- `GET /api/v1/jobs/{id}`: state, per-file progress, error; the `hf` log only with `?log=N`.
- `GET /api/v1/disk`: free, used and reserved space on the models folder.
- **Guardrails for API downloads** (Settings → API tokens): approval mode (default: requests wait
as *pending approval* until you approve or reject them on the model or job page), max size per
request (60 GB), free space that must remain after the download, counting what other open
downloads still need (100 GB), API jobs at once (2), and an optional author allowlist. Rejecting a
request removes a model it added, or restores the previous file selection.
- Everything requested with a token shows **requested by &lt;token name&gt;** in the library, on the
model and job pages, with a "Requested by" filter (and "awaiting approval" under Status).
- **Agent skill** for Hermes Agent and similar ([docs/agent/SKILL.md](docs/agent/SKILL.md)): how to
search, look up, request and monitor a download with `curl`, the guardrails, and to wait for
approval instead of retrying.
### Changed
- Settings → API keys is now **Runtime API keys** (the keys deployments require), to keep it apart
from API tokens.
- Tests can now use the database: `npm test` runs with `--conditions=react-server`.
## [0.9.0] - 2026-10-13
Model testing, part three: benchmarks. Measure deployments with BetterBench (the benchmark behind
launch80.com) and get a launch80-style report: single runs, paired A/B runs and sweeps over launch
options, with CPU, RAM and GPU usage recorded during each run. Runs can be published to launch80
with a preview and an explicit confirmation. Runtimes can use NVIDIA, Intel/AMD and ROCm GPUs, and
downloads can be speed-limited.
No changes to `compose.yaml`. Optional new `.env` setting: `L80_TOKEN` (launch80 publishing). The
new database tables are created on start.
### Added
- **Download speed limit** (Settings → Downloads), in MB/s, for all downloads together; changes
apply to running downloads within seconds. `hf download` and hf_xet have no bandwidth option
(checked with huggingface_hub 2.1.1 / hf_xet 1.6.0), so the worker pauses and resumes the hf
process (SIGSTOP/SIGCONT) whenever it gets ahead of the limit: short bursts above it, the
average holds (tested: 145 MB at a 2 MB/s limit took 67 s). Linux only; ignored on Windows.
- **Paired A/B benchmarks** (`betterbench ab`): from a deployment's Benchmark card, pick another
running deployment of the same model as B. The same prompts go to both, alternating, with greedy
decoding, until the difference is known to ±the target precision (default 1 %, at most 200
pairs). The report shows the verdict (faster/slower/no measurable difference), the confidence
interval, both sides, what differs between them and the caveats, after launch80's rules.
- **Sweeps**: vary one or two settings of a deployment (context size, KV cache type, quant file,
threads, parallel slots, batch sizes, flash attention, prompt cache, GPU layers, CPU limit; vLLM:
dtype, max sequences, KV cache, GPU memory share), up to 16 variants. Kaname deploys each variant
in turn, benchmarks it, removes it again, and shows all of them side by side (chart and table,
best values in bold), with a link to compare the runs in detail. Compare now takes up to 16 runs.
- **Resource usage in every run**: CPU (cores, average and peak), RAM (average and peak against the
container limit) from Docker, and per GPU VRAM, utilization and power from nvidia-smi, sampled
every 2 s while the benchmark runs. Shown on the report, the A/B report and the sweep table.
- **Benchmarks** (new main menu entry) with [BetterBench](https://github.com/GGZ14/BetterBench)
(Apache-2.0, the benchmark behind launch80.com), built into the image (v0.6.1, archive pinned by
checksum).
- Start a run from a running deployment: quick (5 passes) or full (20), choose generation,
prompt processing (input lengths up to the context size) and parallel requests, add a label.
- Runs go one at a time; the run page shows the current step, the live BetterBench output, then
headline numbers (weighted decode t/s, time to first token, prefill t/s, peak throughput) and
the per-category, per-length and per-load tables, BetterBench's own HTML report (sandboxed)
and its `results.json`.
- Each run keeps a snapshot of the deployment's settings (and the CPU/GPU it ran on). Select runs
to **compare** them: differing settings are highlighted, numbers show the change against the
first run.
- Cancel, run again with the same settings, rename, delete.
- **Benchmark report page** after launch80's `bench.betterbench.v1`: headline tiles (combined
decode, ITL 1% low or stream-update p99, TTFT p50), "Read these first" caveats with launch80's
rules (quick run, under-sampled percentiles marked †, runs stopped at max_tokens, batched streams,
failed requests, skipped prefill depths, prefix-cache hits), charts for decode by category, ITL
range, prefill and parallel load, the full tables, the reasoning split and a Method section. Every
figure comes from BetterBench's own report functions; existing runs are recomputed on start.
- **Publish to launch80** (double opt-in, as the L80 docs describe): step 1 runs
`L80 betterbench --results … --dry-run --payload-out` and shows exactly what would be sent
(template, size, title, summary, notes; endpoint and host removed; the payload is downloadable);
step 2 publishes that same file with `L80 publish` only after an explicit confirmation. Needs
`L80_TOKEN` (launch80 Supporter) for the worker; the L80 CLI 0.4.0 ships in the image, pinned by
checksum. The link, who confirmed it and when it expires (5 days) are kept per run.
- `results.json` downloads no longer contain the endpoint URL or host name.
- **GPUs.** Runtimes have a type: CPU, NVIDIA (CUDA), Intel/AMD via `/dev/dri` (Vulkan, SYCL,
XPU) or AMD ROCm, with presets for the official CUDA, Vulkan, Intel and ROCm builds of
llama.cpp and vLLM.
- The worker lists NVIDIA GPUs (name, VRAM, driver) with a short-lived probe container and shows
them under Settings → Runtimes; the first time one shows up, a "llama.cpp (CUDA)" runtime is
added.
- Deployments on GPU runtimes pick which GPUs to use and set GPU layers (`-ngl`), split mode,
tensor split and MoE experts in RAM (llama.cpp) or tensor parallelism and GPU memory share
(vLLM).
- llama.cpp **prompt cache in RAM** (`--cache-ram`) as a deployment option, 1 GiB for new
deployments.
### Fixed
- llama-server keeps up to 8 GiB of earlier prompts in RAM by default. Under a container memory
limit it grew until the limit and then slowed to a crawl (the memory-mapped model got evicted).
The memory estimate now counts the prompt cache and the KV cache (by context size and cache
type).
## [0.8.0] - 2026-10-06
Model testing, part two: deployments. Serve a downloaded model with a llama.cpp or vLLM runtime
container, tune its launch options, protect it with API keys and try it from Kaname.
No changes to `compose.yaml`; the new database tables are created on start.
### Added
- **Deployments** (new main menu entry): serve a downloaded model with a runtime container.
- **New deployment:** pick a runtime (only pulled images), then a model it can serve (llama.cpp:
downloaded GGUF files with the quant, optional mmproj for vision and MTP head / draft model for
speculative decoding; vLLM: safetensors repos with a config.json), then launch options: context
size, threads, parallel slots, KV cache types, flash attention, batch sizes (llama.cpp) or data
type, max sequences, KV cache GiB (vLLM), CPU and memory limits (with an estimate), an optional
published host port and extra arguments. A live preview shows the exact `docker run` command.
- The worker starts the container on Kaname's Docker network with the models mounted read-only,
waits for `/health`, follows the log, samples CPU/RAM every 5 s and refuses to start when the
memory limits of running deployments wouldn't fit. Containers keep running across worker
restarts; orphaned ones are removed.
- Deployment page: state, load time, live CPU/RAM, endpoint URLs (Docker network and published
port), live log, start/stop/edit/delete, and a "Try it" chat that streams the answer and shows
time to first token and tokens/s.
- llama.cpp's built-in **web UI** can be switched on or off per deployment (`--no-webui`); with a
published host port the deployment page links to it.
- A failed start names the cause from the log (e.g. vLLM's `ValueError` instead of the end of the
traceback), followed by the last lines of output.
- A deployment's vLLM data type replaces the runtime's `--dtype` instead of repeating the flag.
- Models and runtimes used by a deployment can't be deleted until the deployment is.
- **API keys** (Settings → API keys): add generated or own keys, show and copy them again later.
A deployment with "Require an API key" accepts any of them (`LLAMA_API_KEY`, `VLLM_API_KEY` or
`--api-key` for several vLLM keys); the values are masked in the shown command and in the log, and
Kaname's own "Try it" chat sends one. Key changes apply when a deployment restarts.
- **Deploy from the library:** a "Deploy" button in the library and on the model page opens a new
deployment with the model and a fitting runtime preselected. The library and the model page link
to the deployments that use a model.
- Deployment form reorganized: launch options in groups (General, Context, Performance, KV cache,
Resources, Extra arguments) with each field's flag next to its label, the command in its own step,
and extra arguments as flag/value rows with "+ Add argument" (also in the runtime form).
### Fixed
- Dropdowns were unreadable in dark mode (white option list with light text): native controls now
follow the theme.
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
written (Drizzle queries only run when awaited).
## [0.7.0] - 2026-10-06
First part of model testing: runtimes (llama.cpp, vLLM and your own images) and the Docker
connection through a socket proxy. Starting containers with a model comes next.
**Upgrade note:** `compose.yaml` has a new `docker-proxy` service and `DOCKER_HOST` on the worker;
copy them from `deploy/compose.yaml`.
### Added
- **Runtimes** (Settings → Runtimes): container images that serve models. Presets for the official
llama.cpp CPU server (`ghcr.io/ggml-org/llama.cpp:server`) and vLLM CPU
(`vllm/vllm-openai-cpu:v0.31.0`), plus your own images from any registry (e.g. patched forks) with
an engine type (llama.cpp- or vLLM-compatible), environment, extra arguments, shared memory,
device passthrough (only `/dev/dri…`, `/dev/kfd`) and an opt-in "NUMA tuning" switch (the
`CAP_SYS_NICE` + `seccomp=unconfined` that vLLM recommends on CPU; off by default).
- Pull and update runtime images from the UI, with progress and readable errors.
- Docker host card: Docker version, CPU model and features (AVX2, AVX-512, AMX, …), memory, and the
network and models source the worker detected from its own container.
- `docker-proxy` service (`tecnativa/docker-socket-proxy:v0.5.0`) in both compose files; the worker
reaches Docker only through it (`DOCKER_HOST`). New settings `DOCKER_HOST`,
`KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` (see the wiki).
## [0.6.0] - 2026-10-06
Delete models (with their files), verify and deep verify, one-click repair, and update checks
with a deliberate Update. Database migrations run automatically on start.
### Added
- **Delete** any model (also failed or incomplete ones), with confirmation. By default the worker
deletes its files from disk: only the repo's files and hf's `.cache`; files you put in the folder
yourself are kept, empty folders are removed. Unchecked, only the library entry goes and the folder
shows up under "Found in the models folder".
- **Verify** a model: every selected file is checked for existence, size and the version hf recorded;
reports missing files, size mismatches and extra files in the folder. **Deep verify** hashes every
file (SHA-256 for LFS files, git blob SHA-1 for small files) against the Hub, with progress.
- **Repair** re-downloads only what's missing or broken. Broken files are deleted before `hf` runs,
because `hf` skips a file whose metadata matches without checking its content or size.
- **Update checks:** the Hub check (every `UPDATE_CHECK_INTERVAL_HOURS` and "Check now") also
resolves the tracked revision. If there's a newer commit, the model shows "update available" (badge
in the library and a Status filter value, banner on the model page) with the selected files that
changed, were added or were removed. **Update** is a deliberate action: it pins the new commit (the
old one stays in the revision history), downloads changed and new files, and deletes files that are
no longer selected once the download succeeded.
- Download card: **Resume** for interrupted or cancelled downloads, **Retry** for failed ones.
- Job names in the job list and job page: Download, Download more, Import, Repair, Update, Verify,
Deep verify, Delete.
## [0.5.0] - 2026-10-06
Hugging Face style model pages, file labels, recommended files, importing models already on disk,
and flagging models deleted from the Hub. Database migrations run automatically on start.
### Added
- Model pages modeled on Hugging Face, built from cards: a header with org avatar, `org / name`
with copy button, pills for task, format, architecture, language and license, your tags and a
Hugging Face link; a content card with tabs:
- **Files** (default): selected files with type icon, size, LFS marker and local state
(downloaded, missing, size mismatch, …), a "on disk" progress summary, and the unselected repo
files collapsed below; each file links to the Hub at the pinned commit
- **Model card**: the repo's README at the pinned commit, rendered (sanitized HTML, relative
links/images resolved to the Hub)
- **Jobs**: download history
- Custom tags are color-coded: automatic color from the name, or one you pick in Settings.
- File labels in front of every file name: Model, MTP, Vision (mmproj), Draft, Adapter, imatrix,
Config, Tokenizer, Template, Docs, Image, Git (detected from the file name).
- Split files (`…-00001-of-00003.gguf`) are shown and selected as one entry with "N parts", the
combined size and a combined status, in the Files tab, Add model, Download more and progress lists.
- **Download more** in the Files tab: pick additional files (quick-select chips, checkboxes) and
download them; they're added to the model's selection. Files already on disk are skipped.
- **Settings** page (`/settings`), first section **Labels**: name and color per file label (with
reset), and rename, recolor or delete your tags. Stored in a new `settings` table.
- App icon (要).
- Sidebar with download status/actions, local copy details (commit, path, patterns) and a model
tree (base model → quantized/finetuned → this repo) listing other local models of the same base.
- Hub metadata now includes the author's avatar and the relation to the base model; existing models
are refetched once by the worker.
- Models deleted from Hugging Face are flagged, never deleted locally: the worker checks every model
every `UPDATE_CHECK_INTERVAL_HOURS` (and right after a failed download) whether the repo and the
pinned commit still exist. A deleted repo (or one made private) or a rewritten history shows a
warning badge in the library (searchable, and a value of the Status filter), a banner on the model
page, and blocks new downloads and "Download more". "On the Hub" in the sidebar shows the last
check, with "Check now".
- **Import models already on disk:** the worker scans the models folder (at startup, every
2 minutes and on "Rescan") for `<org>/<name>` folders that aren't in the library. They're listed
under "Found in the models folder"; **Import** opens Add model for that folder with the repo, the
commit hf recorded (if any) and the files already there preselected, marked "on disk". The import
job runs `hf download` into the existing folder: hf 2.1.1 hashes files it didn't download itself,
keeps those that match and downloads only missing or different ones. Other files in the folder
are left alone. Jobs show the purpose "import".
- **Recommended files:** picking a quant (chip or checkbox) in Add model or Download more also
selects the files that usually go with it, shown in a "Recommended with your quant" strip where
each can be unchecked. They drop out again when you deselect the quant. Variants are matched:
the MTP head or mmproj with the same quant if there is one, otherwise the best single one (mmproj:
F16, BF16, Q8_0, F32); nothing is added if the model already has one of that kind. Which kinds
(default: chat template, MTP, vision) is set in the new **Settings → Downloads**.
- Create tags in Settings (name and color), before any model uses them.
- Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your
existing tags with their colors, and "Manage tags…".
- Account menu in the header with your profile picture from the OIDC provider (initials as
fallback): name and email, links to the settings, theme (system/light/dark) and sign out.
### Changed
- Model URLs are the repo path, like on Hugging Face: `/unsloth/Qwen3-8B-GGUF` (case-insensitive,
redirects to the canonical spelling). Old `/models/<id>` links redirect.
- The auth gate excludes only exact paths (`/login`, `/api/auth/…`), so org names like `loginx`
can't bypass it.
- Quant labels (library column, Quant filter, "Local copy") only count model weights, not MTP,
mmproj or imatrix files.
- Tags are no longer deleted automatically when no model uses them anymore; delete them in Settings.
- Settings has separate pages for **File labels**, **Tags** and **Downloads**.
- The selection bar at the bottom of Add model is a floating card like the rest of the page.
- Header: app icon, navigation with icons and the current page highlighted.
- Docs: full configuration reference and the NAS guide moved to the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki); the README keeps the quick install.
### Fixed
- Hydration error in progress bars on non-English browsers (locale-dependent `aria-valuetext`).
## [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
+28 -3
View File
@@ -1,3 +1,4 @@
# syntax=docker/dockerfile:1.7
# One image for both services; the first argument picks the role: `web` (default) or `worker`.
FROM node:24-trixie-slim AS node
@@ -15,16 +16,38 @@ RUN npm run build \
# --- runtime -----------------------------------------------------------------
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
# has CA certificates and libstdc++, so no apt is needed.
# has CA certificates and libstdc++; apt only adds the PCI ID database (GPU names for benchmarks).
FROM python:3.13-slim-trixie AS runtime
COPY --from=node /usr/local/bin/node /usr/local/bin/node
RUN apt-get update \
&& apt-get install -y --no-install-recommends pci.ids \
&& rm -rf /var/lib/apt/lists/*
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
# re-verify that before bumping.
ARG HF_HUB_VERSION=2.1.1
# BetterBench (Apache-2.0), the benchmark run against deployments. Not on PyPI: the release
# archive is pinned by checksum; flags used by src/worker/betterbench.ts are verified per version.
ARG BETTERBENCH_VERSION=0.6.1
ADD --checksum=sha256:f0a9d7fcc411c809ff87a0a22e2d76f6662b426431d2ae9fa273bc2644464db7 \
https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /tmp/betterbench.tar.gz
# L80 CLI (launch80.com): publishes a BetterBench run as a shareable page. Release archives pinned
# by checksum (from the release's checksums.txt); the per-architecture one is installed.
ARG L80_VERSION=0.4.0
ARG TARGETARCH
ADD --checksum=sha256:cde6b67dfb67b0ffddd56dfd384b8b24610573199287c59597359145310d9d23 \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /tmp/l80/amd64.tar.gz
ADD --checksum=sha256:bbd7c6cf35bcba2bf9a651f348581b691b36d5f7cdca9c8a11e8a1ac2fc3f5bc \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /tmp/l80/arm64.tar.gz
RUN mkdir -p /opt/l80 \
&& tar -xzf "/tmp/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
&& chmod 0755 /opt/l80/L80 \
&& rm -rf /tmp/l80
RUN python -m venv /opt/hf \
&& /opt/hf/bin/pip install --no-cache-dir "huggingface_hub[hf_xet]==${HF_HUB_VERSION}" \
&& rm -rf /root/.cache \
&& python -m venv /opt/betterbench \
&& /opt/betterbench/bin/pip install --no-cache-dir /tmp/betterbench.tar.gz \
&& rm -rf /root/.cache /tmp/betterbench.tar.gz \
&& useradd --uid 1000 --create-home --shell /usr/sbin/nologin app \
&& mkdir -p /data /models \
&& chown app:app /data /models
@@ -38,7 +61,9 @@ ENV PATH=/opt/hf/bin:$PATH \
HOSTNAME=0.0.0.0 \
DATABASE_URL=file:/data/app.db \
MODELS_DIR=/models \
HF_HOME=/data/hf-home
HF_HOME=/data/hf-home \
BETTERBENCH_BIN=/opt/betterbench/bin/betterbench \
L80_BIN=/opt/l80/L80
WORKDIR /app
COPY --from=build --chown=app:app /app/package.json /app/next.config.ts ./
+111 -65
View File
@@ -1,94 +1,140 @@
# 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.
## Configuration
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.
All settings live in `.env`. The four steps above cover the required ones; the **[configuration
reference in the wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration)**
lists every option with defaults and examples (folders, ports, download tuning, OIDC groups, which
Hugging Face token to use).
## Local development
Models end up in `<models folder>/<org>/<repo>/`, e.g. `models/unsloth/Qwen3-8B-GGUF/`.
More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki).
## 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**. Files that belong with the quant (chat template, MTP head, vision projector)
are selected along with it; choose which kinds in Settings → Downloads. 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.
Create, rename and color them in Settings.
- **Import:** models you already have in the models folder (as `<org>/<name>`) show up under
"Found in the models folder"; **Import** matches them with the Hub repo and verifies the files
instead of downloading them again. See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models).
- **Verify / repair:** Verify checks every file's presence and size, Deep verify hashes them against
the Hub; Repair downloads only what's missing or broken.
- **Updates:** Kaname checks the Hub regularly and shows which of your files a newer commit changes;
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
model is flagged and your local copy is kept.
- **Delete:** removes the model and, if you want, its files from disk.
- **Runtimes:** register llama.cpp, vLLM or your own fork images and pull them from Settings → Runtimes
(groundwork for testing model configs). See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
- **API for agents:** create a token in Settings → API tokens and let a program or AI agent look up
repos, list models and request downloads at `/api/v1`, and deploy and benchmark models to tune
their launch options, within guardrails you set (approval, sizes and limits, one GPU job at a time,
allowed runtimes and arguments, protected deployments). See [docs/api.md](docs/api.md) (also how to
let `/api/v1/` past a forward-auth proxy) and the agent skills [docs/agent/SKILL.md](docs/agent/SKILL.md)
and [docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md).
## 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. Files over 50 GB can only be downloaded with Xet, so a download that
includes one uses Xet anyway.
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
metadata after each download.
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
hashed and kept if they match, and downloaded again if not. Imports rely on this.
## 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).
+22
View File
@@ -16,6 +16,11 @@ services:
worker:
<<: *app
command: worker
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
DOCKER_HOST: tcp://docker-proxy:2375
volumes: [data:/data, models:/models]
web:
@@ -23,6 +28,23 @@ services:
ports: ["${WEB_PORT:-3000}:3000"]
volumes: [data:/data]
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
volumes:
data:
models:
+23 -16
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:
@@ -8,9 +8,11 @@ services:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
DOCKER_HOST: tcp://docker-proxy:2375
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:
@@ -21,14 +23,19 @@ services:
- ${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}"
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
+192
View File
@@ -0,0 +1,192 @@
---
name: kaname-tuning
description: Deploy local LLMs on the user's Kaname server, benchmark their speed and check their answer quality to find good launch options (context, KV cache type, batch sizes, GPU layers, runtime) for the hardware. Use when the user asks to deploy, test, benchmark, tune or compare a model's settings, or to find the fastest setup for a model.
required_environment_variables:
- name: KANAME_URL
prompt: Kaname base URL (no trailing slash)
- name: KANAME_TOKEN
prompt: Kaname API token (kn_…) with the deployments and benchmarks scopes
---
# Kaname: deploy and tune models
Kaname runs models in containers (llama.cpp or vLLM) and measures them with BetterBench. With this
skill you deploy a downloaded model, benchmark it, change **one** launch option at a time and report
which setup is best. To find or download models, use the `kaname-models` skill (`SKILL.md`).
You may only change and benchmark deployments your own token created. You **cannot** touch the
user's deployments (especially protected ones), change settings, runtimes or tokens, or delete
models. Tell the user when something needs one of those.
Every call needs `KANAME_URL` and `KANAME_TOKEN` (never print the token or put it in a URL), and the
`kaname` helper (a `curl` wrapper that adds the token and JSON headers; see `SKILL.md` → Setup). If
`kaname` is missing, write out
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …` instead.
Errors are `{"error": {"code", "message"}}`; the message says what to do.
## Rules
- **No polling loops.** Status calls take `?wait=S` (max 900): Kaname holds the request until the
state settles. Make one call, with `-m` (curl's time limit) a bit above the wait.
- **Approval:** by default every start, run and sweep waits for the user (`state:
pending_approval`). Then **stop**: tell the user what you asked for and that it awaits their
approval in Kaname. Don't retry, don't poll. Continue when the user says it's approved.
- **Never work around a guardrail** (another token, splitting a sweep, renaming things). Report the
error message and stop.
- **One GPU job at a time:** one of your deployments running at once (unless the user raised the
limit), one run or sweep at a time. Stop your deployment when you're done.
- **Change one variable at a time**, so a difference has one cause.
## 1. Know your limits
```bash
kaname "$KANAME_URL/api/v1"
```
`deploymentGuardrails`: approval mode, how many of your deployments may run, run/sweep time limits,
max sweep variants, caps, host ports. Your scopes must include `deployments:write` and
`benchmarks:run`; if not, tell the user.
## 2. Pick a model and a runtime
```bash
kaname "$KANAME_URL/api/v1/models?status=ready&q=qwen3"
kaname "$KANAME_URL/api/v1/models/<modelId>" # its files (pick a .gguf for llama.cpp)
kaname "$KANAME_URL/api/v1/runtimes"
```
Runtimes say what they serve (llama.cpp: a GGUF file, vLLM: a safetensors repo), whether you may use
them (`"allowed": true`) and which extra argument flags you may pass (`allowedExtraArgs`). `gpus`
lists the host's GPUs and their VRAM.
Previous results for this model, to start from what is known:
```bash
kaname "$KANAME_URL/api/v1/benchmarks?limit=10"
```
## 3. Deploy
Check first (nothing is created; you get the exact command and the memory/VRAM estimates):
```bash
kaname -X POST "$KANAME_URL/api/v1/deployments" -d '{
"runtimeId": "<runtimeId>", "modelId": "<modelId>", "dryRun": true,
"options": { "modelFile": "Qwen3-8B-Q4_K_M.gguf", "contextSize": 16384, "gpuLayers": "auto",
"cacheTypeK": "q8_0", "cacheTypeV": "q8_0", "parallel": 1, "extraArgs": [] }
}'
```
If `estimates.vramMb` is above `estimates.gpuVramMb`, lower the context, quantize the KV cache or
pick a smaller quant. Then the same body without `"dryRun"`:
- `state: pending_approval` → tell the user and stop (see Rules).
- `state: starting` → wait until it is ready:
```bash
kaname -m 660 "$KANAME_URL/api/v1/deployments/<id>?wait=600"
```
`state: running` → go on. `state: failed` → read `error` (and `?log=50`), fix the options
(`PATCH`, below) and start again; don't repeat the same failing options.
## 4. Benchmark
```bash
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{
"deploymentId": "<id>", "quick": true, "label": "Q4_K_M ctx16k q8_0 KV",
"description": "Baseline for tuning Qwen3-8B on this GPU"
}'
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
```
- `quick: true` (5 passes) to screen options; `quick: false` (20 passes) to confirm the winner.
- `phases` (`decode`, `prefill`, `concurrency`) narrows what is measured; leave it out for all.
- The result's `headline` has `decodeTps` (generation speed), `prefillTps` (prompt processing at the
deepest prompt), `ttftMs` (time to first token) and `peakParallelTps`; `setup` lists GPU, PCIe,
engine version, model/quant/KV cache, context and concurrency; `resources` has VRAM, power and
temperature. `?full=1` only when you need the per-category details.
- If the wait times out, the run is still going: one more call with `?wait=900`, then report.
Then check that the answers are still right (speed alone can hide a broken setup):
```bash
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{"kind": "eval", "deploymentId": "<id>", "label": "Q4_K_M ctx16k q8_0 KV"}'
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
```
`quality.score` (0–100) and per section (`tools`, `coding`, `retrieval`). Add `?full=1` to see which
items failed. A drop of more than a few points against the baseline means the change hurt quality,
however fast it is.
## 5. Change one variable and compare
Stop, change one option, start, wait, benchmark again:
```bash
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
kaname -m 120 "$KANAME_URL/api/v1/deployments/<id>?wait=60"
kaname -X PATCH "$KANAME_URL/api/v1/deployments/<id>" -d '{"options": {"cacheTypeK": "f16", "cacheTypeV": "f16"}}'
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/start"
```
Or let Kaname do it: a **sweep** deploys each variant of one or two settings, benchmarks it (with
`"quality": true` also runs the quality eval) and removes it again (stop your own deployment first;
it counts as one run):
```bash
kaname -X POST "$KANAME_URL/api/v1/sweeps" -d '{
"baseDeploymentId": "<id>", "quick": true, "quality": true,
"params": [{ "key": "kvCache", "values": ["f16", "q8_0", "q4_0"] }]
}'
kaname -m 960 "$KANAME_URL/api/v1/sweeps/<sweepId>?wait=900"
```
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
`flashAttn`, `cacheRamMb`, `gpuLayers` (llama.cpp); `dtype`, `maxNumSeqs`, `gpuMemoryUtilization`
(vLLM); `cpus`. A sweep can take long: after a timed-out wait, report progress instead of waiting
again and again.
Compare runs side by side:
```bash
kaname "$KANAME_URL/api/v1/benchmarks/compare?ids=<run1>,<run2>,<run3>"
```
Differences under ~2 % between separate runs are noise. For a small difference that matters, run
an A/B (two deployments of the same model at once, if the user allows 2 agent deployments):
`{"kind": "ab", "deploymentId": "<A>", "deploymentBId": "<B>"}`.
## 6. Report and clean up
Report a compact table, one row per setup, the varied option first:
| KV cache | Decode t/s | Prefill t/s | TTFT ms | Quality | VRAM peak | Notes |
| --- | --- | --- | --- | --- | --- | --- |
| f16 | 58.1 | 1910 | 88 | 86.1 | 11.2 GB | baseline |
| q8_0 | 57.6 | 1880 | 90 | 86.1 | 9.4 GB | −1 % speed, same quality, 1.8 GB less VRAM |
Name the winner and why: speed and quality together (and what stayed the same: GPU, engine version,
quant, context). Then stop
your deployment (or delete it if the user doesn't need it):
```bash
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
```
## When something is refused
| `error.code` | What to do |
| --- | --- |
| `too_many_deployments` | Stop your other deployment first, or tell the user. |
| `gpu_busy` | Another agent job is running or a deployment is loading: wait once with `?wait=`, then retry once; otherwise report and stop. |
| `vram_protected` | It would crowd the user's protected deployment out of VRAM: smaller quant, context or quantized KV cache, or tell the user. |
| `arg_not_allowed` | That flag isn't allowed; use the structured option if there is one (`contextSize`, `gpuLayers`, `cacheTypeK`, …) or drop it. |
| `limit_exceeded` | Over the memory/CPU cap: smaller model or context. |
| `port_not_allowed` | Leave out `hostPort`. |
| `runtime_not_allowed`, `runtime_not_pulled` | Pick another runtime from `GET /api/v1/runtimes`, or tell the user. |
| `protected`, `not_owner` | Not your deployment: deploy your own. |
| `too_many_variants` | Vary fewer values. |
| `busy` | Stop the deployment before changing it. |
| `unauthorized`, `forbidden` | Token wrong, revoked or missing a scope: tell the user. |
+133
View File
@@ -0,0 +1,133 @@
---
name: kaname-models
description: Find, request and track downloads of local LLMs (Hugging Face models, GGUF quants) on the user's Kaname server. Use when the user asks to get, download, add or check a model, or asks which models are available locally or how much disk space is left.
required_environment_variables:
- name: KANAME_URL
prompt: Kaname base URL (no trailing slash)
- name: KANAME_TOKEN
prompt: Kaname API token (kn_…)
---
# Kaname: local model downloads
Kaname manages the user's local LLM library. You can look up Hugging Face repos, see what is
already downloaded, request a download and follow it. You **cannot** delete anything, change
settings, or start models with this skill: tell the user when they need one of those. To deploy and
benchmark models (with a token that has the deployments and benchmarks scopes), see
`SKILL-tuning.md`.
Every call needs two environment variables:
- `KANAME_URL`: e.g. `https://models.example.com` (no trailing slash)
- `KANAME_TOKEN`: the API token (`kn_…`). Never print it or put it in a URL.
## Setup
The examples use `kaname`, a small wrapper around `curl` that adds the token and JSON headers. The
user installs it once:
```bash
mkdir -p ~/.local/bin && curl -fsSL https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/docs/agent/kaname -o ~/.local/bin/kaname && chmod +x ~/.local/bin/kaname
```
If `kaname` is not found, write out the full command in each call instead:
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …`
(every command runs in a fresh shell, so don't define a shell function for it).
All responses are JSON. Errors are `{"error": {"code", "message"}}`; the message says what to do.
## 0. Know your limits
```bash
kaname "$KANAME_URL/api/v1"
```
Shows your token name, scopes and the guardrails. The defaults:
- **approvalMode `approve`**: your requests wait until the user approves them. That's normal.
- **maxRequestSize** (60 GB): one request may download at most this much.
- **minFreeSize** (100 GB): this much must stay free on disk after the download.
- **maxOpenAgentJobs** (2): at most this many of your requests pending or running at once.
- **allowedAuthors**: if not empty, only repos from these Hugging Face authors.
## 1. Is it already here?
```bash
kaname "$KANAME_URL/api/v1/models?q=qwen3%208b"
kaname "$KANAME_URL/api/v1/models?author=unsloth&quant=Q4_K_M&status=ready"
```
Filters: `q`, `author`, `family`, `quant`, `tag`, `status`, `requested_by` (comma-separate values).
If the model is there with `status: ready`, you're done. Don't request it again.
## 2. Look up the repo
```bash
kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"
```
Note `sha` (the commit) and pick a quant from `quants` (each has a `size`). Choose one that fits the
user's request and the limits: check `size` against `maxRequestSize`, and check space with:
```bash
kaname "$KANAME_URL/api/v1/disk" # availableForRequests = what a request may still use
```
If `gated` is not `false`, the download only works if the user's Hugging Face account has access.
## 3. Request the download
```bash
kaname -X POST "$KANAME_URL/api/v1/downloads" \
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"<sha from lookup>","quant":"Q4_K_M"}'
```
For repos without GGUF quants (safetensors), use `"include": ["*.safetensors", "*.json"]` instead
of `quant`. Optional: `"tags": ["…"]`.
Answer:
- `201`, `state: pending_approval`: **waiting for the user.** Tell them what you requested and that
it needs their approval in Kaname. **Do not retry or re-request.**
- `201`, `state: queued`: it will start on its own.
- `200`, `created: false`: you (or someone) already requested exactly this; you get the existing
job. Don't request it again.
## 4. Follow it
```bash
kaname -m 660 "$KANAME_URL/api/v1/jobs/<jobId>?wait=600"
```
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. With `?wait=600`
Kaname holds the request until the job is finished (or 600 s have passed; then `timedOut` is
`true`), so one call replaces a polling loop. Keep `-m` (curl's time limit) a bit above the wait.
Every call costs a full round of your context, so call rarely:
- **`pending_approval`:** do **not** poll. Tell the user what you requested and that it awaits
their approval in Kaname, then stop. Check again only when the user says it's approved, or, if
the user asks for it, schedule a single one-off check later with your cron/scheduling tool.
- **`queued` / `downloading` / `verifying`:** one call with `?wait=600`. If it comes back with
`timedOut: true` and the ETA is long, tell the user it is still downloading instead of waiting
again and again. Never loop in short intervals.
- **`completed`:** tell the user it's ready.
- **`cancelled`:** the user rejected or cancelled it. Don't ask again unless the user says so.
- **`failed`:** report `error.message` to the user. Don't loop on retries.
Add `?log=20` only when you need to explain a failure.
## When a request is refused
| `error.code` | What to do |
| --- | --- |
| `too_large` | Pick a smaller quant (or fewer files) that fits `maxRequestSize`. |
| `disk_space` | Pick a smaller quant, or tell the user the disk is full. |
| `too_many_jobs` | Don't wait in a loop: tell the user your earlier downloads are still pending or running, and stop. Request again later when the user asks. |
| `author_not_allowed` | Find the model from an allowed author, or ask the user. |
| `already_exists` | The repo is in the library at another commit; the user updates it in Kaname. |
| `busy` | That model has a download in progress; tell the user and stop. |
| `gated_no_access`, `gated_no_token` | The user must accept the model's terms on Hugging Face. |
| `disk_unknown` | Kaname's worker is offline; tell the user and stop. |
| `unauthorized`, `forbidden` | Your token is wrong, revoked or lacks a scope: tell the user. |
Never try to work around a guardrail (e.g. by splitting one big download into several requests).
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"
+419
View File
@@ -0,0 +1,419 @@
# Kaname API (`/api/v1`)
A small JSON API for programs and AI agents: look up Hugging Face repos, list the local library,
request downloads, deploy models and benchmark them to tune launch options. Everything an agent can
do here is bounded by [guardrails](#guardrails); it can't delete models or files, change settings,
manage runtimes or tokens, or touch deployments it didn't create.
The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login. Only
`/api/v1` accepts tokens, and it accepts *only* tokens (a browser session doesn't work there).
- [Authentication](#authentication)
- [Errors](#errors)
- [Endpoints](#endpoints): models and downloads, [deployments](#deployments), [benchmarks](#benchmarks)
- [Waiting instead of polling](#waiting-instead-of-polling)
- [Guardrails](#guardrails)
- [Behind a forward-auth proxy (Traefik)](#behind-a-forward-auth-proxy-traefik)
## Authentication
Create a token in **Settings → API tokens**. It is shown once; Kaname stores only its SHA-256.
Send it with every request:
```
Authorization: Bearer kn_…
```
| Scope | Allows |
| --- | --- |
| `models:read` | Hub lookup, list models, read jobs (and their log), disk space |
| `downloads:create` | `POST /api/v1/downloads`, within the guardrails |
| `deployments:read` | List runtimes and deployments, read a deployment's state and log |
| `deployments:write` | Create deployments; edit, start, stop and delete **its own** ones, within the guardrails |
| `benchmarks:read` | Read runs, sweeps and comparisons |
| `benchmarks:run` | Start runs, A/B runs and sweeps on **its own** deployments; cancel its own |
Tokens created before 0.13 keep the scopes they had; grant new ones with **Scopes** next to the
token in Settings → API tokens.
A missing, unknown or revoked token gets `401`; a token without the needed scope gets `403`. The
settings page shows when each token was last used; **Revoke** stops it immediately.
Everything a token requests is marked with its name ("requested by hermes") on the model and job
pages and in the library, where you can filter by it.
## Errors
Errors are JSON with a message meant to be read and acted on:
```json
{ "error": { "code": "too_large", "message": "exceeds max size per request 60.0 GB: requested 74.2 GB. Pick a smaller quant or fewer files." } }
```
| Status | Codes |
| --- | --- |
| 400 | `invalid_request` (also unknown fields), `invalid_json`, `empty_selection` (quant or globs match nothing), `invalid_repo_id`, `invalid` |
| 401 / 403 | `unauthorized`, `forbidden` (scope), `author_not_allowed`, `gated_no_token`, `gated_no_access`, `runtime_not_allowed`, `arg_not_allowed`, `port_not_allowed`, `protected`, `not_owner` |
| 404 | `not_found`, `repo_not_found`, `revision_not_found` |
| 409 | `already_exists` (repo is in the library at another commit), `busy` (a model with an open job; a deployment that must be stopped first), `runtime_not_pulled`, `vram_protected`, `invalid` (e.g. benchmarking a stopped deployment) |
| 422 | `too_large`, `limit_exceeded`, `too_many_variants` |
| 429 | `too_many_jobs`, `too_many_deployments`, `gpu_busy`, `rate_limited` (Hugging Face) |
| 503 / 507 | `disk_unknown` (worker offline), `disk_space` |
Sizes appear as bytes plus a readable `"… GB"` field (decimal GB, like the Hub).
## Endpoints
### `GET /api/v1`
Any valid token. Who you are, your scopes, the current guardrails and the endpoint list.
```bash
curl -s -H "Authorization: Bearer $KANAME_TOKEN" "$KANAME_URL/api/v1"
```
```json
{
"token": { "name": "hermes", "scopes": ["models:read", "downloads:create"] },
"guardrails": { "approvalMode": "approve", "maxRequestBytes": 60000000000, "maxRequestSize": "60.0 GB",
"minFreeBytes": 100000000000, "minFreeSize": "100.0 GB", "maxOpenAgentJobs": 2, "allowedAuthors": [] },
"endpoints": ["…"]
}
```
### `GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]`
`models:read`. Resolves the revision to a commit SHA and lists quants and files, the same data as
the Add model dialog. `repo` may also be a Hub URL. Up to 200 files are listed unless `files=all`.
```json
{
"repoId": "unsloth/Qwen3-8B-GGUF", "revision": "main", "sha": "9e6855bc…", "gated": false,
"lastModified": "2026-05-01T10:00:00.000Z",
"inLibrary": null,
"quants": [{ "quant": "Q4_K_M", "files": 1, "bytes": 5027783488, "size": "5.0 GB" }, "…"],
"fileCount": 31, "totalBytes": 104000000000,
"files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "bytes": 5027783488 }, "…"],
"filesTruncated": false
}
```
`inLibrary` is `{ modelId, pinnedSha, status }` when the repo is already in Kaname.
### `GET /api/v1/models`
`models:read`. The library, filtered like the library page:
| Parameter | Meaning |
| --- | --- |
| `q` | Search text; every word must match (repo, author, family, quant, tags, …) |
| `author`, `family`, `quant`, `tag` | Facets; repeat or comma-separate values (OR within a facet, AND across) |
| `status` | `pending`, `downloading`, `ready`, `incomplete`, `failed`, `deleting`, `pending_approval`, `update_available`, `repo_missing`, `commit_missing` |
| `requested_by` | Token name |
```json
{ "count": 1, "models": [{ "id": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "status": "ready", "pendingApproval": false,
"pinnedSha": "9e68…", "quants": ["Q4_K_M"], "tags": ["agent"], "selectedFiles": 1, "selectedBytes": 5027783488,
"onDiskBytes": 5027783488, "onDisk": "5.0 GB", "updateAvailable": false, "hubState": "available",
"requestedBy": "hermes", "createdAt": "…", "downloadedAt": "…" }] }
```
### `GET /api/v1/models/{id}`
`models:read`. One model with its selected files (path, bytes, state) and latest job.
### `POST /api/v1/downloads`
`downloads:create`. Request a download of a repo **at a pinned commit**: take `sha` from the lookup.
| Field | |
| --- | --- |
| `repoId` | `"org/name"` |
| `sha` | Full 40-character commit SHA |
| `quant` | e.g. `"Q4_K_M"`: that quant's weight files (all split parts) plus the companion files ticked in Settings → Downloads (chat template, mmproj, …), as in the Add model dialog |
| `include` | Instead of `quant`: glob patterns, e.g. `["*.safetensors", "*.json"]` |
| `tags` | Optional user tags for the model |
| `revision` | Optional branch to track for update checks (default `main`) |
```bash
curl -s -X POST -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" \
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"9e6855bc…","quant":"Q4_K_M"}' \
"$KANAME_URL/api/v1/downloads"
```
```json
{ "created": true, "modelId": "01M…", "jobId": "01M…", "state": "pending_approval",
"requestedBytes": 5027783488, "requestedSize": "5.0 GB", "files": ["Qwen3-8B-Q4_K_M.gguf"],
"message": "Requested; waiting for the user to approve it in Kaname. Do not retry or poll; tell the user and stop." }
```
- **201**: a new job, `state` `pending_approval` (approval mode `approve`) or `queued` (`auto`).
- **200** with `"created": false`: the same repo, commit and files were requested before; you get the
existing model and its latest job. Nothing is queued twice.
- If the repo is already in the library at the same commit, the request adds the files that are
missing from its selection (only the added bytes count against the guardrails). At another commit
it is refused: updating a model is done in the UI.
It uses the same code path as the Add model dialog (the file list is fetched again from the Hub at
that commit; the client's list isn't trusted).
### `GET /api/v1/jobs/{id}[?wait=S][&log=N]`
`models:read`. Compact job state:
```json
{ "id": "01M…", "modelId": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "kind": "download", "purpose": "initial",
"state": "downloading", "cancelRequested": false, "requestedBy": "hermes",
"progress": { "doneBytes": 3000000000, "totalBytes": 5027783488, "percent": 59.7, "done": "3.0 GB", "total": "5.0 GB",
"speedBytesPerSecond": 52000000, "etaSeconds": 39 },
"error": null,
"files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "state": "downloading", "doneBytes": 3000000000, "totalBytes": 5027783488 }],
"createdAt": "…", "startedAt": "…", "finishedAt": null,
"next": "Downloading; check again in a minute." }
```
States: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `failed`, `cancelled`
(also when the user rejected the request), `interrupted`. The `hf` log is only included with
`?log=N` (the last N lines, at most 200). `?wait=S` returns once the job is finished (or right away
while it waits for approval); see [Waiting instead of polling](#waiting-instead-of-polling).
### `GET /api/v1/disk`
`models:read`. Space on the models folder, as reported by the worker every few seconds:
```json
{ "workerOnline": true, "freeBytes": 945600000000, "totalBytes": 2000000000000, "usedBytes": 1054400000000,
"reservedBytes": 105454144, "minFreeBytes": 100000000000, "availableForRequestsBytes": 845494545856,
"free": "945.6 GB", "total": "2000.0 GB", "availableForRequests": "845.5 GB" }
```
`reservedBytes` is what open downloads still have to fetch; `availableForRequests` is what a request
may use before hitting the minimum-free guardrail.
### Deployments
A deployment is a model served by a runtime container. Agents use the same validation, estimates and
`docker run` command as the UI; they can only edit, start, stop, delete and benchmark deployments their
own token created, and never [protected](#protected-deployments) ones.
#### `GET /api/v1/runtimes`
`deployments:read`. Runtimes with a pulled image: engine (`llama.cpp` or `vllm`), accelerator
(`cpu`, `nvidia`, `dri` for Intel/AMD), what they serve, whether agents may use them (`allowed`) and
the extra argument flags agents may pass (`allowedExtraArgs`); plus the host's GPUs.
#### `GET /api/v1/deployments[?mine=1]`, `GET /api/v1/deployments/{id}[?wait=S][&log=N]`
`deployments:read`. State (`stopped`, `pending_approval`, `starting`, `running`, `stopping`,
`failed`), `mine`, `protected`, runtime, model, options, limits, the endpoint inside the Docker
network, what the server reported once ready (version, slots, context), live CPU/RAM, error and a
`next` hint. `?wait=S` returns once it is running, stopped or failed (or right away while the start
waits for approval). `?log=N` adds the last N log lines (max 200).
#### `POST /api/v1/deployments`
`deployments:write`.
| Field | |
| --- | --- |
| `runtimeId`, `modelId` | From `GET /api/v1/runtimes` and `GET /api/v1/models` |
| `options` | The deployment form's launch options: `modelFile` (llama.cpp: the `.gguf`; vLLM: `""`), `contextSize`, `parallel`, `cacheTypeK`/`cacheTypeV`, `flashAttn`, `gpuLayers`, `batchSize`/`ubatchSize`, `maxNumSeqs`, `gpuMemoryUtilization`, … and `extraArgs` (only [allowed flags](#deployments-and-benchmarks)). Unknown fields are refused. |
| `cpus`, `memoryMb` | Optional limits within the caps; without `memoryMb` the estimate is used |
| `hostPort` | Optional, only inside the configured range (none by default) |
| `name` | Optional |
| `start` | Default `true`; with approval mode `approve` the start waits for the user |
| `dryRun` | `true`: only validate; returns the command and estimates, creates nothing |
```json
{ "created": true, "id": "01M…", "state": "pending_approval",
"command": "docker run -v <models>:/models:ro ghcr.io/ggml-org/llama.cpp:server-intel -m /models/… -c 16384 -ctk q8_0 …",
"estimates": { "memoryMb": 9800, "vramMb": 7900, "gpuVramMb": 32768 }, "limits": { "memoryMb": 9800, "cpus": null },
"message": "Created; the start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop." }
```
#### `PATCH /api/v1/deployments/{id}`, `POST …/start`, `POST …/stop`, `DELETE …`
`deployments:write`, own deployments only. `PATCH` takes `options` (merged into the current ones),
`cpus`, `memoryMb`, `hostPort`, `name`, and only while the deployment is stopped; it returns the new
command and estimates. `start` goes through the same guardrails as creating one (and approval);
`stop` and `DELETE` never need approval.
### Benchmarks
#### `POST /api/v1/benchmarks`
`benchmarks:run`. A [BetterBench](https://github.com/GGZ14/BetterBench) run against the token's own
**running** deployment.
| Field | |
| --- | --- |
| `kind` | `run` (default, BetterBench speed), `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) or `eval` (the [quality eval](#quality-eval)) |
| `deploymentId`, `deploymentBId` | Own, running deployments |
| `quick` | `true`: 5 passes, a smoke check; default `false`: 20 passes, comparable |
| `passes`, `phases` | Optional: passes per category; phases `decode`, `prefill`, `concurrency` (default all) |
| `label`, `description` | Optional; the description goes into the report and the launch80 preview |
| `sections` | `eval` only: `tools`, `coding`, `retrieval` (default all) |
Answers `201` with `state` `pending_approval` (default) or `queued`, and the run's time limit.
#### `GET /api/v1/benchmarks/{id}[?wait=S][&full=1]`, `GET /api/v1/benchmarks[?deployment=&requested_by=&limit=]`
`benchmarks:read`. Compact result:
```json
{ "id": "01M…", "kind": "run", "state": "completed", "label": "q8_0 KV", "mine": true,
"headline": { "decodeTps": 61.3, "prefillTps": 1840, "prefillDepth": 16000, "ttftMs": 92, "peakParallelTps": 155.2, "peakParallelLevel": 8 },
"setup": { "gpus": "1× Intel Arc Pro B65 (32 GiB)", "pcie": "Gen5 x8 of Gen5 x16", "p2p": "n/a", "rebar": "on",
"engine": "llama.cpp b11541-f2918cabb", "image": "ghcr.io/ggml-org/llama.cpp:server-intel", "digest": "sha256:…",
"model": "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache", "ctx": "16,384", "concurrency": "4" },
"resources": { "cpuAvgCores": 1.1, "ramPeakBytes": 2100000000,
"gpus": [{ "name": "Intel Arc Pro B65", "vramPeakMb": 9100, "vramTotalMb": 32768, "utilAvg": 88.5, "powerAvgW": 151.2, "tempPeakC": 71 }] },
"error": null, "next": "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…" }
```
`?full=1` adds BetterBench's complete summary (per category, per prompt depth, per concurrency
level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence interval). Eval runs
have `quality` instead of `headline`:
`{"evalSet": "kaname-eval-1", "score": 83.3, "sections": {"tools": "11/12", "coding": "6/8", "retrieval": "8/9"}}`,
and with `?full=1` the `failed` items with the reason.
`POST /api/v1/benchmarks/{id}/cancel` cancels an own run.
#### `GET /api/v1/benchmarks/compare?ids=a,b,…`
`benchmarks:read`. 2–16 runs: headline numbers side by side, the setup values that differ per run
(`differs`) and the ones they share (`same`).
#### `POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}[?wait=S]`, `POST /api/v1/sweeps/{id}/cancel`
`benchmarks:run` / `benchmarks:read`. One or two settings varied from an own base deployment, e.g.
`{"baseDeploymentId": "…", "params": [{"key": "kvCache", "values": ["f16", "q8_0"]}], "quick": true}`;
`"quality": true` also runs the quality eval on each variant.
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
`flashAttn`, `cacheRamMb`, `gpuLayers`, `dtype`, `maxNumSeqs`, `kvCacheGb`, `gpuMemoryUtilization`,
`cpus` (per engine, as in the UI). Each variant is deployed, benchmarked and removed again. The
answer lists every variant with its headline numbers and setup.
#### Quality eval
BetterBench measures speed only. `kind: "eval"` checks what a deployment answers, deterministically
(greedy decoding, temperature 0, fixed seed, thinking turned off where the chat template supports
it), so a quant, KV cache type or build that changes quality shows up next to the speed numbers:
| Section | Items | Passes when |
| --- | --- | --- |
| `tools` | 12 requests with 3 tools each | exactly one tool call, valid JSON arguments, the right function and the expected arguments |
| `coding` | 8 short Python functions | the answer's code passes its unit tests, run in a throwaway container (no network, read-only, unprivileged) |
| `retrieval` | a six-digit code hidden at 10 %, 50 % and 90 % depth in texts of 25 %, 50 % and 100 % of the context | the answer contains the code |
The score is the mean pass rate of the sections that could run (a server that refuses tool calls,
e.g. vLLM without a tool-call parser, doesn't count as 0). The eval set is versioned (`evalSet`);
only results of the same version compare.
## Waiting instead of polling
Every status call costs an agent a round of its context. The status endpoints (`/jobs/{id}`,
`/deployments/{id}`, `/benchmarks/{id}`, `/sweeps/{id}`) take `?wait=S` (seconds, at most 900): the
request is held until the state is settled (finished, running, failed, cancelled) or the time is up,
then answers with the current state plus `waitedSeconds` and `timedOut`. Something that waits for the
user's approval answers right away: there is nothing to wait for. Use one waiting call instead of a
polling loop, with a wait shorter than your HTTP client's timeout (and any proxy's).
## Guardrails
### Downloads
Settings → API tokens → **Guardrails for API downloads**. They apply to every token together;
downloads started in the UI aren't affected.
| Setting | Default | Rejection |
| --- | --- | --- |
| Approval | **Ask me**: requests wait as *pending approval* until you approve or reject them on the model or job page | (not an error; `state: pending_approval`) |
| Max size per request | 60 GB | `422 too_large` |
| Keep free on the models folder | 100 GB, after the download and after what other open downloads still need | `507 disk_space` (`503 disk_unknown` if the worker is offline) |
| Agent jobs at once | 2 (pending approval, queued or running) | `429 too_many_jobs` |
| Allowed authors | empty = any; e.g. `unsloth, ggml-org, Qwen` (case-insensitive) | `403 author_not_allowed` |
Rejecting a request cancels its job. A model that only that request added leaves the library again;
for a request that added files to an existing model, the previous selection is restored.
### Deployments and benchmarks
Settings → API tokens → **Guardrails for API deployments and benchmarks**, for every token together:
| Setting | Default | Rejection |
| --- | --- | --- |
| Approval | **Ask me**: starts, runs and sweeps wait as *pending approval* on the deployment, run or sweep page. Creating or editing a stopped deployment, stopping and deleting own ones need none. | (not an error) |
| Agent deployments at once | 1 (running, starting or waiting to start); 2 for A/B runs | `429 too_many_deployments` |
| One GPU job at a time | No agent start while an agent run or sweep is pending or running, or another agent deployment is still loading; one agent run or sweep at a time; no sweep while an agent deployment runs (the sweep deploys its variants itself) | `429 gpu_busy` |
| Max minutes per run / sweep | 30 / 180, then the worker stops it | (`failed` with the reason) |
| Max variants per sweep | 8 | `422 too_many_variants` |
| Runtimes | Any with a pulled image, or an allowlist | `403 runtime_not_allowed`, `409 runtime_not_pulled` |
| Extra arguments | Tuning flags only, per engine (editable list); values can't be paths or URLs | `403 arg_not_allowed`, naming the argument |
| Host ports | None (Kaname reaches deployments over the Docker network), or a range | `403 port_not_allowed` |
| Memory / CPU caps | The host's size, or what you set; agent deployments always get a memory limit (the estimate if they don't give one) | `422 limit_exceeded` |
| Own deployments only | Agents change and benchmark only what their token created | `403 not_owner` |
Docker options (devices, volumes, privileges, capabilities, network) are never arguments: they belong
to the runtime, which tokens can't change.
### Protected deployments
The **Protect** button on a deployment's page: agents can't edit, start, stop, delete or benchmark
it, and can't start a deployment on the same GPUs if the estimated VRAM of everything running there
plus the new one (and 1 GiB to spare) exceeds the GPUs' VRAM (`409 vram_protected`). When the need
can't be estimated (only some layers on the GPU), such a start is refused too.
### Activity
Settings → API tokens → **Activity** next to each token lists what it did: every request that
creates or changes something, waits for approval, or was refused (with the error code).
## Behind a forward-auth proxy (Traefik)
If Kaname sits behind forward auth (e.g. Traefik with Tinyauth or Pocket ID), the proxy would answer
API calls with a login redirect. Let `/api/v1/` through without forward auth; Kaname checks the
bearer token itself there. Everything else keeps forward auth.
Two routers for the same host, the API one with a higher priority and no auth middleware:
```yaml
# docker compose labels on the kaname "web" service
labels:
- traefik.enable=true
- traefik.http.services.kaname.loadbalancer.server.port=3000
# UI and internal API: forward auth as before
- traefik.http.routers.kaname.rule=Host(`models.example.com`)
- traefik.http.routers.kaname.entrypoints=websecure
- traefik.http.routers.kaname.tls=true
- traefik.http.routers.kaname.middlewares=tinyauth
- traefik.http.routers.kaname.service=kaname
# Token API: no forward auth (bearer tokens are checked by Kaname)
- traefik.http.routers.kaname-api.rule=Host(`models.example.com`) && PathPrefix(`/api/v1/`)
- traefik.http.routers.kaname-api.entrypoints=websecure
- traefik.http.routers.kaname-api.tls=true
- traefik.http.routers.kaname-api.priority=100
- traefik.http.routers.kaname-api.service=kaname
```
The same in a file provider:
```yaml
http:
routers:
kaname-api:
rule: Host(`models.example.com`) && PathPrefix(`/api/v1/`)
entryPoints: [websecure]
tls: {}
priority: 100
service: kaname
```
Notes:
- Use `PathPrefix(`/api/v1/`)` with the trailing slash, so nothing else that starts with `/api/v1`
slips past forward auth. Kaname's own login gate also excludes exactly `/api/v1` and `/api/v1/…`.
- Don't exempt `/api` as a whole: the internal routes rely on the login session.
- Agents on the same network can also call Kaname directly (`http://<host>:3000/api/v1/…`) without
going through the proxy.
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;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `models` ADD `base_relation` text;--> statement-breakpoint
ALTER TABLE `models` ADD `author_avatar_url` text;
+2
View File
@@ -0,0 +1,2 @@
-- Refetch Hub metadata once so existing models get author avatar and base relation.
UPDATE `models` SET `metadata_fetched_at` = NULL;
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE `settings` (
`key` text PRIMARY KEY NOT NULL,
`value` text NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `tags` ADD `color` text;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `models` ADD `hub_state` text;--> statement-breakpoint
ALTER TABLE `models` ADD `hub_missing_since` integer;
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE `local_folders` (
`path` text PRIMARY KEY NOT NULL,
`files` text NOT NULL,
`file_count` integer NOT NULL,
`total_bytes` integer NOT NULL,
`commit` text,
`scanned_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `worker_state` ADD `scan_requested_at` integer;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `jobs` ADD `result` text;--> statement-breakpoint
ALTER TABLE `models` ADD `update_diff` text;
+26
View File
@@ -0,0 +1,26 @@
CREATE TABLE `runtimes` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`engine` text NOT NULL,
`image` text NOT NULL,
`description` text,
`env` text DEFAULT '{}' NOT NULL,
`extra_args` text DEFAULT '[]' NOT NULL,
`devices` text DEFAULT '[]' NOT NULL,
`shm_size_mb` integer,
`numa_tuning` integer DEFAULT false NOT NULL,
`preset` text,
`image_state` text DEFAULT 'unknown' NOT NULL,
`image_id` text,
`image_size` integer,
`image_created` text,
`pull_requested_at` integer,
`pull_started_at` integer,
`pull_progress` text,
`pull_error` text,
`image_checked_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `worker_state` ADD `docker` text;
+37
View File
@@ -0,0 +1,37 @@
CREATE TABLE `deployment_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`deployment_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL,
FOREIGN KEY (`deployment_id`) REFERENCES `deployments`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `deployment_logs_idx` ON `deployment_logs` (`deployment_id`,`id`);--> statement-breakpoint
CREATE TABLE `deployments` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`runtime_id` text NOT NULL,
`model_id` text NOT NULL,
`options` text NOT NULL,
`cpus` real,
`memory_mb` integer,
`host_port` integer,
`desired_state` text DEFAULT 'stopped' NOT NULL,
`state` text DEFAULT 'stopped' NOT NULL,
`delete_requested_at` integer,
`container_id` text,
`container_name` text,
`command` text,
`image_id` text,
`started_at` integer,
`ready_at` integer,
`stopped_at` integer,
`exit_code` integer,
`error` text,
`stats` text,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`runtime_id`) REFERENCES `runtimes`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
+8
View File
@@ -0,0 +1,8 @@
CREATE TABLE `api_keys` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`key` text NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_keys_key_unique` ON `api_keys` (`key`);
+29
View File
@@ -0,0 +1,29 @@
CREATE TABLE `benchmark_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`run_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL
);
--> statement-breakpoint
CREATE INDEX `benchmark_logs_idx` ON `benchmark_logs` (`run_id`,`id`);--> statement-breakpoint
CREATE TABLE `benchmark_runs` (
`id` text PRIMARY KEY NOT NULL,
`deployment_id` text,
`model_id` text,
`tool` text DEFAULT 'betterbench' NOT NULL,
`settings` text NOT NULL,
`snapshot` text NOT NULL,
`label` text,
`state` text DEFAULT 'queued' NOT NULL,
`phase` text,
`cancel_requested_at` integer,
`started_at` integer,
`finished_at` integer,
`error` text,
`summary` text,
`has_report` integer DEFAULT false NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `benchmark_runs_created_idx` ON `benchmark_runs` (`created_at`);
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `runtimes` ADD `accelerator` text DEFAULT 'cpu' NOT NULL;
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE `benchmark_publications` (
`id` text PRIMARY KEY NOT NULL,
`run_id` text NOT NULL,
`state` text DEFAULT 'preview' NOT NULL,
`template` text DEFAULT 'bench.betterbench.v1' NOT NULL,
`title` text,
`summary` text,
`payload_bytes` integer,
`previewed_at` integer,
`confirmed_by` text,
`confirmed_at` integer,
`url` text,
`guid` text,
`published_at` integer,
`error` text,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `benchmark_publications_run_idx` ON `benchmark_publications` (`run_id`);
+23
View File
@@ -0,0 +1,23 @@
CREATE TABLE `benchmark_sweeps` (
`id` text PRIMARY KEY NOT NULL,
`label` text,
`base_deployment_id` text,
`base` text NOT NULL,
`params` text NOT NULL,
`settings` text NOT NULL,
`variants` text NOT NULL,
`state` text DEFAULT 'queued' NOT NULL,
`cancel_requested_at` integer,
`started_at` integer,
`finished_at` integer,
`error` text,
`created_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `kind` text DEFAULT 'run' NOT NULL;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `deployment_b_id` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `snapshot_b` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `ab` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `resources` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `sweep_id` text;--> statement-breakpoint
ALTER TABLE `deployments` ADD `sweep_id` text;
+17
View File
@@ -0,0 +1,17 @@
CREATE TABLE `api_tokens` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`prefix` text NOT NULL,
`hash` text NOT NULL,
`scopes` text NOT NULL,
`last_used_at` integer,
`revoked_at` integer,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_tokens_hash_unique` ON `api_tokens` (`hash`);--> statement-breakpoint
CREATE UNIQUE INDEX `api_tokens_name_uq` ON `api_tokens` (`name`);--> statement-breakpoint
ALTER TABLE `jobs` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `jobs` ADD `requested_by` text;--> statement-breakpoint
ALTER TABLE `models` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `models` ADD `requested_by` text;
+7
View File
@@ -0,0 +1,7 @@
ALTER TABLE `benchmark_runs` ADD `meta` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `meta_b` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `system` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `description` text;--> statement-breakpoint
ALTER TABLE `deployments` ADD `engine_info` text;--> statement-breakpoint
ALTER TABLE `runtimes` ADD `image_digest` text;--> statement-breakpoint
ALTER TABLE `runtimes` ADD `engine_name` text;
+25
View File
@@ -0,0 +1,25 @@
CREATE TABLE `agent_activity` (
`id` text PRIMARY KEY NOT NULL,
`token_id` text NOT NULL,
`token_name` text NOT NULL,
`action` text NOT NULL,
`target_type` text,
`target_id` text,
`outcome` text NOT NULL,
`code` text,
`message` text,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `agent_activity_token_idx` ON `agent_activity` (`token_id`,`created_at`);--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `requested_by` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `time_limit_s` integer;--> statement-breakpoint
ALTER TABLE `benchmark_sweeps` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `benchmark_sweeps` ADD `requested_by` text;--> statement-breakpoint
ALTER TABLE `benchmark_sweeps` ADD `time_limit_s` integer;--> statement-breakpoint
ALTER TABLE `benchmark_sweeps` ADD `run_time_limit_s` integer;--> statement-breakpoint
ALTER TABLE `deployments` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `deployments` ADD `requested_by` text;--> statement-breakpoint
ALTER TABLE `deployments` ADD `protected` integer DEFAULT false NOT NULL;--> statement-breakpoint
ALTER TABLE `deployments` ADD `start_requested_at` integer;
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `benchmark_runs` ADD `quality` text;
+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": {}
}
}
+908
View File
@@ -0,0 +1,908 @@
{
"version": "6",
"dialect": "sqlite",
"id": "024725ee-3ede-4d7d-85b0-52dfd38971f8",
"prevId": "9c67e3d1-730e-4c71-ac1e-2ec7d0d37dea",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"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": {}
}
}
+908
View File
@@ -0,0 +1,908 @@
{
"id": "0388c49a-d01a-4c5a-9694-0d844297213f",
"prevId": "024725ee-3ede-4d7d-85b0-52dfd38971f8",
"version": "6",
"dialect": "sqlite",
"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",
"columnsFrom": [
"job_id"
],
"tableTo": "jobs",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"columnsFrom": [
"model_file_id"
],
"tableTo": "model_files",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "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",
"columnsFrom": [
"job_id"
],
"tableTo": "jobs",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "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",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "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",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "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",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "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",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"columnsFrom": [
"tag_id"
],
"tableTo": "tags",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"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": {
"columns": {},
"schemas": {},
"tables": {}
},
"internal": {
"indexes": {}
}
}
+946
View File
@@ -0,0 +1,946 @@
{
"version": "6",
"dialect": "sqlite",
"id": "84e7c88b-53c4-4eba-8f2f-7de08b494316",
"prevId": "0388c49a-d01a-4c5a-9694-0d844297213f",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+960
View File
@@ -0,0 +1,960 @@
{
"version": "6",
"dialect": "sqlite",
"id": "4bf01375-42a2-440f-aeba-69644c7bca95",
"prevId": "84e7c88b-53c4-4eba-8f2f-7de08b494316",
"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
},
"hub_state": {
"name": "hub_state",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_missing_since": {
"name": "hub_missing_since",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+126
View File
@@ -22,6 +22,132 @@
"when": 1791210991713,
"tag": "0002_worker_lease",
"breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1791221700558,
"tag": "0003_model_metadata_and_tags",
"breakpoints": true
},
{
"idx": 4,
"version": "6",
"when": 1791223472733,
"tag": "0004_model_avatar_relation",
"breakpoints": true
},
{
"idx": 5,
"version": "6",
"when": 1791223474007,
"tag": "0005_refetch_metadata",
"breakpoints": true
},
{
"idx": 6,
"version": "6",
"when": 1791224932279,
"tag": "0006_settings_and_tag_color",
"breakpoints": true
},
{
"idx": 7,
"version": "6",
"when": 1791233230682,
"tag": "0007_hub_state",
"breakpoints": true
},
{
"idx": 8,
"version": "6",
"when": 1791233749207,
"tag": "0008_local_folders",
"breakpoints": true
},
{
"idx": 9,
"version": "6",
"when": 1791238659338,
"tag": "0009_verify_update",
"breakpoints": true
},
{
"idx": 10,
"version": "6",
"when": 1791242201063,
"tag": "0010_runtimes",
"breakpoints": true
},
{
"idx": 11,
"version": "6",
"when": 1791278463453,
"tag": "0011_deployments",
"breakpoints": true
},
{
"idx": 12,
"version": "6",
"when": 1791281615301,
"tag": "0012_api_keys",
"breakpoints": true
},
{
"idx": 13,
"version": "6",
"when": 1791654372298,
"tag": "0013_benchmarks",
"breakpoints": true
},
{
"idx": 14,
"version": "6",
"when": 1791655909335,
"tag": "0014_runtime_accelerator",
"breakpoints": true
},
{
"idx": 15,
"version": "6",
"when": 1791657884019,
"tag": "0015_benchmark_publications",
"breakpoints": true
},
{
"idx": 16,
"version": "6",
"when": 1791658947930,
"tag": "0016_ab_resources_sweeps",
"breakpoints": true
},
{
"idx": 17,
"version": "6",
"when": 1792504668583,
"tag": "0017_api_tokens",
"breakpoints": true
},
{
"idx": 18,
"version": "6",
"when": 1792513935880,
"tag": "0018_benchmark_metadata",
"breakpoints": true
},
{
"idx": 19,
"version": "6",
"when": 1792587768766,
"tag": "0019_agent_tuning",
"breakpoints": true
},
{
"idx": 20,
"version": "6",
"when": 1792588720328,
"tag": "0020_quality_eval",
"breakpoints": true
}
]
}
+1708 -5
View File
File diff suppressed because it is too large. Load diff
+7 -2
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.3.1",
"version": "0.14.2",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -13,7 +13,7 @@
"typecheck": "next typegen && tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
"test": "tsx --test \"src/**/*.test.ts\"",
"test": "tsx --conditions=react-server --test \"src/**/*.test.ts\"",
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs"
},
"dependencies": {
@@ -28,6 +28,10 @@
"next-themes": "^0.4.6",
"react": "19.2.8",
"react-dom": "19.2.8",
"react-markdown": "^10.1.0",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.1",
"server-only": "^0.0.1",
"shadcn": "^4.21.1",
"sonner": "^2.0.8",
@@ -37,6 +41,7 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tailwindcss/typography": "^0.5.20",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Read-only diagnostics for Intel GPU support (Arc / Arc Pro B-series) on a Kaname host.
# Shows which telemetry sources this kernel and driver offer, so Kaname uses ones that exist.
# Changes nothing. Run it on the Docker host (or VM) that has the GPU:
#
# bash scripts/intel-probe.sh # as your user: what an unprivileged container can see
# sudo bash scripts/intel-probe.sh # adds lspci's link/ReBAR capability details
#
# Paste the output back. It contains no hostname, IP addresses or user names.
set -u
section() { printf '\n=== %s ===\n' "$1"; }
show() { [ -e "$1" ] && printf '%s: %s\n' "$1" "$(tr '\n' ' ' < "$1" 2>/dev/null || echo '(not readable)')"; }
section "System"
echo "kernel: $(uname -r)"
grep -E '^(PRETTY_NAME|VERSION_ID)=' /etc/os-release 2>/dev/null
command -v systemd-detect-virt >/dev/null && echo "virt: $(systemd-detect-virt 2>/dev/null)"
show /sys/class/dmi/id/sys_vendor
show /sys/class/dmi/id/product_name
echo "running as uid $(id -u)"
section "Intel display devices"
gpus=()
for d in /sys/bus/pci/devices/*; do
[ "$(cat "$d/vendor" 2>/dev/null)" = "0x8086" ] || continue
case "$(cat "$d/class" 2>/dev/null)" in 0x03*) gpus+=("$(basename "$d")") ;; esac
done
[ ${#gpus[@]} -eq 0 ] && echo "no Intel GPU found on the PCI bus"
for a in "${gpus[@]}"; do
d=$(readlink -f "/sys/bus/pci/devices/$a")
section "GPU $a"
echo "sysfs path: $d"
show "$d/device"
show "$d/subsystem_device"
echo "driver: $(basename "$(readlink "$d/driver" 2>/dev/null)" 2>/dev/null)"
command -v lspci >/dev/null && lspci -nn -s "$a"
echo "-- link per level (GPU up to the root port):"
p=$d
while [[ $(basename "$p") =~ ^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$ ]]; do
printf '%s vendor=%s cur=%s x%s max=%s x%s\n' "$(basename "$p")" "$(cat "$p/vendor" 2>/dev/null)" \
"$(cat "$p/current_link_speed" 2>/dev/null)" "$(cat "$p/current_link_width" 2>/dev/null)" \
"$(cat "$p/max_link_speed" 2>/dev/null)" "$(cat "$p/max_link_width" 2>/dev/null)"
p=$(dirname "$p")
done
echo "-- BARs (start end flags):"
head -6 "$d/resource" 2>/dev/null
echo "-- VRAM / memory files:"
find "$d" -maxdepth 3 \( -iname '*vram*' -o -iname '*lmem*' -o -iname '*mem_info*' \) 2>/dev/null | while read -r f; do
[ -f "$f" ] && show "$f"
done
ls "$d/tile0" 2>/dev/null | head -30
echo "-- hwmon:"
for h in "$d"/hwmon/hwmon*; do
[ -d "$h" ] || continue
show "$h/name"
for f in "$h"/*_input "$h"/*_label "$h"/*_crit "$h"/power*_max; do [ -f "$f" ] && show "$f"; done
done
if [ "$(id -u)" = 0 ] && command -v lspci >/dev/null; then
echo "-- lspci capabilities:"
lspci -vvv -s "$a" | grep -E 'LnkCap:|LnkSta:|Resizable BAR|BAR [0-9]: current size|Region'
fi
done
section "/dev/dri"
ls -ln /dev/dri 2>/dev/null
for n in /dev/dri/renderD*; do [ -e "$n" ] && echo "$n gid=$(stat -c %g "$n") group=$(stat -c %G "$n")"; done
getent group render video | cut -d: -f1,3
section "DRM fdinfo (per-process VRAM / engine time)"
found=0
for f in /proc/[0-9]*/fdinfo/*; do
grep -q '^drm-driver:' "$f" 2>/dev/null || continue
found=1
echo "readable example: $f"
grep -E '^drm-(driver|client-id|engine-|cycles-|total-cycles-|memory-|total-|resident-)' "$f" | head -25
break
done
[ $found = 0 ] && echo "no readable DRM fdinfo (no GPU process running, or not permitted for this user)"
section "Tools"
for t in xpu-smi intel_gpu_top clinfo sycl-ls vulkaninfo docker; do
printf '%s: %s\n' "$t" "$(command -v "$t" || echo missing)"
done
command -v docker >/dev/null && docker version --format 'docker server {{.Server.Version}}' 2>/dev/null
@@ -0,0 +1,99 @@
"use client";
import { Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
/**
* Delete a model, whatever its state (failed, incomplete, ready, …). By default its files are
* deleted from disk too (by the worker); unchecked, only the library entry goes.
*/
export function DeleteModelButton({
id,
repoId,
localPath,
mayHaveFiles,
}: {
id: string;
repoId: string;
localPath: string;
/** False if nothing was ever downloaded, so there's nothing on disk to ask about. */
mayHaveFiles: boolean;
}) {
const router = useRouter();
const [deleteFiles, setDeleteFiles] = useState(true);
const [pending, setPending] = useState(false);
async function remove() {
setPending(true);
const res = await fetch(`/api/models/${id}${mayHaveFiles && deleteFiles ? "?files=1" : ""}`, { method: "DELETE" });
if (res.ok) {
toast.success(res.status === 202 ? `Deleting ${repoId} and its files…` : `${repoId} removed from the library`);
router.push("/");
router.refresh();
} else {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Delete failed (${res.status})`);
setPending(false);
}
}
return (
<AlertDialog>
<AlertDialogTrigger
render={
<Button
variant="outline"
size="sm"
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
/>
}
>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {repoId}?</AlertDialogTitle>
<AlertDialogDescription>
{mayHaveFiles
? "The model is removed from the library, including its tags and job history."
: "Nothing was downloaded yet, so this only removes the library entry."}
</AlertDialogDescription>
</AlertDialogHeader>
{mayHaveFiles && (
<label className="flex cursor-pointer items-start gap-2.5 rounded-md bg-muted/50 px-3 py-2.5 text-sm">
<Checkbox checked={deleteFiles} onCheckedChange={(v) => setDeleteFiles(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>Also delete the files from disk</span>
<span className="text-xs text-muted-foreground">
Deletes the repo&apos;s files in <code className="font-mono">{localPath}</code>. Files you put there yourself are
kept. Unchecked, the folder stays and shows up under &ldquo;Found in the models folder&rdquo;.
</span>
</span>
</label>
)}
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove} disabled={pending}>
{mayHaveFiles && deleteFiles ? "Delete with files" : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
@@ -0,0 +1,176 @@
"use client";
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ApprovalBar } from "@/components/approval-bar";
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { VerifyResult } from "@/components/verify-result";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { groupJobFiles } from "@/lib/file-groups";
import { formatBytes, percent } from "@/lib/format";
import { jobLabel } from "@/lib/job-labels";
const OPEN = ["queued", "downloading", "verifying"];
const VERIFY_KINDS = ["verify", "deep_verify"];
/** Sidebar card: current job with progress, the last verify result, and the model's actions. */
export function DownloadCard({
modelId,
status,
hubMissing,
}: {
modelId: string;
status: ModelStatus;
/** The repo or pinned commit is gone from the Hub; no new downloads. */
hubMissing: boolean;
}) {
const { snapshot } = useLive({ model: modelId });
const [busy, setBusy] = useState(false);
const jobs = snapshot?.jobs ?? [];
const latest = jobs[0];
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const pending = latest?.state === "pending_approval" ? latest : undefined;
const router = useRouter();
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
// The newest verify, unless a download ran after it (its result would be stale).
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
const verify = lastCheck && VERIFY_KINDS.includes(lastCheck.kind) && lastCheck.state === "completed" ? lastCheck : undefined;
const verifyProblems = verify?.result
? (verify.result.missing?.length ?? 0) + (verify.result.sizeMismatch?.length ?? 0) + (verify.result.hashMismatch?.length ?? 0)
: 0;
async function run(fn: () => Promise<unknown>) {
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
}
const neverRan = jobs.length === 0;
const downloadLabel = neverRan
? "Download"
: latest?.state === "interrupted" || latest?.state === "cancelled"
? "Resume"
: latest?.state === "failed" && latest.kind === "download"
? "Retry"
: "Download missing";
const canDownload = !open && !pending && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
const canVerify = !open && !pending && !neverRan && status !== "deleting" && !!snapshot;
const needsRepair = !open && !pending && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
let hint = "Downloads the selected files at the pinned commit.";
if (pending) hint = "Requested through the API; waits for your approval.";
else if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
else if (open) hint = "Runs in the background; you can close this page.";
else if (status === "deleting") hint = "Deleting…";
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
else if (status === "ready") hint = "All selected files are present.";
const showProgress =
latest && latest.kind !== "delete" && !(latest.state === "completed" && (status === "ready" || VERIFY_KINDS.includes(latest.kind)));
return (
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-2">
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
<DownloadIcon className="size-4 text-muted-foreground" />
{open ? jobLabel(open) : "Download"}
</h3>
{latest && <JobStateBadge job={latest} />}
</div>
<p className="text-xs text-muted-foreground">{hint}</p>
{pending && <ApprovalBar job={pending} onRemoved={() => router.push("/")} />}
{showProgress && !pending && <JobProgress job={latest} compact />}
{latest?.state === "failed" && latest.errorMessage && (
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
{latest.errorMessage}
</pre>
)}
{files.length > 0 && (
<ul className="flex flex-col gap-1.5">
{files.map((f) => (
<li key={f.path} className="flex flex-col gap-1">
<div className="flex justify-between gap-2 text-xs">
<span className="truncate font-mono" title={f.path}>
{f.path}
{f.parts > 1 && <span className="text-muted-foreground"> · {f.parts} parts</span>}
</span>
<span className="shrink-0 text-muted-foreground tabular-nums">{formatBytes(f.expectedBytes)}</span>
</div>
<Progress value={percent(f.doneBytes, f.expectedBytes)} />
</li>
))}
</ul>
)}
{verify?.result && !open && (
<div className="rounded-md bg-muted/50 px-2.5 py-2">
<VerifyResult result={verify.result} deep={verify.kind === "deep_verify"} />
</div>
)}
<div className="flex flex-wrap gap-2">
{open ? (
<Button variant="destructive" size="sm" disabled={busy || open.cancelRequested} onClick={() => run(() => cancelJob(open.id))}>
{open.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
<>
{needsRepair ? (
<Button size="sm" disabled={busy} onClick={() => run(() => startRepair(modelId))}>
<WrenchIcon />
Repair
</Button>
) : (
canDownload && (
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
{downloadLabel}
</Button>
)
)}
{canVerify && (
<>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => run(() => startVerify(modelId, false))}
title="Check that every selected file exists with the right size (seconds)"
>
<ShieldCheckIcon />
Verify
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => run(() => startVerify(modelId, true))}
title="Hash every file and compare with the Hub (slow: reads every byte)"
>
Deep verify
</Button>
</>
)}
</>
)}
{latest && latest.kind !== "delete" && (
<Link href={`/jobs/${latest.id}`} className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted">
View log
</Link>
)}
</div>
</div>
);
}
@@ -0,0 +1,241 @@
"use client";
import { PlusIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
type Candidate = { path: string; size: number };
/**
* Files tab header: selection summary + on-disk progress, and a "Download more" panel to add
* files that aren't selected yet.
*/
export function FilesHeader({
modelId,
sha,
selectedCount,
totalBytes,
localCount,
localBytes,
candidates,
selectedPaths,
freeBytes,
busy,
hubMissing,
}: {
modelId: string;
sha: string;
selectedCount: number;
totalBytes: number;
localCount: number;
localBytes: number;
candidates: Candidate[];
/** Files the model already has selected (no second mmproj/MTP is recommended). */
selectedPaths: string[];
freeBytes: number | null;
/** A download is queued/running; adding files has to wait. */
busy: boolean;
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
hubMissing: boolean;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [submitting, setSubmitting] = useState(false);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
for (const c of candidates) {
const g = quantGroup(c.path);
if (!g) continue;
const entry = m.get(g) ?? { paths: [], size: 0 };
entry.paths.push(c.path);
entry.size += c.size;
m.set(g, entry);
}
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [candidates]);
// Companions (template, MTP, mmproj, …) of newly picked model files come along.
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(candidates, picked, { have: selectedPaths });
const chosen = useMemo(() => new Set([...picked, ...recActive]), [picked, recActive]);
// Split files are one entry; its checkbox selects all parts.
const entries = useMemo(() => groupSplitFiles(candidates), [candidates]);
const pickedEntries = entries.filter((e) => e.parts.every((p) => chosen.has(p.path))).length;
const pickedBytes = candidates.filter((c) => chosen.has(c.path)).reduce((s, c) => s + c.size, 0);
const tooBig = freeBytes != null && pickedBytes > freeBytes;
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setPicked((prev) => {
const next = new Set(prev);
for (const p of paths) {
if (on) next.add(p);
else next.delete(p);
}
return next;
});
}
async function submit() {
setSubmitting(true);
try {
const res = await fetch(`/api/models/${modelId}/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ add: [...chosen] }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not add files (${res.status})`);
return;
}
toast.success(`${body.added} file${body.added === 1 ? "" : "s"} added, download queued`);
setOpen(false);
setPicked(new Set());
resetRecommended();
router.refresh();
} finally {
setSubmitting(false);
}
}
return (
<div className="border-b">
<div className="flex flex-col gap-2 px-5 py-4">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-sm">
<span>
<span className="font-medium">
{selectedCount} selected file{selectedCount === 1 ? "" : "s"}
</span>
<span className="text-muted-foreground">
{" "}
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
</span>
</span>
<div className="flex items-center gap-3">
<span className="text-muted-foreground">
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
</span>
{candidates.length > 0 && !hubMissing && (
<Button
size="sm"
variant={open ? "outline" : "default"}
onClick={() => setOpen((o) => !o)}
disabled={busy && !open}
title={busy ? "Wait until the current download has finished" : undefined}
>
{open ? (
"Close"
) : (
<>
<PlusIcon /> Download more
</>
)}
</Button>
)}
</div>
</div>
<Progress value={percent(localBytes, totalBytes)} />
</div>
{open && (
<div className="border-t bg-muted/30">
{groups.length > 0 && (
<div className="flex flex-col gap-1.5 px-5 pt-4">
<span className="text-xs text-muted-foreground">Quick select</span>
<div className="flex flex-wrap gap-1.5">
{groups.map(([name, g]) => {
const on = g.paths.every((p) => picked.has(p));
return (
<Button
key={name}
type="button"
size="xs"
variant={on ? "default" : "outline"}
onClick={() => toggle(g.paths, !on)}
title={g.paths.join("\n")}
>
{name}
<span className="opacity-70">{formatBytes(g.size)}</span>
</Button>
);
})}
</div>
</div>
)}
<RecommendedStrip files={candidates} paths={recAll} active={recActive} onToggle={toggle} className="mx-5 mt-3" />
<ul className="mt-3 max-h-96 divide-y overflow-y-auto border-y bg-card">
{entries.map((e) => {
const paths = e.parts.map((p) => p.path);
const on = paths.every((p) => chosen.has(p));
const isRecommended = paths.every((p) => recAll.includes(p));
return (
<li key={e.path}>
<label className="grid cursor-pointer grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2 hover:bg-muted/50">
<Checkbox checked={on} onCheckedChange={(v) => toggle(paths, v === true)} />
<FileRoleBadge path={e.path} />
<span className="flex min-w-0 items-center gap-2" title={paths.join("\n")}>
<span className="truncate font-mono text-[13px]">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
</span>
<span className="text-right text-sm text-muted-foreground tabular-nums">{formatBytes(e.size)}</span>
</label>
</li>
);
})}
</ul>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-3 text-sm">
<span>
<span className="font-medium">
{pickedEntries} file{pickedEntries === 1 ? "" : "s"} · {formatBytes(pickedBytes)}
</span>
{freeBytes != null && (
<span className={tooBig ? "text-destructive" : "text-muted-foreground"}>
{" "}
({formatBytes(freeBytes)} free)
</span>
)}
</span>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" onClick={() => {
setPicked(new Set());
resetRecommended();
}}
disabled={chosen.size === 0}
>
Clear
</Button>
<Button size="sm" onClick={submit} disabled={chosen.size === 0 || submitting || busy}>
{submitting ? "Adding…" : pickedEntries === 0 ? "Download" : `Download ${pickedEntries} file${pickedEntries === 1 ? "" : "s"}`}
</Button>
</div>
</div>
</div>
)}
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
import {
AlertTriangleIcon,
BoxIcon,
CheckCircle2Icon,
ChevronRightIcon,
CircleDashedIcon,
FileIcon,
FileImageIcon,
FileJsonIcon,
FileTextIcon,
ShieldCheckIcon,
XCircleIcon,
} from "lucide-react";
import { FileRoleBadge } from "@/components/labels";
import type { ModelFileState } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { type FileGroup, groupSplitFiles } from "@/lib/file-groups";
import { cn } from "@/lib/utils";
import { FilesHeader } from "./download-more";
type FileRow = { id: string; path: string; size: number; lfsSha256: string | null; state: ModelFileState };
const STATE: Record<ModelFileState, { label: string; icon: React.ReactNode; className: string }> = {
pending: { label: "Not downloaded", icon: <CircleDashedIcon className="size-3.5" />, className: "text-muted-foreground" },
present: { label: "Downloaded", icon: <CheckCircle2Icon className="size-3.5" />, className: "text-emerald-600 dark:text-emerald-400" },
verified: { label: "Verified", icon: <ShieldCheckIcon className="size-3.5" />, className: "text-emerald-600 dark:text-emerald-400" },
missing: { label: "Missing", icon: <XCircleIcon className="size-3.5" />, className: "text-destructive" },
size_mismatch: { label: "Size mismatch", icon: <AlertTriangleIcon className="size-3.5" />, className: "text-amber-600 dark:text-amber-400" },
hash_mismatch: { label: "Hash mismatch", icon: <AlertTriangleIcon className="size-3.5" />, className: "text-amber-600 dark:text-amber-400" },
};
function FileTypeIcon({ path }: { path: string }) {
const ext = path.toLowerCase().split(".").pop() ?? "";
const cls = "size-4 text-muted-foreground";
if (["gguf", "safetensors", "bin", "pt", "onnx"].includes(ext)) return <BoxIcon className={cls} />;
if (ext === "json") return <FileJsonIcon className={cls} />;
if (["md", "txt"].includes(ext)) return <FileTextIcon className={cls} />;
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext)) return <FileImageIcon className={cls} />;
return <FileIcon className={cls} />;
}
function FileName({ path }: { path: string }) {
const slash = path.lastIndexOf("/");
return (
<span className="min-w-0 truncate font-mono text-[13px]" title={path}>
{slash >= 0 && <span className="text-muted-foreground">{path.slice(0, slash + 1)}</span>}
{path.slice(slash + 1)}
</span>
);
}
type Entry = FileGroup<FileRow>;
/** One status for a whole entry (all parts of a split file). */
function entryState(e: Entry): { state: ModelFileState; label: string } {
const states = e.parts.map((p) => p.state);
const done = states.filter((st) => st === "present" || st === "verified").length;
const worst = (["missing", "hash_mismatch", "size_mismatch"] as const).find((st) => states.includes(st));
if (worst) return { state: worst, label: STATE[worst].label };
if (done === states.length) {
const state = states.every((st) => st === "verified") ? "verified" : "present";
return { state, label: STATE[state].label };
}
if (done > 0) return { state: "pending", label: `${done} of ${states.length} parts` };
return { state: "pending", label: STATE.pending.label };
}
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
function Row({ entry, href, muted, showState }: { entry: Entry; href: string; muted?: boolean; showState: boolean }) {
const { state: stateKey, label } = entryState(entry);
const state = STATE[stateKey];
const split = entry.totalParts > 1;
return (
<li>
<a
href={href}
target="_blank"
rel="noreferrer"
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
className={cn(
// Fixed status column so sizes line up between selected and unselected rows.
"grid grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_7.5rem]",
muted && "text-muted-foreground",
)}
>
<FileTypeIcon path={entry.path} />
<FileRoleBadge path={entry.path} className={muted ? "opacity-70" : undefined} />
<span className="flex min-w-0 items-center gap-2">
<FileName path={entry.path} />
{split && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{entry.parts.length === entry.totalParts
? `${entry.totalParts} parts`
: `${entry.parts.length} of ${entry.totalParts} parts`}
</span>
)}
{entry.parts[0].lfsSha256 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">LFS</span>
)}
</span>
<span className="hidden text-right text-sm tabular-nums sm:block">{formatBytes(entry.size)}</span>
{showState ? (
<span className={cn("flex items-center justify-end gap-1.5 text-xs whitespace-nowrap", state.className)}>
{state.icon}
<span className="hidden md:inline">{label}</span>
</span>
) : (
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(entry.size)}</span>
)}
</a>
</li>
);
}
/** "Files and versions"-style list: selected files with their local state, the rest collapsed. */
export function FilesTab({
modelId,
repoId,
sha,
selected,
others,
freeBytes,
busy,
hubMissing,
}: {
modelId: string;
repoId: string;
sha: string;
selected: FileRow[];
others: FileRow[];
freeBytes: number | null;
busy: boolean;
hubMissing: boolean;
}) {
const hub = `https://huggingface.co/${repoId}`;
// Split files link to their folder (all parts), single files to the file itself.
const href = (e: Entry) => {
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
};
const selectedEntries = groupSplitFiles(selected);
const otherEntries = groupSplitFiles(others);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const localEntries = selectedEntries.filter(isLocal);
const localBytes = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
return (
<div>
<FilesHeader
modelId={modelId}
sha={sha}
selectedCount={selectedEntries.length}
totalBytes={totalBytes}
localCount={localEntries.length}
localBytes={localBytes}
candidates={others.map((f) => ({ path: f.path, size: f.size }))}
selectedPaths={selected.map((f) => f.path)}
freeBytes={freeBytes}
busy={busy}
hubMissing={hubMissing}
/>
<ul className="divide-y">
{selectedEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} showState />
))}
</ul>
{otherEntries.length > 0 && (
<details className="group border-t">
<summary className="flex cursor-pointer list-none items-center gap-2 px-5 py-3 text-sm hover:bg-muted/50">
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-open:rotate-90" />
<span className="font-medium">Not selected</span>
<span className="text-muted-foreground">
{otherEntries.length} file{otherEntries.length === 1 ? "" : "s"} ·{" "}
{formatBytes(others.reduce((s, f) => s + f.size, 0))}
</span>
</summary>
<ul className="divide-y border-t">
{otherEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} muted showState={false} />
))}
</ul>
</details>
)}
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { RefreshCwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/** Check the Hub right now: repo and pinned commit still there, newer commit on the tracked revision. */
export function HubCheckButton({ modelId, label = "Check now" }: { modelId: string; label?: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function check() {
setBusy(true);
try {
const res = await fetch(`/api/models/${modelId}/hub-check`, { method: "POST" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Check failed (${res.status})`);
else if (json.state === "available" && json.update) toast.info("Update available");
else if (json.state === "available") toast.success(json.warning ?? "Up to date");
else if (json.state === "repo_missing") toast.warning("The repo is no longer on Hugging Face");
else if (json.state === "commit_missing") toast.warning("The pinned commit is no longer on Hugging Face");
else toast.error(`Could not check: ${json.error ?? "unknown error"}`);
router.refresh();
} finally {
setBusy(false);
}
}
return (
<Button variant="ghost" size="xs" onClick={check} disabled={busy}>
<RefreshCwIcon className={cn(busy && "animate-spin")} />
{label}
</Button>
);
}
+53
View File
@@ -0,0 +1,53 @@
"use client";
import Link from "next/link";
import { JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import { formatBytes } from "@/lib/format";
import { jobLabel } from "@/lib/job-labels";
/** Job history of one model (live). */
export function JobsTab({ modelId }: { modelId: string }) {
const { snapshot } = useLive({ model: modelId });
const jobs = snapshot?.jobs ?? [];
if (snapshot && jobs.length === 0) {
return <p className="py-6 text-sm text-muted-foreground">No jobs yet.</p>;
}
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Started</TableHead>
<TableHead>Kind</TableHead>
<TableHead>State</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden sm:table-cell">Finished</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<Link href={`/jobs/${j.id}`} className="hover:underline">
<LocalTime value={j.startedAt ?? j.createdAt} />
</Link>
</TableCell>
<TableCell className="text-sm">
{jobLabel(j)}
</TableCell>
<TableCell>
<JobStateBadge job={j} />
</TableCell>
<TableCell className="text-right text-sm tabular-nums">{formatBytes(j.totalBytes)}</TableCell>
<TableCell className="hidden text-sm text-muted-foreground sm:table-cell">
<LocalTime value={j.finishedAt} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
+49
View File
@@ -0,0 +1,49 @@
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkGfm from "remark-gfm";
// Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts,
// styles or event handlers, only the tags/attributes GitHub-style READMEs normally use.
const schema = {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
img: [...(defaultSchema.attributes?.img ?? []), "width", "height", "align", "loading"],
div: [...(defaultSchema.attributes?.div ?? []), "align"],
p: [...(defaultSchema.attributes?.p ?? []), "align"],
td: [...(defaultSchema.attributes?.td ?? []), "align"],
th: [...(defaultSchema.attributes?.th ?? []), "align"],
},
};
/** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
const base = `https://huggingface.co/${repoId}`;
return (
<article className="prose prose-sm max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-img:inline-block prose-img:my-1 prose-pre:bg-muted prose-pre:text-foreground prose-table:text-xs">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw, [rehypeSanitize, schema]]}
urlTransform={(url, key) => {
const safe = defaultUrlTransform(url);
if (!safe || safe.startsWith("#") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(safe)) return safe;
// Relative path inside the repo: images from /resolve, links to /blob, both at the pinned SHA.
const path = safe.replace(/^\.?\//, "");
return key === "src" ? `${base}/resolve/${sha}/${path}` : `${base}/blob/${sha}/${path}`;
}}
components={{
a: ({ href, children, ...props }) => (
<a href={href} {...props} target={href?.startsWith("#") ? undefined : "_blank"} rel="noreferrer">
{children}
</a>
),
// eslint-disable-next-line @next/next/no-img-element
img: ({ alt, ...props }) => <img alt={alt ?? ""} loading="lazy" referrerPolicy="no-referrer" {...props} />,
}}
>
{markdown}
</ReactMarkdown>
</article>
);
}
+528
View File
@@ -0,0 +1,528 @@
import {
ArrowDownIcon,
BoxIcon,
CpuIcon,
ExternalLinkIcon,
FileTextIcon,
FolderIcon,
HistoryIcon,
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
PlusIcon,
RocketIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
} from "lucide-react";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
import { getModelByRepo, relatedModels } from "@/lib/library";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
import { modelTagList } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
import { DownloadCard } from "./download-card";
import { FilesTab } from "./files-tab";
import { HubCheckButton } from "./hub-check";
import { JobsTab } from "./jobs-tab";
import { ModelCard } from "./model-card";
import { DeleteModelButton } from "./delete-model-button";
import { TagEditor } from "./tag-editor";
import { UpdateBanner } from "./update-banner";
export const dynamic = "force-dynamic";
const TABS = [
{ id: "files", label: "Files", icon: FolderIcon },
{ id: "card", label: "Model card", icon: FileTextIcon },
{ id: "jobs", label: "Jobs", icon: HistoryIcon },
] as const;
type TabId = (typeof TABS)[number]["id"];
const FORMATS: Record<string, string> = {
gguf: "GGUF",
safetensors: "Safetensors",
transformers: "Transformers",
pytorch: "PyTorch",
onnx: "ONNX",
mlx: "MLX",
};
const RELATION_LABEL: Record<string, string> = {
quantized: "Quantized",
finetune: "Finetuned",
adapter: "Adapter",
merge: "Merged",
};
const titleCase = (s: string) => s.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
function languageName(code: string): string | null {
if (!/^[a-z]{2,3}$/.test(code)) return null;
try {
const name = new Intl.DisplayNames(["en"], { type: "language" }).of(code);
return name && name !== code ? name : null;
} catch {
return null;
}
}
export async function generateMetadata({ params }: PageProps<"/[org]/[repo]">): Promise<Metadata> {
const { org, repo } = await params;
return { title: `${org}/${repo}` };
}
export default async function ModelPage({ params, searchParams }: PageProps<"/[org]/[repo]">) {
const { org, repo } = await params;
const sp = await searchParams;
const data = await getModelByRepo(`${org}/${repo}`);
if (!data) notFound();
const { model, files } = data;
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
const tab: TabId = TABS.some((t) => t.id === sp.tab) ? (sp.tab as TabId) : "files";
const [author, name] = model.repoId.split("/");
const hub = `https://huggingface.co/${model.repoId}`;
const baseModels = model.baseModels ?? [];
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
deploymentsByModel(),
listDeployableModels(),
]);
const modelDeployments = byModel.get(model.id) ?? [];
const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
: null;
const selected = files.filter((f) => f.selected);
const others = files.filter((f) => !f.selected);
const selectedBytes = selected.reduce((s, f) => s + f.size, 0);
const quants = [
...new Set(selected.filter((f) => fileRole(f.path) === "model").map((f) => quantGroup(f.path)).filter(Boolean)),
] as string[];
const formats = hubTags.filter((t) => FORMATS[t]).map((t) => FORMATS[t]);
const languages = hubTags.map(languageName).filter(Boolean) as string[];
const shown = new Set([...Object.keys(FORMATS), model.architecture, author.toLowerCase(), model.pipelineTag]);
const extraTags = hubTags.filter((t) => !shown.has(t) && !languageName(t)).slice(0, 8);
const tabHref = (id: TabId) => (id === "files" ? `/${model.repoId}` : `/${model.repoId}?tab=${id}`);
return (
<div className="flex flex-col gap-4">
{/* Header card, styled after the Hugging Face model page */}
<Panel className="flex flex-col gap-4 p-5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
<Avatar url={model.authorAvatarUrl} name={author} />
<Link href={`/?author=${encodeURIComponent(author)}`} className="text-muted-foreground hover:text-foreground hover:underline">
{author}
</Link>
<span className="text-muted-foreground">/</span>
<h1 className="text-xl font-semibold break-all">{name}</h1>
<CopyButton value={model.repoId} label="Copy repo ID" />
<ModelStatusBadge status={model.status} />
<HubStateBadge state={model.hubState} />
<RequestedByBadge name={model.requestedBy} />
{update && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
update available
</span>
)}
<div className="ml-auto flex items-center gap-2">
{canDeploy && (
<Link
href={`/deployments/new?model=${model.id}`}
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
>
<RocketIcon />
Deploy
</Link>
)}
<DeleteModelButton
id={model.id}
repoId={model.repoId}
localPath={model.localPath}
mayHaveFiles={model.status !== "pending" || recentJobs.length > 0}
/>
<ExternalButton href={hub}>🤗 Hugging Face</ExternalButton>
</div>
</div>
<div className="flex flex-wrap items-center gap-1.5">
{model.pipelineTag && (
<Pill icon={MessagesSquareIcon} accent>
{titleCase(model.pipelineTag)}
</Pill>
)}
{formats.map((f) => (
<Pill key={f} icon={BoxIcon}>
{f}
</Pill>
))}
{model.architecture && <Pill icon={CpuIcon}>{model.architecture}</Pill>}
{languages.length > 0 && <Pill icon={LanguagesIcon}>{languages.join(", ")}</Pill>}
{model.license && <Pill icon={ScaleIcon}>License: {model.license}</Pill>}
{extraTags.map((t) => (
<Pill key={t} muted>
{t}
</Pill>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-muted-foreground">Your tags</span>
<TagEditor modelId={model.id} tags={tags} />
</div>
</Panel>
{hubMissing && (
<div className="flex flex-wrap items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="font-medium text-amber-800 dark:text-amber-200">
{model.hubState === "repo_missing"
? "This repo is no longer on Hugging Face"
: "The pinned commit is no longer on Hugging Face"}
</p>
<p className="text-muted-foreground">
{model.hubState === "repo_missing"
? "It was deleted, renamed or made private. "
: "The repo's history was rewritten. "}
Your local copy is kept and stays usable; downloading more files or repairing isn&apos;t possible.
{model.hubMissingSince && (
<>
{" "}
Missing since <LocalTime value={model.hubMissingSince} />.
</>
)}
</p>
</div>
<HubCheckButton modelId={model.id} label="Check again" />
</div>
)}
{update && (
<UpdateBanner modelId={model.id} revision={model.trackedRevision} pinnedSha={model.pinnedSha} diff={update} hubUrl={hub} />
)}
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
{/* Content card with the tabs as a segmented control in its header */}
<Panel className="min-w-0 overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-3">
<nav className="inline-flex rounded-lg bg-muted p-1">
{TABS.map((t) => (
<Link
key={t.id}
href={tabHref(t.id)}
scroll={false}
className={cn(
"flex items-center gap-1.5 rounded-md px-3 py-1 text-sm transition-colors",
tab === t.id
? "bg-background font-medium text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}
>
<t.icon className="size-4" />
{t.label}
{t.id === "files" && <span className="text-xs text-muted-foreground tabular-nums">{selected.length}</span>}
</Link>
))}
</nav>
</div>
{tab === "card" && (
<div className="p-5 sm:p-6">
{card ? (
<>
<ModelCard markdown={card} repoId={model.repoId} sha={model.pinnedSha} />
<div className="mt-6 flex justify-end">
<a
href={`${hub}/blob/${model.pinnedSha}/README.md`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
README.md @ {shortSha(model.pinnedSha)}
<ExternalLinkIcon className="size-3" />
</a>
</div>
</>
) : (
<p className="text-sm text-muted-foreground">
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
<a href={hub} target="_blank" rel="noreferrer" className="underline">
Open on Hugging Face
</a>
</p>
)}
</div>
)}
{tab === "files" && (
<FilesTab
modelId={model.id}
repoId={model.repoId}
sha={model.pinnedSha}
selected={selected}
others={others}
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
busy={model.status === "downloading"}
hubMissing={hubMissing}
/>
)}
{tab === "jobs" && (
<div className="px-2 pb-2">
<JobsTab modelId={model.id} />
</div>
)}
</Panel>
<aside className="flex flex-col gap-4">
<SideCard>
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
</SideCard>
{(modelDeployments.length > 0 || canDeploy) && (
<SideCard title="Deployments" icon={RocketIcon}>
<div className="flex flex-col gap-2">
{modelDeployments.length === 0 ? (
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
) : (
modelDeployments.map((d) => (
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{d.name}</span>
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
</span>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</Link>
))
)}
{canDeploy && (
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
<PlusIcon className="size-3.5" />
New deployment
</Link>
)}
</div>
</SideCard>
)}
<SideCard title="Local copy" icon={ListChecksIcon}>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Selection</dt>
<dd>{quants.length > 0 ? quants.join(", ") : `${selected.length} file${selected.length === 1 ? "" : "s"}`}</dd>
<dt className="text-muted-foreground">Size</dt>
<dd className="tabular-nums">{formatBytes(selectedBytes)}</dd>
<dt className="text-muted-foreground">Commit</dt>
<dd className="flex items-center gap-1">
<a href={`${hub}/commit/${model.pinnedSha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline" title={model.pinnedSha}>
{shortSha(model.pinnedSha)}
</a>
<span className="text-muted-foreground">on {model.trackedRevision}</span>
<CopyButton value={model.pinnedSha} label="Copy commit SHA" />
</dd>
<dt className="text-muted-foreground">Downloaded</dt>
<dd>
<LocalTime value={model.downloadedAt} />
</dd>
<dt className="text-muted-foreground">Path</dt>
<dd className="flex min-w-0 items-center gap-1">
<span className="truncate font-mono text-xs" title={`$MODELS_DIR/${model.localPath}`}>
{model.localPath}
</span>
<CopyButton value={model.localPath} label="Copy path" />
</dd>
{model.includePatterns.length > 0 && (
<>
<dt className="text-muted-foreground">Include</dt>
<dd className="flex flex-col font-mono text-xs">{model.includePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
</>
)}
{model.excludePatterns.length > 0 && (
<>
<dt className="text-muted-foreground">Exclude</dt>
<dd className="flex flex-col font-mono text-xs">{model.excludePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
</>
)}
<dt className="text-muted-foreground">On the Hub</dt>
<dd className="flex flex-col items-start gap-0.5">
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
{model.hubState === "available"
? update
? "Update available"
: "Up to date"
: model.hubState === "repo_missing"
? "Repo deleted"
: model.hubState === "commit_missing"
? "Commit deleted"
: "Not checked yet"}
</span>
{model.lastCheckedAt && (
<span className="text-xs text-muted-foreground" title={model.lastCheckError ?? undefined}>
checked <LocalTime value={model.lastCheckedAt} />
</span>
)}
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
<HubCheckButton modelId={model.id} />
</dd>
<dt className="text-muted-foreground">Added</dt>
<dd>
<LocalTime value={model.createdAt} />
</dd>
</dl>
</SideCard>
<SideCard title="Model tree" icon={SparklesIcon}>
<ModelTree
repoId={model.repoId}
baseModels={baseModels}
relation={model.baseRelation}
families={modelFamilies(model.repoId, baseModels)}
/>
{related.length > 0 && (
<div className="mt-4 flex flex-col gap-1.5 border-t pt-3">
<span className="text-xs text-muted-foreground">Also in your library</span>
{related.map((r) => (
<Link key={r.repoId} href={`/${r.repoId}`} className="flex items-center justify-between gap-2 text-sm hover:underline">
<span className="truncate">{r.repoId}</span>
<span className="shrink-0 text-xs text-muted-foreground">{r.quants.join(", ")}</span>
</Link>
))}
</div>
)}
</SideCard>
</aside>
</div>
</div>
);
}
function Avatar({ url, name }: { url: string | null; name: string }) {
if (url) {
// eslint-disable-next-line @next/next/no-img-element
return <img src={url} alt="" className="size-6 rounded-md object-cover" referrerPolicy="no-referrer" />;
}
return (
<span className="grid size-6 place-items-center rounded-md bg-muted text-xs font-semibold uppercase">
{name.slice(0, 1)}
</span>
);
}
function Pill({
icon: Icon,
accent,
muted,
children,
}: {
icon?: React.ComponentType<{ className?: string }>;
accent?: boolean;
muted?: boolean;
children: React.ReactNode;
}) {
return (
<span
className={cn(
"inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs",
accent && "border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300",
muted && "text-muted-foreground",
)}
>
{Icon && <Icon className="size-3.5" />}
{children}
</span>
);
}
function ExternalButton({ href, children }: { href: string; children: React.ReactNode }) {
return (
<a href={href} target="_blank" rel="noreferrer" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}>
{children}
<ExternalLinkIcon className="opacity-60" />
</a>
);
}
/** Card surface shared by header, content and sidebar. */
function Panel({ className, children }: { className?: string; children: React.ReactNode }) {
return <div className={cn("rounded-xl bg-card text-card-foreground ring-1 ring-foreground/10", className)}>{children}</div>;
}
function SideCard({
title,
icon: Icon,
children,
}: {
title?: string;
icon?: React.ComponentType<{ className?: string }>;
children: React.ReactNode;
}) {
return (
<Panel className="p-4">
{title && (
<h3 className="mb-3 flex items-center gap-1.5 text-sm font-semibold">
{Icon && <Icon className="size-4 text-muted-foreground" />}
{title}
</h3>
)}
{children}
</Panel>
);
}
function ModelTree({
repoId,
baseModels,
relation,
families,
}: {
repoId: string;
baseModels: string[];
relation: string | null;
families: string[];
}) {
if (baseModels.length === 0) {
return <p className="text-sm text-muted-foreground">Original model, family {families.join(", ")}.</p>;
}
return (
<ol className="flex flex-col items-start gap-1 text-sm">
{baseModels.map((b) => (
<li key={b}>
<a href={`https://huggingface.co/${b}`} target="_blank" rel="noreferrer" className="hover:underline">
{b}
</a>
</li>
))}
<li className="flex items-center gap-1 pl-2 text-xs text-muted-foreground">
<ArrowDownIcon className="size-3.5" />
{relation ? (RELATION_LABEL[relation] ?? titleCase(relation)) : "Derived"}
</li>
<li className="font-medium">{repoId}</li>
</ol>
);
}
+50
View File
@@ -0,0 +1,50 @@
"use client";
import { XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { TagBadge } from "@/components/tag-badge";
import { TagPicker } from "@/components/tag-picker";
import type { Tag } from "@/lib/tags";
/** Add/remove user tags on a model. */
export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function add(name: string) {
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;
}
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();
}
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.id} name={t.name} color={t.color}>
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)} className="opacity-60 hover:opacity-100">
<XIcon className="size-3" />
</button>
</TagBadge>
))}
<TagPicker exclude={tags.map((t) => t.name)} onPick={add} disabled={busy} />
</div>
);
}
@@ -0,0 +1,121 @@
"use client";
import { ArrowUpCircleIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { startUpdate } from "@/components/job-actions";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
function FileGroup({ title, files, tone }: { title: string; files: UpdateDiffFile[]; tone: string }) {
if (files.length === 0) return null;
return (
<div className="flex flex-col gap-0.5">
<span className={`text-xs font-medium ${tone}`}>
{title} ({files.length})
</span>
<ul className="flex flex-col gap-0.5 text-xs">
{files.slice(0, 20).map((f) => (
<li key={f.path} className="flex justify-between gap-3">
<span className="font-mono break-all">{f.path}</span>
<span className="shrink-0 text-muted-foreground tabular-nums">
{f.oldSize != null && f.oldSize !== f.size ? `${formatBytes(f.oldSize)} → ` : ""}
{formatBytes(f.size)}
</span>
</li>
))}
{files.length > 20 && <li className="text-muted-foreground">… {files.length - 20} more</li>}
</ul>
</div>
);
}
/** "Update available": what would change in the selection, and the deliberate Update action. */
export function UpdateBanner({
modelId,
revision,
pinnedSha,
diff,
hubUrl,
}: {
modelId: string;
revision: string;
pinnedSha: string;
diff: UpdateDiff;
hubUrl: string;
}) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const changes = diff.changed.length + diff.added.length + diff.removed.length;
const download = [...diff.changed, ...diff.added].reduce((s, f) => s + f.size, 0);
async function update() {
setBusy(true);
try {
if (await startUpdate(modelId)) router.refresh();
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-col gap-3 rounded-xl border border-sky-500/30 bg-sky-500/10 px-4 py-3 text-sm">
<div className="flex flex-wrap items-start gap-3">
<ArrowUpCircleIcon className="mt-0.5 size-4 shrink-0 text-sky-600 dark:text-sky-400" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="font-medium text-sky-900 dark:text-sky-100">
Update available: {revision} is at{" "}
<a href={`${hubUrl}/commit/${diff.sha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline">
{shortSha(diff.sha)}
</a>
</p>
<p className="text-muted-foreground">
You have <span className="font-mono">{shortSha(pinnedSha)}</span>.{" "}
{changes === 0
? "None of your selected files changed; updating only moves the pin."
: `${changes} of your selected files would change (${formatBytes(download)} to download).`}{" "}
Checked <LocalTime value={diff.checkedAt} />.
</p>
</div>
<AlertDialog>
<AlertDialogTrigger render={<Button size="sm" disabled={busy} />}>Update</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Update to {shortSha(diff.sha)}?</AlertDialogTitle>
<AlertDialogDescription>
The model is pinned to the new commit (the old one stays in the history) and changed or new files are
downloaded. Files that are no longer part of your selection are deleted after the download succeeded.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={update} disabled={busy}>
Update
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
{changes > 0 && (
<div className="grid gap-3 rounded-lg bg-background/60 px-3 py-2.5 md:grid-cols-3">
<FileGroup title="Changed" files={diff.changed} tone="text-amber-700 dark:text-amber-300" />
<FileGroup title="Added" files={diff.added} tone="text-emerald-700 dark:text-emerald-300" />
<FileGroup title="Removed" files={diff.removed} tone="text-destructive" />
</div>
)}
</div>
);
}
+202 -53
View File
@@ -1,8 +1,13 @@
"use client";
import { XIcon } from "lucide-react";
import Link from "next/link";
import { useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { TagBadge } from "@/components/tag-badge";
import { TagPicker } from "@/components/tag-picker";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@@ -10,6 +15,8 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, shortSha } from "@/lib/format";
import type { LookupResult } from "@/lib/hub/lookup";
import { escapeGlob, matchesAny, parsePatternList, quantGroup } from "@/lib/selection";
@@ -27,15 +34,21 @@ async function postJson<T>(url: string, body: unknown): Promise<T> {
return json;
}
/** A folder from the models folder to import (found by the worker's scan). */
export type ImportFolder = { path: string; commit: string | null; files: { path: string; size: number }[]; fileCount: number };
export function AddModelForm({
freeBytes,
onAdded,
importFolder,
}: {
freeBytes: number | null;
onAdded: (modelId: string) => void;
/** Import mode: look up this folder's repo and preselect the files that are already there. */
importFolder?: ImportFolder;
}) {
const [repo, setRepo] = useState("");
const [revision, setRevision] = useState("main");
const [repo, setRepo] = useState(importFolder?.path ?? "");
const [revision, setRevision] = useState(importFolder?.commit ?? "main");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<LookupResult | null>(null);
@@ -44,18 +57,41 @@ export function AddModelForm({
const [includeText, setIncludeText] = useState("");
const [excludeText, setExcludeText] = useState("");
const [submitting, setSubmitting] = useState(false);
const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]);
async function lookup(e: React.FormEvent) {
e.preventDefault();
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const repoFiles = useMemo(() => result?.files ?? [], [result]);
const isExcluded = useCallback((path: string) => matchesAny(path, excludePatterns), [excludePatterns]);
// Picked by checkbox or include pattern; recommended companions come on top.
const picked = useMemo(
() => repoFiles.filter((f) => (checked.has(f.path) || matchesAny(f.path, includePatterns)) && !isExcluded(f.path)).map((f) => f.path),
[repoFiles, checked, includePatterns, isExcluded],
);
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(
repoFiles,
picked,
{ isExcluded },
);
// Local files of the imported folder by path.
const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]);
async function lookup(e?: React.FormEvent) {
e?.preventDefault();
setLoading(true);
setError(null);
try {
const r = await postJson<LookupResult>("/api/hub/lookup", { repo, revision });
setResult(r);
setRevision(r.revision);
setChecked(new Set());
// Import: preselect every repo file that's already in the folder.
setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path)));
resetRecommended();
setIncludeText("");
setExcludeText("");
setTags([]);
} catch (err) {
setResult(null);
setError(err instanceof Error ? err.message : String(err));
@@ -64,23 +100,31 @@ export function AddModelForm({
}
}
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const autoLookup = useRef(false);
useEffect(() => {
if (importFolder && !autoLookup.current) {
autoLookup.current = true;
void lookup();
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported
}, [importFolder]);
const files = useMemo(() => {
if (!result) return [];
return result.files.map((f) => {
const pickedSet = new Set(picked);
return repoFiles.map((f) => {
const byPattern = matchesAny(f.path, includePatterns);
const excluded = matchesAny(f.path, excludePatterns);
const excluded = isExcluded(f.path);
return {
...f,
group: quantGroup(f.path),
byPattern,
excluded,
selected: (checked.has(f.path) || byPattern) && !excluded,
recommended: recAll.includes(f.path),
selected: pickedSet.has(f.path) || recActive.has(f.path),
};
});
}, [result, checked, includePatterns, excludePatterns]);
}, [repoFiles, picked, includePatterns, isExcluded, recAll, recActive]);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
@@ -95,14 +139,26 @@ export function AddModelForm({
}, [files]);
const selected = files.filter((f) => f.selected);
// Split files are one row; its checkbox covers all parts.
const entries = useMemo(() => groupSplitFiles(files), [files]);
const selectedEntries = entries.filter((e) => e.parts.every((f) => f.selected)).length;
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
// Files already on disk with the right size are verified by hf, not downloaded again.
const present = selected.filter((f) => onDisk.get(f.path) === f.size);
const toDownload = totalBytes - present.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && toDownload > freeBytes;
const repoPaths = useMemo(() => new Set(result?.files.map((f) => f.path)), [result]);
const sizeDiffers = selected.filter((f) => onDisk.has(f.path) && onDisk.get(f.path) !== f.size).length;
const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0;
function toggle(path: string, on: boolean) {
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setChecked((prev) => {
const next = new Set(prev);
if (on) next.add(path);
else next.delete(path);
for (const path of paths) {
if (on) next.add(path);
else next.delete(path);
}
return next;
});
}
@@ -127,10 +183,12 @@ export function AddModelForm({
repoId: result.repoId,
revision: result.revision,
sha: result.sha,
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
include: [...includePatterns, ...[...new Set([...checked, ...recActive])].sort().map(escapeGlob)],
exclude: excludePatterns,
tags: tags.map((t) => t.name),
localPath: importFolder?.path,
});
toast.success(`${result.repoId} added, download queued`);
toast.success(importFolder ? `${result.repoId} imported, verifying files` : `${result.repoId} added, download queued`);
onAdded(id);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
@@ -143,8 +201,12 @@ export function AddModelForm({
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Hugging Face repository</CardTitle>
<CardDescription>Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL.</CardDescription>
<CardTitle>{importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"}</CardTitle>
<CardDescription>
{importFolder
? `The folder's files are matched against this Hub repo${importFolder.commit ? " at the commit hf recorded when it downloaded them" : ""}. Change the repo or revision if they don't fit.`
: "Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL."}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={lookup} className="flex flex-col gap-3 sm:flex-row sm:items-end">
@@ -207,10 +269,27 @@ export function AddModelForm({
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{importFolder && !result.existingModelId && (
<div className="rounded-md bg-muted px-3 py-2 text-sm">
<p>
<span className="font-medium">
{present.length} of {selected.length} selected files are already on disk
</span>{" "}
and are verified by hash (hf only downloads files that are missing or different).
{sizeDiffers > 0 && ` ${sizeDiffers} differ in size and will be downloaded again.`}
</p>
{notInRepo > 0 && (
<p className="mt-1 text-muted-foreground">
{notInRepo} file{notInRepo === 1 ? " in the folder isn't" : "s in the folder aren't"} part of the repo at this
commit; {notInRepo === 1 ? "it stays" : "they stay"} untouched.
</p>
)}
</div>
)}
{result.existingModelId && (
<p className="rounded-md bg-muted px-3 py-2 text-sm">
This repo is already in the library.{" "}
<Link href={`/models/${result.existingModelId}`} className="underline">
<Link href={`/${result.repoId}`} className="underline">
Open it
</Link>
</p>
@@ -240,6 +319,8 @@ export function AddModelForm({
</div>
)}
<RecommendedStrip files={repoFiles} paths={recAll} active={recActive} onToggle={toggle} />
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="include">Include patterns</Label>
@@ -269,6 +350,35 @@ export function AddModelForm({
folder. Selected = checked or matching an include pattern, minus excludes.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label>Tags</Label>
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.name.toLowerCase()} name={t.name} color={t.color}>
<button
type="button"
aria-label={`Remove tag ${t.name}`}
onClick={() => setTags((prev) => prev.filter((x) => x !== t))}
className="opacity-60 hover:opacity-100"
>
<XIcon className="size-3" />
</button>
</TagBadge>
))}
<TagPicker
exclude={tags.map((t) => t.name)}
onPick={(name, tag) =>
setTags((prev) =>
prev.some((x) => x.name.toLowerCase() === name.toLowerCase())
? prev
: [...prev, { name, color: tag?.color }],
)
}
/>
</div>
<p className="text-xs text-muted-foreground">Optional. Editable later on the model page.</p>
</div>
</CardContent>
</Card>
@@ -283,44 +393,62 @@ export function AddModelForm({
</TableRow>
</TableHeader>
<TableBody>
{files.map((f) => (
<TableRow key={f.path} data-state={f.selected ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={f.selected}
disabled={f.byPattern || f.excluded}
onCheckedChange={(v) => toggle(f.path, v === true)}
aria-label={`Select ${f.path}`}
title={
f.excluded
? "Excluded by a pattern"
: f.byPattern
? "Selected by an include pattern"
: undefined
}
/>
</TableCell>
<TableCell className="font-mono text-xs break-all whitespace-normal">
{f.path}
{f.excluded && <span className="ml-2 text-muted-foreground">(excluded)</span>}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{f.lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
))}
{entries.map((e) => {
const parts = e.parts;
const all = parts.every((f) => f.selected);
const some = !all && parts.some((f) => f.selected);
const byPattern = parts.every((f) => f.byPattern);
const excluded = parts.every((f) => f.excluded);
const isRecommended = parts.every((f) => f.recommended);
return (
<TableRow key={e.path} data-state={all ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={all}
indeterminate={some}
disabled={byPattern || excluded}
onCheckedChange={(v) => toggle(parts.map((f) => f.path), v === true)}
aria-label={`Select ${e.path}`}
title={excluded ? "Excluded by a pattern" : byPattern ? "Selected by an include pattern" : undefined}
/>
</TableCell>
<TableCell className="whitespace-normal">
<span className="flex items-center gap-2" title={e.totalParts > 1 ? parts.map((f) => f.path).join("\n") : undefined}>
<FileRoleBadge path={e.path} />
<span className="font-mono text-xs break-all">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
{excluded && <span className="text-xs text-muted-foreground">(excluded)</span>}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
{importFolder && <DiskState parts={parts} onDisk={onDisk} />}
</span>
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(e.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{parts[0].lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
<div className="sticky bottom-0 -mx-4 border-t bg-background/95 px-4 py-3 backdrop-blur">
<div className="sticky bottom-3 z-10 rounded-xl bg-card/95 px-4 py-3 text-card-foreground shadow-lg ring-1 ring-foreground/10 backdrop-blur">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
{selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)}
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{importFolder && <span className="text-muted-foreground"> · {formatBytes(toDownload)} to download</span>}
{freeBytes != null && (
<span className={notEnoughSpace ? "ml-2 text-destructive" : "ml-2 text-muted-foreground"}>
({formatBytes(freeBytes)} free on the models volume)
@@ -328,7 +456,10 @@ export function AddModelForm({
)}
</div>
<div className="ml-auto flex gap-2">
<Button type="button" variant="ghost" onClick={() => setChecked(new Set())}>
<Button type="button" variant="ghost" onClick={() => {
setChecked(new Set());
resetRecommended();
}}>
Clear
</Button>
<Button
@@ -336,7 +467,7 @@ export function AddModelForm({
onClick={addToLibrary}
disabled={selected.length === 0 || submitting || !!result.existingModelId}
>
{submitting ? "Adding…" : "Add & download"}
{submitting ? "Adding…" : importFolder ? "Import & verify" : "Add & download"}
</Button>
</div>
</div>
@@ -346,3 +477,21 @@ export function AddModelForm({
</div>
);
}
/** Import mode: is this entry already in the folder (and the right size)? */
function DiskState({ parts, onDisk }: { parts: { path: string; size: number }[]; onDisk: Map<string, number> }) {
const here = parts.filter((f) => onDisk.has(f.path));
if (here.length === 0) return null;
const ok = here.every((f) => onDisk.get(f.path) === f.size) && here.length === parts.length;
return (
<span
className={
ok
? "shrink-0 rounded border border-emerald-500/30 bg-emerald-500/10 px-1 text-[10px] leading-4 text-emerald-700 dark:text-emerald-300"
: "shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300"
}
>
{ok ? "on disk" : here.length < parts.length ? `${here.length} of ${parts.length} parts on disk` : "on disk, size differs"}
</span>
);
}
+93 -5
View File
@@ -1,32 +1,120 @@
"use client";
import { FolderInputIcon, RefreshCwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { AddModelForm } from "./add-model-form";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { formatBytes, shortSha } from "@/lib/format";
import { cn } from "@/lib/utils";
import { AddModelForm, type ImportFolder } from "./add-model-form";
/** Library header with an "Add model" toggle that opens the lookup/selection form inline. */
export function AddModelPanel({ freeBytes, defaultOpen }: { freeBytes: number | null; defaultOpen: boolean }) {
type Folder = ImportFolder & { totalBytes: number };
/**
* Library header with an "Add model" toggle that opens the lookup/selection form inline, and the
* folders in the models folder that aren't in the library yet, each with "Import".
*/
export function AddModelPanel({
freeBytes,
defaultOpen,
folders,
}: {
freeBytes: number | null;
defaultOpen: boolean;
folders: Folder[];
}) {
const router = useRouter();
const [open, setOpen] = useState(defaultOpen);
const [importing, setImporting] = useState<Folder | null>(null);
const [scanning, setScanning] = useState(false);
function close() {
setOpen(false);
setImporting(null);
}
async function rescan() {
setScanning(true);
try {
const res = await fetch("/api/local-folders/scan", { method: "POST" });
if (!res.ok) {
toast.error(`Could not start a scan (${res.status})`);
return;
}
// The worker picks the request up with its next heartbeat (every 5 s).
await new Promise((r) => setTimeout(r, 7_000));
router.refresh();
} finally {
setScanning(false);
}
}
return (
<>
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Library</h1>
<Button variant={open ? "outline" : "default"} onClick={() => setOpen((o) => !o)}>
<Button variant={open ? "outline" : "default"} onClick={() => (open ? close() : setOpen(true))}>
{open ? "Close" : "Add model"}
</Button>
</div>
{open && (
<AddModelForm
key={importing?.path ?? "new"}
freeBytes={freeBytes}
importFolder={importing ?? undefined}
onAdded={() => {
setOpen(false);
close();
router.refresh();
}}
/>
)}
{!open && folders.length > 0 && (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FolderInputIcon className="size-4 text-muted-foreground" />
Found in the models folder
</CardTitle>
<CardDescription>
{folders.length} folder{folders.length === 1 ? " isn't" : "s aren't"} in the library yet. Import matches
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again.
</CardDescription>
<CardAction>
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
<RefreshCwIcon className={cn(scanning && "animate-spin")} />
{scanning ? "Scanning…" : "Rescan"}
</Button>
</CardAction>
</CardHeader>
<CardContent>
<ul className="divide-y rounded-lg ring-1 ring-foreground/10">
{folders.map((f) => (
<li key={f.path} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-2">
<span className="min-w-0 flex-1 truncate font-mono text-sm" title={f.path}>
{f.path}
</span>
<span className="text-xs text-muted-foreground tabular-nums">
{f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)}
{f.commit && <> · hf commit {shortSha(f.commit)}</>}
</span>
<Button
size="sm"
variant="outline"
onClick={() => {
setImporting(f);
setOpen(true);
}}
>
Import
</Button>
</li>
))}
</ul>
</CardContent>
</Card>
)}
</>
);
}
+185
View File
@@ -0,0 +1,185 @@
import { TriangleAlertIcon } from "lucide-react";
import { BenchmarkResources } from "@/components/benchmark-resources";
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib/ab-report";
import { CONFIG_ROWS } from "@/lib/benchmark-view";
import type { PairedResult } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
/** The difference with its 95% interval on a %-axis: zero line, the ±target band, the interval and the point. */
function IntervalChart({ r, target }: { r: PairedResult; target: number }) {
const reach = Math.max(Math.abs(r.ci_low_pct), Math.abs(r.ci_high_pct), target) * 1.25 || 1;
const pos = (v: number) => `${((v + reach) / (2 * reach)) * 100}%`;
const ticks = [-reach, -reach / 2, 0, reach / 2, reach].map((t) => Math.round(t * 10) / 10);
return (
<div className="flex flex-col gap-1" role="img" aria-label={`Difference ${sign(r.pct_diff)}, 95% interval ${sign(r.ci_low_pct)} to ${sign(r.ci_high_pct)}`}>
<div className="relative h-12">
{/* ±target band: differences inside it are smaller than the precision asked for */}
<div className="absolute inset-y-2 bg-muted" style={{ left: pos(-target), width: `calc(${pos(target)} - ${pos(-target)})` }} />
<div className="absolute inset-y-0 w-px bg-foreground/50" style={{ left: pos(0) }} />
<div
className={cn("absolute top-1/2 h-2 -translate-y-1/2 rounded-full", r.significant ? "bg-series" : "bg-foreground/40")}
style={{ left: pos(r.ci_low_pct), width: `calc(${pos(r.ci_high_pct)} - ${pos(r.ci_low_pct)})` }}
/>
<div
className={cn("absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2 ring-card", r.significant ? "bg-series" : "bg-foreground/60")}
style={{ left: pos(r.pct_diff) }}
/>
</div>
<div className="relative h-4 text-[11px] text-muted-foreground tabular-nums">
{ticks.map((t) => (
<span key={t} className="absolute -translate-x-1/2" style={{ left: pos(t) }}>
{t > 0 ? "+" : ""}
{t}%
</span>
))}
</div>
<p className="text-[11px] text-muted-foreground">
Dot: B&apos;s difference from A. Bar: the 95% interval. Grey band: ±{target}%, the precision asked for. B is better to the {r.higher_is_better ? "right" : "left"}.
</p>
</div>
);
}
function Side({ label, name, value, unit }: { label: string; name: string; value: number; unit: string }) {
return (
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-lg font-semibold">
{value.toFixed(unit === "ms" ? 2 : 1)} <span className="text-sm font-normal text-muted-foreground">{unit}</span>
</span>
<span className="truncate text-[11px] text-muted-foreground" title={name}>
{name}
</span>
</div>
);
}
export function AbReport({ run }: { run: ListRow }) {
const ab = run.ab;
const a = run.snapshot;
const b = run.snapshotB;
if (!ab || !b) return null;
const d = ab.decode_tps;
const g = ab.gap_median;
const caveats = abCaveats(ab);
const rows = CONFIG_ROWS.map((row) => ({ row, va: row.value(a), vb: row.value(b) })).filter((x) => x.va != null || x.vb != null);
const differs = rows.filter((x) => x.va !== x.vb);
const same = rows.filter((x) => x.va === x.vb);
return (
<article className="flex flex-col gap-8 rounded-2xl bg-card px-5 py-6 ring-1 ring-foreground/10 sm:px-8 sm:py-8">
<header className="flex flex-col gap-3">
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
BetterBench {ab.betterbenchVersion} · paired A/B · {ab.pairs} pairs
</span>
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${a.deploymentName} vs ${b.deploymentName}`}</h2>
<p className="max-w-3xl text-sm leading-relaxed">{abSummaryText(ab, a.deploymentName, b.deploymentName)}</p>
</header>
<section className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<div className="flex flex-col gap-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Decode throughput</span>
<span className={cn("text-3xl font-semibold", d.significant ? "" : "text-muted-foreground")}>{abHeadline(d)}</span>
<span className="text-sm text-muted-foreground">
{sign(d.pct_diff)} · 95% CI {sign(d.ci_low_pct)} to {sign(d.ci_high_pct)} · {d.significant ? "significant" : "within noise"}
</span>
<IntervalChart r={d} target={ab.target_mde_pct} />
</div>
<div className="flex flex-col gap-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g.batched ? "Stream-update gap" : "Token-to-token smoothness"}</span>
<span className={cn("text-3xl font-semibold", g.significant ? "" : "text-muted-foreground")}>{abHeadline(g)}</span>
<span className="text-sm text-muted-foreground">
{sign(g.pct_diff)} · 95% CI {sign(g.ci_low_pct)} to {sign(g.ci_high_pct)} · lower is better
</span>
<IntervalChart r={g} target={ab.target_mde_pct} />
</div>
</section>
<div className="grid gap-2 sm:grid-cols-4">
<Side label="A · decode, mean" name={a.deploymentName} value={d.mean_a} unit="t/s" />
<Side label="B · decode, mean" name={b.deploymentName} value={d.mean_b} unit="t/s" />
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">Pairs</span>
<span className="text-lg font-semibold">{ab.pairs}</span>
<span className="text-[11px] text-muted-foreground">
±{halfWidth(d).toFixed(2)}% reached · target ±{ab.target_mde_pct}%
</span>
</div>
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">Paired CV</span>
<span className="text-lg font-semibold">{(ab.paired_cv * 100).toFixed(2)}%</span>
<span className="text-[11px] text-muted-foreground">~{ab.pairs_needed_for_mde} pairs for ±{ab.target_mde_pct}%</span>
</div>
</div>
{caveats.length > 0 && (
<div className="flex gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex flex-col gap-1.5">
<span className="font-medium text-amber-800 dark:text-amber-200">Read these first</span>
{caveats.map((x) => (
<p key={x} className="text-foreground/80">
{x}
</p>
))}
</div>
</div>
)}
<section className="flex flex-col gap-3">
<h3 className="text-base font-semibold">What differs</h3>
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<table className="w-full text-xs">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="px-3 py-2 font-medium" />
<th className="px-3 py-2 font-medium">A · {a.deploymentName}</th>
<th className="px-3 py-2 font-medium">B · {b.deploymentName}</th>
</tr>
</thead>
<tbody>
{differs.length === 0 && (
<tr>
<td colSpan={3} className="px-3 py-2 text-muted-foreground">
Same settings on both sides (a null A/B: it shows how much noise the setup has).
</td>
</tr>
)}
{differs.map(({ row, va, vb }) => (
<tr key={row.key} className="border-b bg-amber-500/5 last:border-0">
<td className="px-3 py-1.5 font-medium">{row.label}</td>
<td className="px-3 py-1.5 font-mono break-all">{va ?? <span className="text-muted-foreground">default</span>}</td>
<td className="px-3 py-1.5 font-mono break-all">{vb ?? <span className="text-muted-foreground">default</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
{same.length > 0 && <p className="text-xs text-muted-foreground">Same on both: {same.map((x) => `${x.row.label.toLowerCase()} ${x.va}`).join(" · ")}.</p>}
</section>
{run.resources && (
<section className="flex flex-col gap-3">
<h3 className="text-base font-semibold">Resources</h3>
<BenchmarkResources stats={run.resources} names={{ a: a.deploymentName, b: b.deploymentName }} />
</section>
)}
<section className="flex flex-col gap-2">
<h3 className="text-base font-semibold">Method</h3>
<div className="flex max-w-3xl flex-col gap-2 text-sm text-muted-foreground">
{abMethod(ab).map((p) => (
<p key={p}>{p}</p>
))}
</div>
</section>
<footer className="border-t pt-4 text-xs text-muted-foreground">
Generated by Kaname from a BetterBench {ab.betterbenchVersion} paired A/B{ab.corpusVersion ? ` on corpus v${ab.corpusVersion}` : ""}. Every figure is BetterBench&apos;s own.
</footer>
</article>
);
}
@@ -0,0 +1,399 @@
"use client";
import {
DownloadIcon,
ExternalLinkIcon,
RotateCcwIcon,
SquareIcon,
Trash2Icon,
TriangleAlertIcon,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { CopyButton } from "@/components/copy-button";
import { LiveLog } from "@/components/live-log";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
import type { ListRow } from "../benchmark-list";
import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { RunMetaCard } from "@/components/run-meta";
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-report";
import { QualityReport } from "./quality-report";
import { BenchmarkReport } from "./benchmark-report";
import { PublishCard } from "./publish-card";
function duration(a: string | null, b: string | null, now: number) {
if (!a) return null;
const s = Math.max(
0,
((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000,
);
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
return h
? `${h} h ${m} min`
: m
? `${m} min ${Math.round(s % 60)} s`
: `${Math.round(s)} s`;
}
export function BenchmarkDetail({ initial }: { initial: ListRow }) {
const router = useRouter();
const [r, setR] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const [label, setLabel] = useState(initial.label ?? "");
const [description, setDescription] = useState(initial.description ?? "");
const active = r.state === "pending_approval" || r.state === "queued" || r.state === "running";
useEffect(() => {
if (!active) return;
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/benchmarks/${r.id}`, {
cache: "no-store",
}).catch(() => null);
if (res?.ok) setR(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [active, r.id]);
async function again() {
if (!r.deploymentId) return;
const res = await fetch("/api/benchmarks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
deploymentId: r.deploymentId,
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
kind: r.kind,
label: r.label,
description: r.description,
...r.settings,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok)
return toast.error(
json.error?.message ?? `Could not start (${res.status})`,
);
router.push(`/benchmarks/${json.id}`);
}
const s = r.snapshot;
const sum = r.summary;
const took = duration(r.startedAt, r.finishedAt, now);
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">
{r.label ??
(r.kind === "ab"
? `${s.deploymentName} vs ${r.snapshotB?.deploymentName}`
: s.deploymentName)}
</h1>
{r.kind === "ab" && (
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">
A/B
</span>
)}
<BenchmarkStateBadge
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
<RequestedByBadge name={r.requestedBy} />
</div>
<p className="text-sm text-muted-foreground">
{r.deploymentId ? (
<Link
href={`/deployments/${r.deploymentId}`}
className="hover:underline"
>
{s.deploymentName}
</Link>
) : (
`${s.deploymentName} (deleted)`
)}{" "}
·{" "}
{r.modelId ? (
<Link href={`/${s.repoId}`} className="hover:underline">
{s.repoId}
</Link>
) : (
s.repoId
)}{" "}
· {s.runtimeName}
{r.kind === "ab" && r.snapshotB && (
<>
{" "}
· B:{" "}
{r.deploymentBId ? (
<Link
href={`/deployments/${r.deploymentBId}`}
className="hover:underline"
>
{r.snapshotB.deploymentName}
</Link>
) : (
r.snapshotB.deploymentName
)}
</>
)}
{r.sweepId && (
<>
{" "}
·{" "}
<Link
href={`/benchmarks/sweeps/${r.sweepId}`}
className="hover:underline"
>
part of a sweep
</Link>
</>
)}
</p>
<p className="text-xs text-muted-foreground">
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
{r.kind === "ab"
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
: describeSettings(r.settings)}{" "}
· created <LocalTime value={r.createdAt} />
{took &&
` · ${r.state === "running" ? "running for" : "took"} ${took}`}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{r.hasReport && (
<a
href={`/api/benchmarks/${r.id}/report`}
target="_blank"
rel="noreferrer"
className={buttonVariants({ variant: "outline" })}
>
<ExternalLinkIcon />
Full report
</a>
)}
{r.state === "completed" && (
<a
href={`/api/benchmarks/${r.id}/results`}
className={buttonVariants({ variant: "outline" })}
>
<DownloadIcon />
{r.kind === "ab" ? "ab.json" : "results.json"}
</a>
)}
{active ? (
<Button
variant="outline"
disabled={!!r.cancelRequestedAt}
onClick={async () =>
(await cancelBenchmark(r.id)) && router.refresh()
}
>
<SquareIcon />
Cancel
</Button>
) : (
r.deploymentId &&
!r.sweepId && (
<Button
variant="outline"
onClick={again}
title="Queue a new run with the same settings (the deployment must be running)"
>
<RotateCcwIcon />
Run again
</Button>
)
)}
<AlertDialog>
<AlertDialogTrigger
render={
<Button
variant="outline"
disabled={r.state === "running"}
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
/>
}
>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete this benchmark?</AlertDialogTitle>
<AlertDialogDescription>
Its numbers, log, results.json and HTML report are removed.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteBenchmark(r.id)) {
router.push("/benchmarks");
router.refresh();
}
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{r.state === "pending_approval" && (
<AgentApprovalBar
requestedBy={r.requestedBy}
what={`run ${r.kind === "ab" ? "an A/B" : r.kind === "eval" ? "the quality eval" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
base={`/api/benchmarks/${r.id}`}
/>
)}
{r.error && (
<div className="flex gap-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
<pre className="min-w-0 flex-1 font-sans break-words whitespace-pre-wrap">
{r.error}
</pre>
</div>
)}
{r.state === "queued" && (
<p className="text-sm text-muted-foreground">
Waiting: benchmarks run one at a time.
</p>
)}
{r.state === "running" && r.phase && (
<p className="text-sm text-muted-foreground">Now: {r.phase}</p>
)}
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
<div className="flex min-w-0 flex-col gap-4">
{r.kind === "ab" ? <AbReport run={r} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <BenchmarkReport run={r} />}
<LiveLog
url={`/api/benchmarks/${r.id}/logs`}
title="BetterBench output"
live={active}
/>
</div>
<aside className="flex flex-col gap-4">
{r.kind === "run" && r.state === "completed" && r.summary && (
<PublishCard
runId={r.id}
defaultTitle={r.label ?? `${s.repoId} ${weightsLabel(s)}`}
defaultSummary={reportSummary(r)}
/>
)}
<Card size="sm">
<CardHeader>
<CardTitle>Label</CardTitle>
</CardHeader>
<CardContent>
<Input
value={label}
maxLength={120}
placeholder="e.g. q8_0 KV cache"
onChange={(e) => setLabel(e.target.value)}
onBlur={async () =>
label !== (r.label ?? "") &&
(await renameBenchmark(r.id, label || null)) &&
setR({ ...r, label: label.trim() || null })
}
onKeyDown={(e) =>
e.key === "Enter" && (e.target as HTMLInputElement).blur()
}
/>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Description</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-1.5">
<textarea
value={description}
maxLength={4000}
rows={3}
placeholder="What this run tries out, e.g. q8_0 KV cache to fit 64k context"
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
onChange={(e) => setDescription(e.target.value)}
onBlur={async () =>
description !== (r.description ?? "") &&
(await describeBenchmark(r.id, description || null)) &&
setR({ ...r, description: description.trim() || null })
}
/>
<p className="text-[11px] text-muted-foreground">
Passed to BetterBench (when set before the run starts) and to the launch80 preview, together with the system summary.
</p>
</CardContent>
</Card>
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
{r.kind !== "ab" && (
<Card size="sm">
<CardHeader>
<CardTitle>Settings measured</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
{CONFIG_ROWS.map((row) => {
const v = row.value(s);
return v == null ? null : (
<div key={row.key} className="contents">
<dt className="text-muted-foreground">{row.label}</dt>
<dd className="min-w-0 font-mono break-all">{v}</dd>
</div>
);
})}
</dl>
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between text-xs text-muted-foreground">
Command
<CopyButton value={s.command} label="Copy command" />
</div>
<pre className="rounded-md bg-muted/60 px-2 py-1.5 font-mono text-[11px] break-all whitespace-pre-wrap">
{s.command}
</pre>
</div>
{sum && (
<p className="text-[11px] text-muted-foreground">
BetterBench {sum.betterbenchVersion} · corpus v
{sum.corpusVersion} · phases: {sum.phases.join(", ") || "–"}
</p>
)}
</CardContent>
</Card>
)}
</aside>
</div>
</div>
);
}
@@ -0,0 +1,389 @@
"use client";
import { TriangleAlertIcon } from "lucide-react";
import { BarChart } from "@/components/bar-chart";
import { BenchmarkResources } from "@/components/benchmark-resources";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled, weightsLabel } from "@/lib/benchmark-report";
import { configChips } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) {
return (
<div className="flex flex-col gap-1 rounded-xl bg-muted/50 px-4 py-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-3xl font-semibold">
{value}
<span className="ml-1 text-base font-normal text-muted-foreground">{unit}</span>
</span>
<span className="text-xs text-muted-foreground">{note}</span>
</div>
);
}
function Section({ title, intro, children }: { title: string; intro?: string; children: React.ReactNode }) {
return (
<section className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<h2 className="text-base font-semibold">{title}</h2>
{intro && <p className="max-w-3xl text-sm text-muted-foreground">{intro}</p>}
</div>
{children}
</section>
);
}
/** A percentile cell, daggered when it fails BetterBench's sample gate. */
function Gated({ v, sum, section, k, metric, fmt = f1 }: { v: number | null | undefined; sum: BenchmarkSummary; section: string; k: string | number; metric: string; fmt?: (v: number | null | undefined) => string }) {
const gated = v != null && undersampled(sum, section, k, metric);
return (
<span className={cn(gated && "text-amber-700 dark:text-amber-300")} title={gated ? "Under-sampled: roughly the worst observed, not a percentile" : undefined}>
{fmt(v)}
{gated && "†"}
</span>
);
}
const date = (iso: string | null | undefined) =>
iso
? new Date(iso.replace(/([+-]\d\d)(\d\d)$/, "$1:$2"))
.toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" })
.toUpperCase()
.replace(",", " ·")
: "";
/** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */
export function BenchmarkReport({ run }: { run: ListRow }) {
const sum = run.summary;
if (!sum) return null;
const s = run.snapshot;
const batched = isBatched(sum);
const caveats = reportCaveats(run);
const c = sum.combined;
const peak = sum.concurrency.length ? sum.concurrency.reduce((a, b) => (b.aggregate_tps > a.aggregate_tps ? b : a)) : null;
const cfg = sum.config ?? {};
const chips = [
sum.corpusVersion && `corpus v${sum.corpusVersion}`,
sum.single.length && sum.passes ? `${sum.passes} passes/cat` : null,
cfg.greedy ? "greedy" : cfg.temperature != null ? `temp ${cfg.temperature}` : null,
cfg.unique_nonce === false ? "warm prefix cache" : "cold prefix cache (nonce)",
`phases: ${sum.phases.join(", ")}`,
].filter(Boolean) as string[];
return (
<article className="flex flex-col gap-8 rounded-2xl bg-card px-5 py-6 ring-1 ring-foreground/10 sm:px-8 sm:py-8">
<header className="flex flex-col gap-3">
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
BetterBench {sum.betterbenchVersion} · {date(sum.timestamp ?? run.startedAt)}
</span>
<div className="flex flex-col gap-1">
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${s.repoId} ${weightsLabel(s) !== "safetensors" ? weightsLabel(s) : ""}`.trim()}</h2>
<p className="text-sm text-muted-foreground">{reportSubtitle(run)}</p>
</div>
<div className="flex flex-wrap gap-1.5">
{chips.map((x) => (
<span key={x} className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
{x}
</span>
))}
<span className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">{s.runtimeName}</span>
{configChips(s).map((x) => (
<span key={x} className="rounded-md bg-muted px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
{x}
</span>
))}
</div>
<p className="max-w-3xl text-sm leading-relaxed">{reportSummary(run)}</p>
</header>
{c && (
<div className="grid gap-3 sm:grid-cols-3">
<Tile label="Combined decode" value={f1(c.decode)} unit="t/s" note="weighted across categories" />
{batched ? (
<Tile label="Combined update p99" value={f1(c.update_p99)} unit="ms" note="gap between stream updates" />
) : (
<Tile label="Combined ITL 1% low" value={f1(c.itl_low1)} unit="t/s" note="the trustworthy tail metric" />
)}
<Tile label="Combined TTFT p50" value={f0(c.ttft_p50)} unit="ms" note="single-stream, batch = 1" />
</div>
)}
{caveats.length > 0 && (
<div className="flex gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex flex-col gap-1.5">
<span className="font-medium text-amber-800 dark:text-amber-200">Read these first</span>
{caveats.map((x) => (
<p key={x} className="text-foreground/80">
{x}
</p>
))}
</div>
</div>
)}
{sum.single.length > 0 && (
<Section
title="Decode throughput by category"
intro={`Median per-pass decode t/s at batch = 1, ${sum.passes} passes per category. The vertical line is the weighted combined score.`}
>
<BarChart
axisLabel="Decode t/s (median)"
reference={c?.decode != null ? { value: c.decode, label: `combined ${f1(c.decode)}` } : null}
rows={sum.single.map((r) => ({
label: r.category,
value: r.decode_med,
valueLabel: f1(r.decode_med),
details: [
`decode ${f1(r.decode_med)} t/s`,
r.decode_iqr != null ? `IQR ${f1(r.decode_iqr)}` : "",
r.decode_cv != null ? `CV ${(r.decode_cv * 100).toFixed(1)}%` : "",
`${r.runs} passes`,
].filter(Boolean),
}))}
/>
<p className="text-xs text-muted-foreground">Hover a bar for its IQR and coefficient of variation. A high CV means the category&apos;s passes disagree, so read small differences there with care.</p>
</Section>
)}
{sum.single.length > 0 && !batched && sum.single.some((r) => r.itl_low1 != null && r.itl_high99 != null) && (
<Section
title="Inter-token latency range by category"
intro="Each bar spans the 1% low to the 99% high instantaneous token rate, with a tick at the median. Wide bars stutter; narrow bars feel smooth."
>
<BarChart
mode="range"
axisLabel="Instantaneous t/s"
rows={sum.single.map((r) => ({
label: r.category,
value: r.itl_med ?? null,
range: r.itl_low1 != null && r.itl_high99 != null ? [r.itl_low1, r.itl_high99] : null,
valueLabel: r.itl_low1 != null ? `${f1(r.itl_low1)} – ${f1(r.itl_high99)}${undersampled(sum, "single_stream", r.category, "itl_high99") ? "†" : ""}` : undefined,
details: [`1% low ${f1(r.itl_low1)} t/s`, `median ${f1(r.itl_med)} t/s`, `99% high ${f1(r.itl_high99)} t/s`],
}))}
/>
</Section>
)}
{sum.prefill.some((p) => !p.skipped) && (
<Section title="Prompt processing by input length" intro="Median prefill t/s (prompt tokens ÷ TTFT) at increasing input depth, cold prefix cache.">
<BarChart
axisLabel="Prefill t/s (median)"
rows={sum.prefill
.filter((p) => !p.skipped)
.map((p) => ({
label: `~${p.target_depth.toLocaleString("en-US")} tok`,
value: p.pp_med ?? null,
valueLabel: f0(p.pp_med),
details: [`prompt ${f0(p.prompt_tokens_med)} tokens`, `TTFT ${f0(p.ttft_p50)} ms`, `1% low ${f0(p.pp_low1)} · 99% high ${f0(p.pp_p99)} t/s`, `${p.pp_n ?? "?"} runs`],
}))}
/>
</Section>
)}
{sum.concurrency.length > 0 && (
<Section
title="Throughput under parallel load"
intro={`Aggregate t/s across all requests at each concurrency level${peak ? `; the knee is where the bars stop growing (peak at ${peak.level})` : ""}.`}
>
<BarChart
axisLabel="Aggregate t/s"
rows={sum.concurrency.map((x) => ({
label: `${x.level} parallel`,
value: x.aggregate_tps,
valueLabel: f1(x.aggregate_tps),
details: [`per request ${f1(x.decode_med)} t/s`, `TTFT p50 ${f0(x.ttft_p50)} ms · p99 ${f0(x.ttft_p99)} ms`, `${x.ok}/${x.requests} requests ok`],
}))}
/>
</Section>
)}
{run.resources && (
<Section title="Resources" intro="What the server used while BetterBench measured it.">
<BenchmarkResources stats={run.resources} />
</Section>
)}
<Section title="Full numbers">
{sum.single.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Category</TableHead>
<TableHead className="text-right">Passes</TableHead>
<TableHead className="text-right">TTFT p50</TableHead>
<TableHead className="text-right">TTFT p99</TableHead>
{batched ? (
<>
<TableHead className="text-right">Update p50</TableHead>
<TableHead className="text-right">Update p99</TableHead>
<TableHead className="text-right">Tok/update</TableHead>
</>
) : (
<>
<TableHead className="text-right">ITL 1% low</TableHead>
<TableHead className="text-right">ITL med</TableHead>
<TableHead className="text-right">ITL 99% high</TableHead>
</>
)}
<TableHead className="text-right">Decode med</TableHead>
<TableHead className="text-right">±IQR</TableHead>
<TableHead className="pr-3 text-right">CV</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.single.map((r) => (
<TableRow key={r.category}>
<TableCell className="pl-3">{r.category}</TableCell>
<TableCell className="text-right">{r.runs}</TableCell>
<TableCell className="text-right">{f1(r.ttft_p50)}</TableCell>
<TableCell className="text-right">
<Gated v={r.ttft_p99} sum={sum} section="single_stream" k={r.category} metric="ttft_p99" />
</TableCell>
{batched ? (
<>
<TableCell className="text-right">{f1(r.update_p50)}</TableCell>
<TableCell className="text-right">
<Gated v={r.update_p99} sum={sum} section="single_stream" k={r.category} metric="update_p99" />
</TableCell>
<TableCell className="text-right">{r.tok_per_update != null ? r.tok_per_update.toFixed(2) : "—"}</TableCell>
</>
) : (
<>
<TableCell className="text-right">{f1(r.itl_low1)}</TableCell>
<TableCell className="text-right">{f1(r.itl_med)}</TableCell>
<TableCell className="text-right">
<Gated v={r.itl_high99} sum={sum} section="single_stream" k={r.category} metric="itl_high99" />
</TableCell>
</>
)}
<TableCell className="text-right font-medium">{f1(r.decode_med)}</TableCell>
<TableCell className="text-right">{f1(r.decode_iqr)}</TableCell>
<TableCell className="pr-3 text-right">{r.decode_cv != null ? `${(r.decode_cv * 100).toFixed(1)}%` : "—"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
<div className="grid gap-4 md:grid-cols-2">
{sum.concurrency.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Concurrency</TableHead>
<TableHead className="text-right">OK</TableHead>
<TableHead className="text-right">Aggregate t/s</TableHead>
<TableHead className="text-right">Decode med</TableHead>
<TableHead className="text-right">TTFT p50</TableHead>
<TableHead className="pr-3 text-right">TTFT p99</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.concurrency.map((x) => (
<TableRow key={x.level}>
<TableCell className="pl-3">{x.level}</TableCell>
<TableCell className="text-right">
{x.ok}/{x.requests}
</TableCell>
<TableCell className="text-right font-medium">{f1(x.aggregate_tps)}</TableCell>
<TableCell className="text-right">{f1(x.decode_med)}</TableCell>
<TableCell className="text-right">{f1(x.ttft_p50)}</TableCell>
<TableCell className="pr-3 text-right">
<Gated v={x.ttft_p99} sum={sum} section="concurrency" k={x.level} metric="ttft_p99" />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
{sum.prefill.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Depth</TableHead>
<TableHead className="text-right">Prompt tok</TableHead>
<TableHead className="text-right">TTFT p50</TableHead>
<TableHead className="text-right">PP 1% low</TableHead>
<TableHead className="text-right">PP med</TableHead>
<TableHead className="pr-3 text-right">PP 99%</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.prefill.map((p) => (
<TableRow key={p.target_depth}>
<TableCell className="pl-3">~{p.target_depth.toLocaleString("en-US")}</TableCell>
{p.skipped ? (
<TableCell colSpan={5} className="pr-3 text-right text-muted-foreground">
skipped
</TableCell>
) : (
<>
<TableCell className="text-right">{f0(p.prompt_tokens_med)}</TableCell>
<TableCell className="text-right">{f1(p.ttft_p50)}</TableCell>
<TableCell className="text-right">{f1(p.pp_low1)}</TableCell>
<TableCell className="text-right font-medium">{f1(p.pp_med)}</TableCell>
<TableCell className="pr-3 text-right">
<Gated v={p.pp_p99} sum={sum} section="prefill" k={p.target_depth} metric="pp_p99" />
</TableCell>
</>
)}
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
{sum.reasoning && sum.reasoning.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Category</TableHead>
<TableHead className="text-right">Split known</TableHead>
<TableHead className="text-right">Reasoning share</TableHead>
<TableHead className="text-right">Never answered</TableHead>
<TableHead className="pr-3 text-right">Time to first answer p50</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.reasoning.map((x) => (
<TableRow key={x.category}>
<TableCell className="pl-3">{x.category}</TableCell>
<TableCell className="text-right">
{x.known}/{x.runs}
</TableCell>
<TableCell className="text-right">{x.reasoning_share != null ? `${Math.round(x.reasoning_share * 100)}%` : "unknown"}</TableCell>
<TableCell className="text-right">{x.never_answered}</TableCell>
<TableCell className="pr-3 text-right">{x.ttfa_p50 != null ? `${f0(x.ttfa_p50)} ms` : "unknown"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</Section>
<Section title="Method">
<div className="flex max-w-3xl flex-col gap-2 text-sm text-muted-foreground">
{reportMethod(sum).map((p) => (
<p key={p}>{p}</p>
))}
</div>
</Section>
<footer className="border-t pt-4 text-xs text-muted-foreground">
Generated by Kaname from a BetterBench {sum.betterbenchVersion} run{sum.corpusVersion ? ` on corpus v${sum.corpusVersion}` : ""}
{sum.corpusHash ? ` (corpus hash ${sum.corpusHash})` : ""}. Results are only comparable within a corpus version. Every figure comes from BetterBench&apos;s own report
functions; Kaname adds none.
</footer>
</article>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getBenchmark } from "@/lib/benchmarks";
import { BenchmarkDetail } from "./benchmark-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/benchmarks/[id]">): Promise<Metadata> {
const run = await getBenchmark((await params).id);
return { title: run ? `${run.label ?? run.snapshot.deploymentName} · Benchmark` : "Benchmark" };
}
export default async function BenchmarkPage({ params }: PageProps<"/benchmarks/[id]">) {
const run = await getBenchmark((await params).id);
if (!run) notFound();
return <BenchmarkDetail initial={JSON.parse(JSON.stringify(run))} />;
}
@@ -0,0 +1,263 @@
"use client";
import { CheckIcon, DownloadIcon, ExternalLinkIcon, EyeIcon, LoaderCircleIcon, SendIcon, Trash2Icon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { L80Status, PayloadPreview, PublicationRow } from "@/lib/publications";
type Pub = Omit<PublicationRow, "createdAt" | "previewedAt" | "confirmedAt" | "publishedAt"> & {
createdAt: string;
previewedAt: string | null;
confirmedAt: string | null;
publishedAt: string | null;
};
const RETENTION_DAYS = 5;
const textareaClass =
"min-h-24 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
async function send(url: string, method: string, body?: unknown) {
const res = await fetch(url, { method, ...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Request failed (${res.status})`);
return res.ok ? json : null;
}
/**
* Publish to launch80 as a double opt-in, the way the L80 docs describe it: first a dry run that
* builds the exact payload (nothing is sent), then an explicit confirmation that publishes that file.
*/
export function PublishCard({ runId, defaultTitle, defaultSummary }: { runId: string; defaultTitle: string; defaultSummary: string }) {
const [status, setStatus] = useState<L80Status>(null);
const [pubs, setPubs] = useState<Pub[] | null>(null);
const [title, setTitle] = useState(defaultTitle.slice(0, 120));
const [summary, setSummary] = useState(defaultSummary.slice(0, 600));
const [preview, setPreview] = useState<{ id: string; data: PayloadPreview | null } | null>(null);
const [ack, setAck] = useState(false);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
const res = await fetch(`/api/benchmarks/${runId}/publications`, { cache: "no-store" }).catch(() => null);
if (!res?.ok) return;
const json = (await res.json()) as { status: L80Status; publications: Pub[] };
setStatus(json.status);
setPubs(json.publications);
}, [runId]);
const current = pubs?.find((p) => p.state !== "published") ?? null;
const pending = !!pubs?.some((p) => p.state === "preview" || p.state === "publish");
useEffect(() => {
const first = setTimeout(load, 0);
const t = setInterval(load, pending ? 1_500 : 20_000);
return () => {
clearTimeout(first);
clearInterval(t);
};
}, [load, pending]);
// Load what the previewed payload contains once its preview is ready.
const previewId = current?.state === "previewed" ? current.id : null;
useEffect(() => {
if (!previewId || preview?.id === previewId) return;
let stop = false;
void fetch(`/api/benchmarks/${runId}/publications/${previewId}`, { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((j) => !stop && setPreview({ id: previewId, data: j?.preview ?? null }));
return () => {
stop = true;
};
}, [previewId, preview?.id, runId]);
async function prepare() {
setBusy(true);
setAck(false);
try {
if (await send(`/api/benchmarks/${runId}/publications`, "POST", { title: title.trim() || null, summary: summary.trim() || null })) await load();
} finally {
setBusy(false);
}
}
async function publish(id: string) {
setBusy(true);
try {
if (await send(`/api/benchmarks/${runId}/publications/${id}`, "POST", { confirm: true })) await load();
} finally {
setBusy(false);
}
}
async function discard(id: string) {
const res = await fetch(`/api/benchmarks/${runId}/publications/${id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not discard (${res.status})`);
setPreview(null);
setAck(false);
await load();
}
const published = pubs?.filter((p) => p.state === "published") ?? [];
const p = preview?.id === current?.id ? preview?.data : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<SendIcon className="size-4 text-muted-foreground" />
Publish to launch80
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{pubs === null ? (
<p className="text-xs text-muted-foreground">Loading…</p>
) : !status?.version ? (
<p className="text-xs text-muted-foreground">The L80 CLI isn&apos;t available in this installation, so runs can&apos;t be published.</p>
) : (
<>
{published.map((x) => (
<div key={x.id} className="flex flex-col gap-1 rounded-lg bg-emerald-500/10 px-3 py-2">
<span className="flex items-center gap-1.5 text-xs font-medium text-emerald-700 dark:text-emerald-300">
<CheckIcon className="size-3.5" />
Published <LocalTime value={x.publishedAt} />
</span>
<span className="flex items-center gap-1">
<a href={x.url ?? "#"} target="_blank" rel="noreferrer" className="min-w-0 flex-1 truncate font-mono text-xs underline">
{x.url}
</a>
<CopyButton value={x.url ?? ""} label="Copy link" />
</span>
<span className="text-[11px] text-muted-foreground">
Public until about <LocalTime value={x.publishedAt ? new Date(new Date(x.publishedAt).getTime() + RETENTION_DAYS * 86_400_000).toISOString() : null} />
{x.confirmedBy && ` · confirmed by ${x.confirmedBy}`}
</span>
</div>
))}
{!current && (
<>
<p className="text-xs text-muted-foreground">
Step 1 of 2: prepare a preview. The L80 CLI builds the exact page payload from this run&apos;s results.json (endpoint and host removed). Nothing is sent yet.
</p>
<div className="flex flex-col gap-1.5">
<Label htmlFor="pub-title">Page title</Label>
<Input id="pub-title" value={title} onChange={(e) => setTitle(e.target.value)} maxLength={120} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="pub-summary">Summary</Label>
<textarea id="pub-summary" value={summary} onChange={(e) => setSummary(e.target.value)} maxLength={600} className={textareaClass} />
<span className="text-right text-[11px] text-muted-foreground tabular-nums">{summary.length}/600</span>
</div>
<Button variant="outline" onClick={prepare} disabled={busy}>
<EyeIcon />
Prepare preview
</Button>
</>
)}
{current?.state === "preview" && (
<p className="flex items-center gap-2 text-xs text-muted-foreground">
<LoaderCircleIcon className="size-3.5 animate-spin" />
Building the payload (dry run)…
</p>
)}
{current?.state === "previewed" && (
<div className="flex flex-col gap-3">
<p className="text-xs text-muted-foreground">Step 2 of 2: check what would be published.</p>
{p ? (
<dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 rounded-lg bg-muted/50 px-3 py-2 text-xs">
<dt className="text-muted-foreground">Template</dt>
<dd className="font-mono">{p.template}</dd>
<dt className="text-muted-foreground">Size</dt>
<dd>{(p.bytes / 1024).toFixed(1)} KB</dd>
<dt className="text-muted-foreground">Title</dt>
<dd>{p.title ?? <span className="text-muted-foreground">model name</span>}</dd>
<dt className="text-muted-foreground">Summary</dt>
<dd className="line-clamp-4">{p.summary ?? <span className="text-muted-foreground">none</span>}</dd>
<dt className="text-muted-foreground">Model</dt>
<dd className="font-mono break-all">{p.model}</dd>
<dt className="text-muted-foreground">Notes</dt>
<dd className="flex flex-wrap gap-1">
{Object.entries(p.notes).map(([k, v]) => (
<span key={k} className="rounded bg-background px-1 font-mono text-[11px]">
{k}={v}
</span>
))}
</dd>
{p.sections.map((s) => (
<div key={s.heading} className="contents">
<dt className="text-muted-foreground">{s.heading}</dt>
<dd className="whitespace-pre-line">{s.body}</dd>
</div>
))}
<dt className="text-muted-foreground">Data</dt>
<dd>{p.phases.join(", ")} · every raw sample</dd>
<dt className="text-muted-foreground">Removed</dt>
<dd className={p.hostRemoved ? "" : "text-destructive"}>{p.hostRemoved ? "endpoint URL and host name" : "endpoint or host still present!"}</dd>
</dl>
) : (
<p className="text-xs text-muted-foreground">Reading the payload…</p>
)}
<a href={`/api/benchmarks/${runId}/publications/${current.id}/payload`} className={buttonVariants({ variant: "ghost", size: "sm" }) + " self-start"}>
<DownloadIcon />
Exact payload (JSON)
</a>
<ul className="list-disc pl-4 text-xs text-muted-foreground">
<li>Public: anyone with the link can read it.</li>
<li>Immutable: to change it, publish again.</li>
<li>Unindexed, self-contained, marked &ldquo;self-reported, not verified by launch80&rdquo;.</li>
<li>Removed after {RETENTION_DAYS} days. Counts against your token&apos;s 10 publishes per day.</li>
</ul>
{!status.tokenSet && (
<p className="text-xs text-amber-700 dark:text-amber-300">No launch80 token: set L80_TOKEN (launch80 Supporter) for the worker to publish.</p>
)}
<label className="flex cursor-pointer items-start gap-2 text-xs">
<Checkbox checked={ack} onCheckedChange={(v) => setAck(v === true)} className="mt-0.5" disabled={!status.tokenSet || !p?.hostRemoved} />
<span>I want this run published as a public page on launch80.com, exactly as previewed.</span>
</label>
<div className="flex flex-wrap gap-2">
<Button onClick={() => publish(current.id)} disabled={!ack || busy || !status.tokenSet || !p?.hostRemoved}>
<SendIcon />
Publish
</Button>
<Button variant="ghost" onClick={() => discard(current.id)} disabled={busy}>
<Trash2Icon />
Discard
</Button>
</div>
</div>
)}
{current?.state === "publish" && (
<p className="flex items-center gap-2 text-xs text-muted-foreground">
<LoaderCircleIcon className="size-3.5 animate-spin" />
Publishing…
</p>
)}
{current?.state === "failed" && (
<div className="flex flex-col gap-2">
<pre className="rounded-lg bg-destructive/10 px-3 py-2 font-sans text-xs break-words whitespace-pre-wrap text-destructive">{current.error}</pre>
<Button variant="outline" size="sm" className="self-start" onClick={() => discard(current.id)}>
Start over
</Button>
</div>
)}
{published.length > 0 && !current && (
<a href="https://launch80.com" target="_blank" rel="noreferrer" className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground">
launch80.com <ExternalLinkIcon className="size-3" />
</a>
)}
</>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,68 @@
import { CheckIcon, XIcon } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { QualityResult } from "@/lib/db/schema";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
/** A quality eval's result: the score, each section's pass rate and every item. */
export function QualityReport({ quality, running }: { quality: QualityResult | null; running: boolean }) {
if (!quality) {
return (
<Card>
<CardContent className="text-sm text-muted-foreground">{running ? "The quality eval is running; results appear when it's done." : "No result."}</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Quality</CardTitle>
<CardDescription>
Eval set {quality.evalSet}: greedy decoding (temperature {quality.config.temperature}, seed {quality.config.seed}), thinking{" "}
{quality.config.thinking ? "on" : "off"}
{quality.config.contextTokens ? `, context ${quality.config.contextTokens.toLocaleString("en-US")} tokens` : ""}. Scores are the share of items that pass;
only results of the same eval set compare.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-baseline gap-2">
<span className="text-4xl font-semibold tabular-nums">{quality.score != null ? `${quality.score}%` : "—"}</span>
<span className="text-sm text-muted-foreground">overall (mean of the sections)</span>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>Section</TableHead>
<TableHead className="text-right">Passed</TableHead>
<TableHead className="text-right">Score</TableHead>
<TableHead className="text-right">Time</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{quality.sections.map((s) => (
<TableRow key={s.section}>
<TableCell className="whitespace-normal">
<div className="font-medium">{SECTION_LABEL[s.section]}</div>
<div className="text-xs text-muted-foreground">{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}</div>
</TableCell>
<TableCell className="text-right tabular-nums">{s.unsupported ? "—" : `${s.passed} / ${s.total}`}</TableCell>
<TableCell className="text-right font-medium tabular-nums">{s.score != null ? `${s.score}%` : "—"}</TableCell>
<TableCell className="text-right text-muted-foreground tabular-nums">{s.seconds} s</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<ul className="flex flex-col gap-1 text-xs">
{quality.items.map((i) => (
<li key={`${i.section}-${i.id}`} className="flex items-start gap-1.5">
{i.pass ? <CheckIcon className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> : <XIcon className="mt-0.5 size-3.5 shrink-0 text-destructive" />}
<span className="font-mono">{i.id}</span>
<span className={cn("min-w-0 break-words text-muted-foreground", !i.pass && "text-foreground")}>{i.detail}</span>
</li>
))}
</ul>
</CardContent>
</Card>
);
}
+16
View File
@@ -0,0 +1,16 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string, body?: unknown): Promise<boolean> {
const res = await fetch(url, { method, ...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) });
if (res.ok) return true;
const json = await res.json().catch(() => ({}));
toast.error(json.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const cancelBenchmark = (id: string) => call(`/api/benchmarks/${id}/cancel`, "POST");
export const deleteBenchmark = (id: string) => call(`/api/benchmarks/${id}`, "DELETE");
export const renameBenchmark = (id: string, label: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { label });
export const describeBenchmark = (id: string, description: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { description });
+260
View File
@@ -0,0 +1,260 @@
"use client";
import { GaugeIcon, GitCompareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { NativeSelect } from "@/components/ui/native-select";
import { LocalTime } from "@/components/local-time";
import { buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { BenchmarkRow } from "@/lib/benchmarks";
import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
import { cn } from "@/lib/utils";
export type ListRow = Omit<
BenchmarkRow,
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
> & {
createdAt: string;
startedAt: string | null;
finishedAt: string | null;
cancelRequestedAt: string | null;
};
const MAX_COMPARE = 16;
const fmt = (v: number | null | undefined, digits = 1) =>
v == null ? "–" : v.toFixed(digits);
/** All runs with their headline numbers; polls while something is queued or running. */
export function BenchmarkList({
rows: initial,
compact,
}: {
rows: ListRow[];
compact?: boolean;
}) {
const [rows, setRows] = useState(initial);
const [selected, setSelected] = useState<string[]>([]);
// "" = everything, "-" = started in Kaname, else a token name.
const [by, setBy] = useState("");
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
const tokens = [
...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
].sort();
const shown = rows.filter(
(r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
);
useEffect(() => {
if (!busy || compact) return;
const t = setInterval(async () => {
const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(
() => null,
);
if (res?.ok) setRows(await res.json());
}, 3_000);
return () => clearInterval(t);
}, [busy, compact]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<GaugeIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
No benchmarks yet. Open a running{" "}
<Link href="/deployments" className="underline">
deployment
</Link>{" "}
and start one there.
</p>
</Card>
);
}
const toggle = (id: string) =>
setSelected((s) =>
s.includes(id)
? s.filter((x) => x !== id)
: s.length < MAX_COMPARE
? [...s, id]
: s,
);
const comparable = rows.filter((r) => r.state === "completed");
return (
<div className="flex flex-col gap-3">
{!compact && (comparable.length > 1 || tokens.length > 0) && (
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
<span className="text-muted-foreground">
{selected.length === 0
? "Select completed runs to compare them."
: `${selected.length} selected (up to ${MAX_COMPARE}).`}
</span>
<span className="flex items-center gap-2">
{tokens.length > 0 && (
<NativeSelect
value={by}
onChange={(e) => setBy(e.target.value)}
className="h-8 text-xs"
aria-label="Requested by"
>
<option value="">Requested by anyone</option>
<option value="-">Started in Kaname</option>
{tokens.map((t) => (
<option key={t} value={t}>
{t} (API)
</option>
))}
</NativeSelect>
)}
<Link
href={`/benchmarks/compare?ids=${selected.join(",")}`}
className={cn(
buttonVariants({ size: "sm" }),
selected.length < 2 && "pointer-events-none opacity-50",
)}
aria-disabled={selected.length < 2}
>
<GitCompareIcon />
Compare
</Link>
</span>
</div>
)}
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
{!compact && <TableHead className="w-8" />}
<TableHead>Run</TableHead>
<TableHead className="hidden lg:table-cell">Settings</TableHead>
<TableHead
className="text-right"
title="Weighted single-stream decode speed"
>
Decode t/s
</TableHead>
<TableHead
className="text-right"
title="Median time to first token"
>
TTFT
</TableHead>
<TableHead
className="hidden text-right md:table-cell"
title="Prompt processing at the deepest measured input"
>
Prefill t/s
</TableHead>
<TableHead
className="hidden text-right md:table-cell"
title="Best aggregate throughput under parallel load"
>
Peak t/s
</TableHead>
<TableHead className="w-28">State</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{shown.map((r) => {
const h = headline(r.summary);
const s = r.snapshot;
return (
<TableRow
key={r.id}
data-state={selected.includes(r.id) ? "selected" : undefined}
>
{!compact && (
<TableCell>
<Checkbox
checked={selected.includes(r.id)}
disabled={r.state !== "completed"}
onCheckedChange={() => toggle(r.id)}
aria-label={`Select ${r.label ?? s.deploymentName} for comparison`}
/>
</TableCell>
)}
<TableCell className="whitespace-normal">
<Link
href={`/benchmarks/${r.id}`}
className="font-medium hover:underline"
>
{r.label ?? s.deploymentName}
</Link>
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
{r.label && `${s.deploymentName} · `}
{s.repoId} · <LocalTime value={r.createdAt} />
<RequestedByBadge
name={r.requestedBy}
className="h-4 text-[10px]"
/>
</div>
</TableCell>
<TableCell className="hidden max-w-md whitespace-normal lg:table-cell">
<div className="flex flex-wrap gap-1">
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">
{s.runtimeName}
</span>
{configChips(s).map((c) => (
<span
key={c}
className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground"
>
{c}
</span>
))}
</div>
<div className="mt-0.5 text-[11px] text-muted-foreground">
{describeSettings(r.settings)}
</div>
</TableCell>
<TableCell className="text-right font-medium tabular-nums">
{r.kind === "eval" ? (
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
) : (
fmt(h.decode)
)}
</TableCell>
<TableCell className="text-right tabular-nums">
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
</TableCell>
<TableCell
className="hidden text-right tabular-nums md:table-cell"
title={
h.prefill ? `at ${h.prefill.depth} tokens` : undefined
}
>
{fmt(h.prefill?.tps, 0)}
</TableCell>
<TableCell
className="hidden text-right tabular-nums md:table-cell"
title={h.peak ? `at ${h.peak.level} parallel` : undefined}
>
{fmt(h.peak?.tps)}
</TableCell>
<TableCell>
<BenchmarkStateBadge
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
</div>
);
}
+234
View File
@@ -0,0 +1,234 @@
import type { Metadata } from "next";
import Link from "next/link";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { getBenchmarks } from "@/lib/benchmarks";
import { metaRows } from "@/lib/benchmark-meta";
import { SECTION_LABEL } from "@/lib/quality-view";
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Compare benchmarks" };
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null, runIndex?: number) => number | null };
/** Differences smaller than this are shown without color: below what a single run can resolve. */
const NOISE_PCT = 2;
function Delta({ v, base, higherIsBetter }: { v: number | null; base: number | null; higherIsBetter: boolean }) {
const d = deltaPct(v, base);
if (d == null) return null;
const good = higherIsBetter ? d > 0 : d < 0;
return (
<span
className={cn(
"ml-1.5 text-[11px] tabular-nums",
Math.abs(d) < NOISE_PCT ? "text-muted-foreground" : good ? "text-emerald-600 dark:text-emerald-400" : "text-destructive",
)}
>
{d > 0 ? "+" : ""}
{d.toFixed(1)}%
</span>
);
}
export default async function ComparePage({ searchParams }: PageProps<"/benchmarks/compare">) {
const { ids } = await searchParams;
const runs = await getBenchmarks(
String(ids ?? "")
.split(",")
.filter(Boolean)
.slice(0, 16),
);
if (runs.length < 2) {
return (
<p className="text-sm text-muted-foreground">
Pick at least two completed runs on the{" "}
<Link href="/benchmarks" className="underline">
Benchmarks
</Link>{" "}
page.
</p>
);
}
const sums = runs.map((r) => r.summary);
const depths = [...new Set(sums.flatMap((s) => s?.prefill.filter((p) => !p.skipped).map((p) => p.target_depth) ?? []))].sort((a, b) => a - b);
const levels = [...new Set(sums.flatMap((s) => s?.concurrency.map((c) => c.level) ?? []))].sort((a, b) => a - b);
const categories = [...new Set(sums.flatMap((s) => s?.single.map((c) => c.category) ?? []))];
const groups: { group: string; rows: Metric[] }[] = [
{
group: "Headline",
rows: [
{ label: "Prefill (deepest prompt)", unit: "t/s", higherIsBetter: true, digits: 0, get: (s) => headline(s).prefill?.tps ?? null },
{ label: "Decode (weighted)", unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => headline(s).decode },
{ label: "Time to first token", unit: "ms", higherIsBetter: false, digits: 0, get: (s) => headline(s).ttftMs },
],
},
{
group: "Decode per category",
rows: categories.map((c) => ({ label: c, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.single.find((x) => x.category === c)?.decode_med ?? null })),
},
{
group: "Prompt processing",
rows: depths.map((d) => ({
label: `${d.toLocaleString()} tokens`,
unit: "t/s",
higherIsBetter: true,
digits: 0,
get: (s) => s?.prefill.find((p) => p.target_depth === d && !p.skipped)?.pp_med ?? null,
})),
},
{
group: "Parallel requests (total)",
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
},
];
// Quality evals: the score and each section's pass rate (only when some of the runs are evals).
const quality = runs.map((r) => r.quality);
if (quality.some(Boolean)) {
const sections = [...new Set(quality.flatMap((q) => q?.sections.map((s) => s.section) ?? []))];
groups.push({
group: `Quality (${[...new Set(quality.filter(Boolean).map((q) => q!.evalSet))].join(", ")})`,
rows: [
{ label: "Score", unit: "%", higherIsBetter: true, digits: 1, get: (_s, i) => quality[i!]?.score ?? null },
...sections.map((sec) => ({
label: SECTION_LABEL[sec],
unit: "%",
higherIsBetter: true,
digits: 1,
get: (_s: BenchmarkSummary | null, i?: number) => quality[i!]?.sections.find((x) => x.section === sec)?.score ?? null,
})),
],
});
}
const metrics = groups.filter((g) => g.rows.length > 0);
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
const metaByRun = runs.map((r) => (r.meta ? metaRows(r.meta) : null));
const metaKeys = [...new Map(metaByRun.flatMap((rows) => rows ?? []).map((x) => [x.key, x.label])).entries()];
const metaTable = metaKeys.map(([key, label]) => ({ key, label, values: metaByRun.map((rows) => (rows ? (rows.find((x) => x.key === key)?.value ?? null) : null)) }));
const configRows = CONFIG_ROWS.map((row) => ({ row, values: runs.map((r) => row.value(r.snapshot)) })).filter((x) => x.values.some((v) => v != null));
const corpora = new Set(sums.map((s) => s?.corpusVersion).filter(Boolean));
const anyQuick = runs.some((r) => r.summary?.quick);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">Compare benchmarks</h1>
<p className="text-sm text-muted-foreground">
Differences are against the first run. Separate runs aren&apos;t paired in time, so differences below ~{NOISE_PCT}% are within normal noise.
</p>
{corpora.size > 1 && <p className="text-sm text-destructive">These runs used different prompt sets (corpus versions), so their numbers aren&apos;t comparable.</p>}
{anyQuick && <p className="text-sm text-amber-700 dark:text-amber-300">Some runs are quick runs (5 passes); their numbers are rough.</p>}
</div>
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-48" />
{runs.map((r, i) => (
<TableHead key={r.id} className="align-top whitespace-normal">
<Link href={`/benchmarks/${r.id}`} className="font-medium text-foreground hover:underline">
{r.label ?? r.snapshot.deploymentName}
</Link>
<div className="flex flex-wrap items-center gap-1 py-1 text-[11px] font-normal">
{i === 0 && <span className="rounded-4xl bg-primary px-1.5 text-primary-foreground">baseline</span>}
<BenchmarkStateBadge state={r.state} />
</div>
<div className="text-[11px] font-normal text-muted-foreground">{describeSettings(r.settings)}</div>
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{metaTable.length > 0 && (
<>
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Hardware &amp; runtime
</TableCell>
</TableRow>
{metaTable.map(({ key, label, values }) => {
const differs = new Set(values.map((v) => v ?? "")).size > 1;
return (
<TableRow key={`meta-${key}`} className={cn(differs && "bg-amber-500/5")}>
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{label}</TableCell>
{values.map((v, i) => (
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
{v ?? <span className="text-muted-foreground">not recorded</span>}
</TableCell>
))}
</TableRow>
);
})}
</>
)}
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Settings
</TableCell>
</TableRow>
{configRows.map(({ row, values }) => {
const differs = new Set(values.map((v) => v ?? "")).size > 1;
return (
<TableRow key={row.key} className={cn(differs && "bg-amber-500/5")}>
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{row.label}</TableCell>
{values.map((v, i) => (
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
{v ?? <span className="text-muted-foreground">default</span>}
</TableCell>
))}
</TableRow>
);
})}
{metrics.map((g) => (
<MetricGroup key={g.group} group={g.group} rows={g.rows} sums={sums} cols={runs.length} />
))}
</TableBody>
</Table>
</Card>
</div>
);
}
function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[]; sums: (BenchmarkSummary | null)[]; cols: number }) {
return (
<>
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={cols + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
{group}
</TableCell>
</TableRow>
{rows.map((m) => {
const vals = sums.map((s, i) => m.get(s, i));
const present = vals.filter((v): v is number => v != null);
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
return (
<TableRow key={m.label}>
<TableCell className="text-xs">{m.label}</TableCell>
{vals.map((v, i) => (
<TableCell key={i} className="tabular-nums whitespace-nowrap">
{v == null ? (
<span className="text-muted-foreground">–</span>
) : (
<>
<span className={cn(v === best && "font-semibold")}>
{v.toFixed(m.digits)} <span className="text-[11px] text-muted-foreground">{m.unit}</span>
</span>
{i > 0 && <Delta v={v} base={vals[0]} higherIsBetter={m.higherIsBetter} />}
</>
)}
</TableCell>
))}
</TableRow>
);
})}
</>
);
}
+21
View File
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { listBenchmarks } from "@/lib/benchmarks";
import { BenchmarkList } from "./benchmark-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Benchmarks" };
export default async function BenchmarksPage() {
const rows = await listBenchmarks();
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">Benchmarks</h1>
<p className="text-sm text-muted-foreground">
BetterBench runs against your deployments. Start one from a running deployment; select runs to compare their settings and numbers.
</p>
</div>
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
@@ -0,0 +1,13 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getSweep } from "@/lib/sweeps";
import { SweepDetail } from "./sweep-detail";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Sweep · Benchmarks" };
export default async function SweepPage({ params }: PageProps<"/benchmarks/sweeps/[id]">) {
const data = await getSweep((await params).id);
if (!data) notFound();
return <SweepDetail initial={JSON.parse(JSON.stringify(data))} />;
}
@@ -0,0 +1,305 @@
"use client";
import { GitCompareIcon, Grid3x3Icon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { BarChart } from "@/components/bar-chart";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { metaRows } from "@/lib/benchmark-meta";
import { describeSettings, headline } from "@/lib/benchmark-view";
import type { benchmarkSweeps, BenchmarkSummary, QualityResult, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { cn } from "@/lib/utils";
type Sweep = typeof benchmarkSweeps.$inferSelect;
type Run = {
id: string;
state: string;
summary: BenchmarkSummary | null;
resources: ResourceStats | null;
phase: string | null;
error: string | null;
meta: RunMeta | null;
quality: QualityResult | null;
};
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
pending: "Waiting",
deploying: "Deploying",
benchmarking: "Benchmarking",
evaluating: "Quality eval",
done: "Done",
failed: "Failed",
skipped: "Skipped",
};
type Row = {
v: SweepVariant;
run: Run | null;
decode: number | null;
ttft: number | null;
prefill: number | null;
peak: number | null;
cpu: number | null;
ram: number | null;
vram: number | null;
power: number | null;
temp: number | null;
quality: number | null;
};
function rowsOf(data: SweepData): Row[] {
return data.sweep.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId) ?? null;
const ev = data.runs.find((r) => r.id === v.evalRunId) ?? null;
const h = headline(run?.summary ?? null);
const c = run?.resources?.containers.find((x) => x.side === "a");
const g = run?.resources?.gpus ?? [];
return {
v,
run,
decode: h.decode,
ttft: h.ttftMs,
prefill: h.prefill?.tps ?? null,
peak: h.peak?.tps ?? null,
cpu: c?.cpuAvg ?? null,
ram: c?.memPeakBytes ?? null,
vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
quality: ev?.quality?.score ?? null,
};
});
}
/**
* Recorded setup (GPU, PCIe, engine version, quant, KV cache, context, concurrency): values shared by
* every variant go above the table, the ones that differ become columns.
*/
function setupOf(rows: Row[]) {
const per = rows.map((r) => (r.run?.meta ? metaRows(r.run.meta).filter((x) => x.key !== "image" && x.key !== "digest") : null));
const keys = [...new Map(per.flatMap((x) => x ?? []).map((x) => [x.key, x.label])).entries()];
const recorded = per.filter((x) => x != null);
const value = (i: number, key: string) => per[i]?.find((x) => x.key === key)?.value ?? null;
const differs = keys.filter(([key]) => new Set(recorded.map((x) => x.find((y) => y.key === key)?.value ?? "")).size > 1);
const shared = keys.filter((k) => !differs.includes(k)).map(([key, label]) => ({ label, value: recorded[0]?.find((y) => y.key === key)?.value ?? null }));
return { shared: recorded.length ? shared : [], columns: differs.map(([key, label]) => ({ key, label })), value };
}
/** Best value per column (higher or lower is better), to set it in bold. */
function best(rows: Row[], key: keyof Row, higher: boolean): number | null {
const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number");
if (vals.length < 2) return null;
return higher ? Math.max(...vals) : Math.min(...vals);
}
export function SweepDetail({ initial }: { initial: SweepData }) {
const router = useRouter();
const [data, setData] = useState(initial);
const [busy, setBusy] = useState(false);
const { sweep } = data;
const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running";
useEffect(() => {
if (!active) return;
const t = setInterval(async () => {
const res = await fetch(`/api/sweeps/${sweep.id}`, { cache: "no-store" }).catch(() => null);
if (res?.ok) setData(await res.json());
}, 3_000);
return () => clearInterval(t);
}, [sweep.id, active]);
async function act(path: string, method: string, done: () => void) {
setBusy(true);
try {
const res = await fetch(path, { method });
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Failed (${res.status})`);
done();
} finally {
setBusy(false);
}
}
const rows = rowsOf(data);
const setup = setupOf(rows);
const finished = rows.filter((r) => r.decode != null);
const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed"));
const bestOf = {
decode: best(rows, "decode", true),
ttft: best(rows, "ttft", false),
prefill: best(rows, "prefill", true),
peak: best(rows, "peak", true),
cpu: best(rows, "cpu", false),
ram: best(rows, "ram", false),
vram: best(rows, "vram", false),
power: best(rows, "power", false),
temp: best(rows, "temp", false),
quality: best(rows, "quality", true),
};
const hasQuality = !!sweep.settings.quality;
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
);
const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length;
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex flex-col gap-1">
<h1 className="flex items-center gap-2 text-xl font-semibold">
<Grid3x3Icon className="size-5 text-muted-foreground" />
{sweep.label ?? `Sweep of ${sweep.base.name}`}
</h1>
<p className="text-sm text-muted-foreground">
{sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "}
{sweep.baseDeploymentId ? (
<Link href={`/deployments/${sweep.baseDeploymentId}`} className="underline">
{sweep.base.name}
</Link>
) : (
sweep.base.name
)}
</p>
</div>
<div className="flex items-center gap-2">
<RequestedByBadge name={sweep.requestedBy} />
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
{runIds.length >= 2 && (
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
<GitCompareIcon />
Compare in detail
</Link>
)}
{active ? (
<Button variant="outline" size="sm" disabled={busy || !!sweep.cancelRequestedAt} onClick={() => act(`/api/sweeps/${sweep.id}/cancel`, "POST", () => router.refresh())}>
<SquareIcon />
Cancel
</Button>
) : (
<Button variant="outline" size="sm" disabled={busy} onClick={() => act(`/api/sweeps/${sweep.id}`, "DELETE", () => router.push("/benchmarks"))}>
<Trash2Icon />
Delete
</Button>
)}
</div>
</div>
{active && (
<p className="text-sm text-muted-foreground">
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
</p>
)}
{sweep.state === "pending_approval" && (
<AgentApprovalBar
requestedBy={sweep.requestedBy}
what={`run a sweep of ${rows.length} variants from ${sweep.base.name} (${sweep.params.map((p) => `${p.key}: ${p.values.join(", ")}`).join("; ")}${sweep.timeLimitS ? `, at most ${Math.round(sweep.timeLimitS / 60)} min` : ""}); each variant is deployed, benchmarked and removed`}
base={`/api/sweeps/${sweep.id}`}
/>
)}
{sweep.error && <p className="text-sm text-destructive">{sweep.error}</p>}
{finished.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Generation speed by variant</CardTitle>
<CardDescription>Single-stream decode, tokens per second (BetterBench combined score). Higher is better.</CardDescription>
</CardHeader>
<CardContent>
<BarChart
axisLabel="Decode t/s"
rows={finished.map((r) => ({
label: r.v.label,
value: r.decode,
valueLabel: r.decode!.toFixed(1),
details: [r.ttft != null ? `TTFT ${r.ttft.toFixed(0)} ms` : "", r.ram != null ? `Peak RAM ${formatBytes(r.ram)}` : ""].filter(Boolean),
}))}
/>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Variants</CardTitle>
<CardDescription>Best value per column in bold. Resource figures are averages/peaks over the run.</CardDescription>
{setup.shared.length > 0 && (
<p className="text-xs text-muted-foreground">
{setup.shared
.filter((x) => x.value)
.map((x) => `${x.label}: ${x.value}`)
.join(" · ")}
</p>
)}
</CardHeader>
<CardContent className="overflow-x-auto px-0">
<table className="w-full text-sm">
<thead className="text-xs text-muted-foreground">
<tr className="border-b">
<th className="px-3 py-2 text-left font-medium">Variant</th>
<th className="px-3 py-2 text-left font-medium">State</th>
{setup.columns.map((c) => (
<th key={c.key} className="px-3 py-2 text-left font-medium">
{c.label}
</th>
))}
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
{hasQuality && <th className="px-3 py-2 text-right font-medium">Quality</th>}
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
<th className="px-3 py-2 text-right font-medium">CPU cores</th>
<th className="px-3 py-2 text-right font-medium">Peak RAM</th>
<th className="px-3 py-2 text-right font-medium">Peak VRAM</th>
<th className="px-3 py-2 text-right font-medium">GPU power</th>
<th className="px-3 py-2 text-right font-medium">Peak temp</th>
</tr>
</thead>
<tbody>
{rows.map((r, i) => (
<tr key={r.v.index} className="border-b last:border-0">
<td className="px-3 py-2 font-mono text-xs">
{r.v.runId ? (
<Link href={`/benchmarks/${r.v.runId}`} className="underline-offset-2 hover:underline">
{r.v.label}
</Link>
) : (
r.v.label
)}
</td>
<td className="px-3 py-2 text-xs text-muted-foreground" title={r.v.error ?? r.run?.error ?? undefined}>
{VARIANT_STATE[r.v.state]}
{r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""}
{(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""}
</td>
{setup.columns.map((c) => (
<td key={c.key} className="px-3 py-2 font-mono text-xs">
{setup.value(i, c.key) ?? "–"}
</td>
))}
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
{hasQuality && cell(r.quality, bestOf.quality, (x) => `${x}%`)}
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
{cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
{cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))}
{cell(r.ram, bestOf.ram, (x) => formatBytes(x))}
{cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)}
{cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)}
{cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)}
</tr>
))}
</tbody>
</table>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,36 @@
import type { Metadata } from "next";
import { listDeployableModels, listDeployments } from "@/lib/deployments";
import { SweepForm, type SweepBase } from "./sweep-form";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New sweep" };
export default async function NewSweepPage({ searchParams }: PageProps<"/benchmarks/sweeps/new">) {
const { deployment } = await searchParams;
const [deployments, models] = await Promise.all([listDeployments(), listDeployableModels()]);
const bases: SweepBase[] = deployments
.filter((d) => !d.sweepId)
.map((d) => ({
id: d.id,
name: d.name,
engine: d.engine,
accelerator: d.accelerator,
repoId: d.repoId,
options: d.options,
cpus: d.cpus,
memoryMb: d.memoryMb,
ggufFiles: models.find((m) => m.id === d.modelId)?.candidates.gguf.map((g) => g.path) ?? [],
}));
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">New sweep</h1>
<p className="max-w-3xl text-sm text-muted-foreground">
Vary one or two settings of a deployment. Kaname deploys each variant in turn, benchmarks it with BetterBench, removes it again and compares all of them,
including the resources each one used.
</p>
</div>
<SweepForm bases={bases} initialBaseId={typeof deployment === "string" ? deployment : undefined} />
</div>
);
}
@@ -0,0 +1,257 @@
"use client";
import { Grid3x3Icon, PlusIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { BenchmarkPhase, DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
import { expandSweep, MAX_SWEEP_VARIANTS, splitValues, SweepError, sweepKeysFor } from "@/lib/sweep";
export type SweepBase = {
id: string;
name: string;
engine: RuntimeEngine;
accelerator: RuntimeAccelerator;
repoId: string;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
ggufFiles: string[];
};
const PHASES: { id: BenchmarkPhase; label: string }[] = [
{ id: "decode", label: "Generation" },
{ id: "prefill", label: "Prompt processing" },
{ id: "concurrency", label: "Parallel requests" },
];
/** The base's current value of a sweep key, shown as a hint. */
function currentValue(base: SweepBase, key: string): string {
const o = base.options;
const v: Record<string, unknown> = {
contextSize: o.contextSize,
modelFile: o.modelFile,
kvCache: o.cacheTypeK ?? "f16",
threads: o.threads ?? "auto",
parallel: o.parallel ?? "auto",
batchSize: o.batchSize ?? "default",
ubatchSize: o.ubatchSize ?? "default",
flashAttn: o.flashAttn ?? "auto",
cacheRamMb: o.cacheRamMb ?? "8192 (default)",
gpuLayers: o.gpuLayers ?? "auto",
dtype: o.dtype ?? "runtime default",
maxNumSeqs: o.maxNumSeqs ?? "default",
kvCacheGb: o.kvCacheGb ?? "runtime default",
gpuMemoryUtilization: o.gpuMemoryUtilization ?? "0.9",
cpus: base.cpus ?? "no limit",
};
return String(v[key] ?? "");
}
type Param = { key: string; text: string; files: string[] };
export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initialBaseId?: string }) {
const router = useRouter();
const [baseId, setBaseId] = useState(initialBaseId && bases.some((b) => b.id === initialBaseId) ? initialBaseId : (bases[0]?.id ?? ""));
const base = bases.find((b) => b.id === baseId) ?? null;
const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
const [params, setParams] = useState<Param[]>([{ key: "contextSize", text: "", files: [] }]);
const [label, setLabel] = useState("");
const [quality, setQuality] = useState(false);
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [busy, setBusy] = useState(false);
const values = (p: Param) => (p.key === "modelFile" ? p.files : splitValues(p.text));
let preview: { variants: ReturnType<typeof expandSweep> | null; error: string | null } = { variants: null, error: null };
if (base) {
try {
preview = { variants: expandSweep(params.map((p) => ({ key: p.key, values: values(p) })), base.engine, base.accelerator, { modelFiles: base.ggufFiles }), error: null };
} catch (err) {
preview = { variants: null, error: err instanceof SweepError ? err.message : String(err) };
}
}
const setParam = (i: number, patch: Partial<Param>) => setParams((ps) => ps.map((p, j) => (j === i ? { ...p, ...patch } : p)));
async function submit() {
if (!base || !preview.variants) return;
setBusy(true);
try {
const res = await fetch("/api/sweeps", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
baseDeploymentId: base.id,
label: label.trim() || null,
params: params.map((p) => ({ key: p.key, values: values(p) })),
quick: mode === "quick",
passes: mode === "custom" ? Number(passes) || 10 : null,
phases: phases.length === PHASES.length ? [] : phases,
quality,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
router.push(`/benchmarks/sweeps/${json.id}`);
} finally {
setBusy(false);
}
}
if (bases.length === 0) return <p className="text-sm text-muted-foreground">Create a deployment first; a sweep varies its settings.</p>;
return (
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Base deployment</CardTitle>
<CardDescription>Every variant starts from its settings. It doesn&apos;t need to be running.</CardDescription>
</CardHeader>
<CardContent>
<NativeSelect value={baseId} onChange={(e) => setBaseId(e.target.value)} aria-label="Base deployment">
{bases.map((b) => (
<option key={b.id} value={b.id}>
{b.name} · {b.repoId}
</option>
))}
</NativeSelect>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>What to vary</CardTitle>
<CardDescription>One or two settings; every combination becomes a variant (up to {MAX_SWEEP_VARIANTS}).</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{base &&
params.map((p, i) => {
const def = keys.find((k) => k.key === p.key);
return (
<div key={i} className="flex flex-col gap-2 rounded-lg border px-3 py-3">
<div className="flex items-center gap-2">
<NativeSelect value={p.key} onChange={(e) => setParam(i, { key: e.target.value, text: "", files: [] })} aria-label={`Setting ${i + 1}`}>
{keys
.filter((k) => k.key === p.key || !params.some((q) => q.key === k.key))
.map((k) => (
<option key={k.key} value={k.key}>
{k.label}
</option>
))}
</NativeSelect>
{params.length > 1 && (
<Button variant="ghost" size="icon-sm" aria-label="Remove setting" onClick={() => setParams((ps) => ps.filter((_, j) => j !== i))}>
<XIcon />
</Button>
)}
</div>
{p.key === "modelFile" ? (
<div className="flex flex-col gap-1">
{base.ggufFiles.map((f) => (
<label key={f} className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox checked={p.files.includes(f)} onCheckedChange={(v) => setParam(i, { files: v ? [...p.files, f] : p.files.filter((x) => x !== f) })} />
<span className="font-mono text-xs">{quantGroup(f) ?? f}</span>
</label>
))}
{base.ggufFiles.length < 2 && <p className="text-xs text-muted-foreground">Only one GGUF file is downloaded; download more quants to compare them.</p>}
</div>
) : (
<Input value={p.text} onChange={(e) => setParam(i, { text: e.target.value })} placeholder={def?.hint} aria-label="Values" className="font-mono text-sm" />
)}
<p className="text-xs text-muted-foreground">Base value: {currentValue(base, p.key)}</p>
</div>
);
})}
{params.length < 2 && base && (
<Button
variant="outline"
size="sm"
className="self-start"
onClick={() => setParams((ps) => [...ps, { key: keys.find((k) => !ps.some((q) => q.key === k.key))?.key ?? "threads", text: "", files: [] }])}
>
<PlusIcon />
Vary a second setting
</Button>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Benchmark per variant</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && <Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes" />}
</div>
<div className="flex flex-wrap gap-4">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} />
{p.label}
</label>
))}
</div>
<label className="flex cursor-pointer items-start gap-2 text-sm">
<Checkbox checked={quality} onCheckedChange={(v) => setQuality(v === true)} className="mt-0.5" />
<span className="flex flex-col">
<span>Also run the quality eval on each variant</span>
<span className="text-xs text-muted-foreground">Tool calling, coding and long-context retrieval, after the speed run (adds a few minutes per variant).</span>
</span>
</label>
<div className="flex flex-col gap-1.5">
<Label htmlFor="sw-label">Label</Label>
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
</div>
</CardContent>
</Card>
</div>
<Card className="lg:sticky lg:top-4">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<Grid3x3Icon className="size-4 text-muted-foreground" />
{preview.variants ? `${preview.variants.length} variants` : "Variants"}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{preview.error ? (
<p className="text-xs text-muted-foreground">{preview.error}</p>
) : (
<ol className="flex flex-col gap-1">
{preview.variants?.map((v) => (
<li key={v.index} className="flex gap-2 text-xs">
<span className="w-5 text-right text-muted-foreground tabular-nums">{v.index + 1}</span>
<span className="font-mono">{v.label}</span>
</li>
))}
</ol>
)}
<p className="text-xs text-muted-foreground">
Variants run one after another, each in its own temporary deployment{base?.memoryMb ? " (memory limit: the base's, raised where a variant needs more)" : ""}.
{mode !== "quick" && " Full runs on a CPU can take hours per variant."}
</p>
<Button onClick={submit} disabled={!preview.variants || busy || phases.length === 0}>
<Grid3x3Icon />
Start sweep
</Button>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,286 @@
"use client";
import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select";
import { abHeadline } from "@/lib/ab-report";
import { headline } from "@/lib/benchmark-view";
import type { BenchmarkPhase } from "@/lib/db/schema";
import { QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
import type { ListRow } from "../../benchmarks/benchmark-list";
const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
{ id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
{ id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
];
type Mode = "run" | "ab" | "quality" | "sweep";
type Peer = { id: string; name: string; state: string; modelId: string };
/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
export function BenchmarkCard({ deploymentId, modelId, running, initial }: { deploymentId: string; modelId: string; running: boolean; initial: ListRow[] }) {
const router = useRouter();
const [tab, setTab] = useState<Mode>("run");
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [label, setLabel] = useState("");
const [description, setDescription] = useState("");
const [busy, setBusy] = useState(false);
const [runs, setRuns] = useState(initial);
const [peers, setPeers] = useState<Peer[] | null>(null);
const [peerId, setPeerId] = useState("");
const [mde, setMde] = useState("1");
const [maxPairs, setMaxPairs] = useState("200");
const [sections, setSections] = useState<QualitySection[]>([...QUALITY_SECTIONS]);
const active = runs.some((r) => r.state === "queued" || r.state === "running");
useEffect(() => {
const t = setInterval(
async () => {
const res = await fetch(`/api/benchmarks?deployment=${deploymentId}`, { cache: "no-store" }).catch(() => null);
if (res?.ok) setRuns(await res.json());
},
active ? 3_000 : 15_000,
);
return () => clearInterval(t);
}, [deploymentId, active]);
// Other deployments of the same model (A/B partners).
useEffect(() => {
if (tab !== "ab") return;
let stop = false;
void fetch("/api/deployments", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : []))
.then((rows: Peer[]) => {
if (stop) return;
const list = rows.filter((p) => p.modelId === modelId && p.id !== deploymentId);
setPeers(list);
setPeerId((cur) => cur || list.find((p) => p.state === "running")?.id || "");
});
return () => {
stop = true;
};
}, [tab, modelId, deploymentId]);
async function start(body: Record<string, unknown>) {
setBusy(true);
try {
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, description: description.trim() || null, ...body }) });
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
router.push(`/benchmarks/${json.id}`);
} finally {
setBusy(false);
}
}
const peer = peers?.find((p) => p.id === peerId);
const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
{ id: "run", label: "Run", icon: GaugeIcon },
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
{ id: "quality", label: "Quality", icon: BadgeCheckIcon },
{ id: "sweep", label: "Sweep", icon: Grid3x3Icon },
];
return (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<GaugeIcon className="size-4 text-muted-foreground" />
Benchmark
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
<div className="inline-flex self-start rounded-lg bg-muted p-1" role="tablist">
{TABS.map((t) => (
<button
key={t.id}
type="button"
role="tab"
aria-selected={tab === t.id}
onClick={() => setTab(t.id)}
className={cn("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs", tab === t.id ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground")}
>
<t.icon className="size-3.5" />
{t.label}
</button>
))}
</div>
{tab === "run" && (
<>
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && (
<Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
)}
</div>
<div className="flex flex-col gap-1.5">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-start gap-2">
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} className="mt-0.5" />
<span className="flex flex-col">
<span>{p.label}</span>
<span className="text-xs text-muted-foreground">{p.hint}</span>
</span>
</label>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
<Button
onClick={() =>
start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
}
disabled={!running || busy || phases.length === 0}
>
<GaugeIcon />
Run benchmark
</Button>
<p className="text-xs text-muted-foreground">
{running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."}
</p>
</>
)}
{tab === "ab" && (
<>
<p className="text-xs text-muted-foreground">
Paired A/B: the same prompts go to this deployment (A) and another one of the same model (B), alternating, until the difference is known to ±the target. Both
must be running and fit in memory together.
</p>
{peers === null ? (
<p className="text-xs text-muted-foreground">Loading…</p>
) : peers.length === 0 ? (
<p className="text-xs text-muted-foreground">
No other deployment of this model. Create one with the setting you want to compare (e.g. a different KV cache type), or run a sweep.
</p>
) : (
<>
<NativeSelect value={peerId} onChange={(e) => setPeerId(e.target.value)} aria-label="Deployment B">
<option value="">Choose B…</option>
{peers.map((p) => (
<option key={p.id} value={p.id}>
{p.name} {p.state !== "running" ? `(${p.state})` : ""}
</option>
))}
</NativeSelect>
{peer && peer.state !== "running" && (
<p className="text-xs text-amber-700 dark:text-amber-300">
{peer.name} isn&apos;t running.{" "}
<Link href={`/deployments/${peer.id}`} className="underline">
Start it
</Link>{" "}
first.
</p>
)}
<div className="grid grid-cols-2 gap-2">
<label className="flex flex-col gap-1 text-xs">
<span className="text-muted-foreground">Target precision (±%)</span>
<Input value={mde} onChange={(e) => setMde(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" />
</label>
<label className="flex flex-col gap-1 text-xs">
<span className="text-muted-foreground">Max pairs</span>
<Input value={maxPairs} onChange={(e) => setMaxPairs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
</label>
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
<Button
onClick={() => start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
disabled={!running || busy || !peer || peer.state !== "running"}
>
<GitCompareArrowsIcon />
Start A/B
</Button>
</>
)}
{!running && <p className="text-xs text-muted-foreground">Start this deployment (A) first.</p>}
</>
)}
{tab === "quality" && (
<>
<p className="text-xs text-muted-foreground">
A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality,
next to the speed numbers.
</p>
<div className="flex flex-col gap-1.5">
{QUALITY_SECTIONS.map((s) => (
<label key={s} className="flex cursor-pointer items-start gap-2">
<Checkbox checked={sections.includes(s)} onCheckedChange={(v) => setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
<span className="flex flex-col">
<span>{SECTION_LABEL[s]}</span>
<span className="text-xs text-muted-foreground">{SECTION_HINT[s]}</span>
</span>
</label>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Button onClick={() => start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={!running || busy || sections.length === 0}>
<BadgeCheckIcon />
Run quality eval
</Button>
{!running && <p className="text-xs text-muted-foreground">Start the deployment to evaluate it.</p>}
</>
)}
{tab === "sweep" && (
<>
<p className="text-xs text-muted-foreground">
Vary one or two settings (context size, KV cache type, threads, quant, GPU layers, …). Kaname deploys each variant in turn, benchmarks it, removes it again, and
compares all of them. This deployment doesn&apos;t need to run.
</p>
<Link href={`/benchmarks/sweeps/new?deployment=${deploymentId}`} className={buttonVariants()}>
<Grid3x3Icon />
Set up a sweep
</Link>
</>
)}
{runs.length > 0 && (
<div className="flex flex-col gap-1 border-t pt-3">
{runs.slice(0, 5).map((r) => {
const h = headline(r.summary);
return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
<span className="min-w-0 truncate">
{r.kind !== "run" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">{r.kind === "ab" ? "A/B" : "quality"}</span>}
{r.label ?? new Date(r.createdAt).toLocaleString()}
</span>
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
{r.kind === "ab"
? r.ab && abHeadline(r.ab.decode_tps)
: r.kind === "eval"
? r.quality?.score != null && `${r.quality.score}%`
: h.decode != null && `${h.decode.toFixed(1)} t/s`}
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
</span>
</Link>
);
})}
<Link href="/benchmarks" className="self-start px-1.5 text-xs text-muted-foreground hover:text-foreground">
All benchmarks →
</Link>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,403 @@
"use client";
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, ShieldCheckIcon, ShieldIcon, SquareIcon, Trash2Icon } from "lucide-react";
import { toast } from "sonner";
import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LiveLog } from "@/components/live-log";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
import type { ListRow } from "../../benchmarks/benchmark-list";
import { BenchmarkCard } from "./benchmark-card";
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold tabular-nums">{value}</span>
{children}
</div>
);
}
export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment; benchmarks: ListRow[] }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
useEffect(() => {
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
if (res?.status === 404) router.push("/deployments");
else if (res?.ok) setD(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [d.id, router]);
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
const hostname = useHostname();
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
const webUi = webUiUrl(d, hostname);
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{d.name}</h1>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
<RequestedByBadge name={d.requestedBy} />
{d.protected && (
<span className="inline-flex items-center gap-1 rounded-4xl border border-emerald-500/30 bg-emerald-500/10 px-2 text-xs text-emerald-700 dark:text-emerald-300">
<ShieldCheckIcon className="size-3" />
protected
</span>
)}
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
{d.repoId}
</Link>
{file && ` · ${file}`}
{d.options.mmproj && " · vision"}
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
</p>
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
</div>
<div className="flex flex-wrap items-center gap-2">
{webUi && (
<a
href={webUi}
target="_blank"
rel="noreferrer"
className={cn(buttonVariants({ variant: "outline" }), d.state !== "running" && "pointer-events-none opacity-50")}
aria-disabled={d.state !== "running"}
>
<ExternalLinkIcon />
Web UI
</a>
)}
{active ? (
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
<SquareIcon />
Stop
</Button>
) : (
<Button onClick={() => startDeployment(d.id)}>
<PlayIcon />
Start
</Button>
)}
<Button
variant="outline"
title={d.protected ? "Agents can't touch it now; click to allow them again" : "Agents (API tokens) can't edit, stop, delete or benchmark a protected deployment, nor crowd it out of VRAM"}
onClick={async () => {
const res = await fetch(`/api/deployments/${d.id}/protect`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ protected: !d.protected }) });
if (!res.ok) return void toast.error(`Could not change it (${res.status})`);
setD({ ...d, protected: !d.protected });
toast.success(d.protected ? "No longer protected from agents" : "Protected from agents");
}}
>
{d.protected ? <ShieldCheckIcon /> : <ShieldIcon />}
{d.protected ? "Protected" : "Protect"}
</Button>
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
aria-disabled={active}
title={active ? "Stop it first" : undefined}
>
<PencilIcon />
Edit
</Link>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteDeployment(d.id)) router.push("/deployments");
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{d.startRequestedAt && (
<AgentApprovalBar
requestedBy={d.requestedBy}
what={`start this deployment (${d.runtimeName}${file ? `, ${file}` : ""}, context ${d.options.contextSize}${d.memoryMb ? `, ${formatBytes(d.memoryMb * 2 ** 20)} RAM limit` : ""})`}
base={`/api/deployments/${d.id}`}
/>
)}
{d.state === "failed" && d.error && (
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
<div className="flex min-w-0 flex-col gap-4">
<Card>
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat
label="CPU"
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
>
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
</Stat>
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
{d.stats && d.state === "running" && d.memoryMb ? (
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
) : (
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
)}
</Stat>
<Stat
label={d.state === "starting" ? "Loading" : "Load time"}
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
>
<span className="text-xs text-muted-foreground">until /health answered</span>
</Stat>
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
<span className="text-xs text-muted-foreground">
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
</span>
</Stat>
</CardContent>
</Card>
<LiveLog url={`/api/deployments/${d.id}/logs`} />
</div>
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<BenchmarkCard deploymentId={d.id} modelId={d.modelId} running={d.state === "running"} initial={benchmarks} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-xs">
{internal ? (
<div className="flex items-center justify-between gap-2">
<code className="font-mono break-all">{internal}</code>
<CopyButton value={internal} label="Copy URL" />
</div>
) : (
<span className="text-muted-foreground">Not started yet.</span>
)}
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
{published && (
<div className="flex items-center justify-between gap-2 border-t pt-2">
<code className="font-mono break-all">{published}</code>
<CopyButton value={published} label="Copy URL" />
</div>
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
{d.options.requireApiKey && (
<>
{" "}
Requires one of the{" "}
<Link href="/settings/api-keys" className="underline">
API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.
</>
)}
</span>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Container</dt>
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
<dt className="text-muted-foreground">Runs on</dt>
<dd>
{ACCELERATOR_LABEL[d.accelerator]}
{d.accelerator === "nvidia" && ` · ${d.options.gpus?.length ? `${d.options.gpus.length} selected GPU${d.options.gpus.length === 1 ? "" : "s"}` : "all GPUs"}`}
</dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={d.startedAt} />
</dd>
<dt className="text-muted-foreground">Stopped</dt>
<dd>
<LocalTime value={d.stoppedAt} />
</dd>
{d.command && (
<>
<dt className="text-muted-foreground">Arguments</dt>
<dd className="flex items-start gap-1">
<code className="font-mono break-all">{d.command.join(" ")}</code>
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
</dd>
</>
)}
</dl>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
/** Live container log (polls new lines every 1.5 s). */
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
const [answer, setAnswer] = useState("");
const [busy, setBusy] = useState(false);
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
const [error, setError] = useState<string | null>(null);
async function send() {
setBusy(true);
setAnswer("");
setError(null);
setStats(null);
const t0 = performance.now();
let first: number | null = null;
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
let chunks = 0;
try {
const res = await fetch(`/api/deployments/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
});
if (!res.ok || !res.body) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const j = JSON.parse(data);
if (j.usage) usage = j.usage;
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
if (delta) {
first ??= performance.now();
chunks++;
setAnswer((a) => a + delta);
}
}
}
const total = (performance.now() - t0) / 1000;
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle>Try it</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
disabled={!running}
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
/>
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
<SendIcon />
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
</Button>
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
{stats && (
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div>
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
<div className="text-muted-foreground">first token</div>
</div>
<div>
<div className="font-semibold tabular-nums">
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
</div>
<div className="text-muted-foreground">generation</div>
</div>
<div>
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,26 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentForm } from "../../deployment-form";
import { formData } from "../../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Edit deployment" };
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
const { id } = await params;
const [d, data] = await Promise.all([getDeployment(id), formData()]);
if (!d) notFound();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
{d.state !== "stopped" && d.state !== "failed" && (
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
)}
<DeploymentForm
{...data}
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
/>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { listBenchmarks } from "@/lib/benchmarks";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
const d = await getDeployment((await params).id);
return { title: d ? d.name : "Deployment" };
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const { id } = await params;
const [d, runs] = await Promise.all([getDeployment(id), listBenchmarks({ deploymentId: id })]);
if (!d) notFound();
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} benchmarks={JSON.parse(JSON.stringify(runs))} />;
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string): Promise<boolean> {
const res = await fetch(url, { method });
if (res.ok) return true;
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,210 @@
"use client";
import {
ExternalLinkIcon,
PlayIcon,
RocketIcon,
SquareIcon,
} from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { NativeSelect } from "@/components/ui/native-select";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { startDeployment, stopDeployment } from "./actions";
type Row = Omit<
DeploymentRow,
"startedAt" | "readyAt" | "stoppedAt" | "createdAt"
> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
const isActive = (r: Row) =>
r.desiredState === "running" ||
r.state === "starting" ||
r.state === "running" ||
r.state === "stopping";
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
// "" = everything, "-" = created in the UI, else a token name.
const [by, setBy] = useState("");
const tokens = [
...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
].sort();
const shown = rows.filter(
(r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
);
const hostname = useHostname();
const busy = rows.some(
(r) =>
r.state === "starting" ||
r.state === "stopping" ||
(r.desiredState === "running") !== (r.state === "running"),
);
async function reload() {
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(
() => null,
);
if (res?.ok) setRows(await res.json());
}
useEffect(() => {
const t = setInterval(reload, busy ? 2_000 : 5_000);
return () => clearInterval(t);
}, [busy]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<RocketIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
No deployments yet. Pick a runtime and a downloaded model to start
one.
</p>
<Link href="/deployments/new" className="text-sm underline">
New deployment
</Link>
</Card>
);
}
return (
<div className="flex flex-col gap-3">
{tokens.length > 0 && (
<label className="flex items-center gap-2 self-end text-xs text-muted-foreground">
Requested by
<NativeSelect
value={by}
onChange={(e) => setBy(e.target.value)}
className="h-7 text-xs"
aria-label="Requested by"
>
<option value="">Anyone</option>
<option value="-">Created in Kaname</option>
{tokens.map((t) => (
<option key={t} value={t}>
{t} (API)
</option>
))}
</NativeSelect>
</label>
)}
<div className="grid gap-3 md:grid-cols-2">
{shown.map((r) => {
const file = r.options.modelFile
? (quantGroup(r.options.modelFile) ?? r.options.modelFile)
: null;
const loadSecs =
r.readyAt && r.startedAt
? (new Date(r.readyAt).getTime() -
new Date(r.startedAt).getTime()) /
1000
: null;
return (
<Card key={r.id} className="gap-3 px-4 py-3">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-0.5">
<Link
href={`/deployments/${r.id}`}
className="truncate font-medium hover:underline"
>
{r.name}
</Link>
<span className="truncate text-xs text-muted-foreground">
{r.repoId}
{file && ` · ${file}`}
{r.options.mmproj && " · vision"}
{r.options.draftFile && " · MTP/draft"}
</span>
<span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
{r.runtimeName}
<RequestedByBadge
name={r.requestedBy}
className="h-4 text-[10px]"
/>
{r.protected && (
<span className="text-emerald-700 dark:text-emerald-300">
protected
</span>
)}
{r.startRequestedAt && (
<span className="text-amber-700 dark:text-amber-300">
start awaits approval
</span>
)}
</span>
</div>
<DeploymentStateBadge
state={r.state}
desiredState={r.desiredState}
/>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="tabular-nums">
{r.state === "running" && r.stats
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
: r.state === "failed"
? (r.error?.split("\n")[0] ?? "failed")
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
{r.state === "running" &&
loadSecs != null &&
` · loaded in ${loadSecs.toFixed(1)} s`}
</span>
<span className="flex items-center gap-1.5">
{r.state === "running" && webUiUrl(r, hostname) && (
<a
href={webUiUrl(r, hostname)!}
target="_blank"
rel="noreferrer"
className={buttonVariants({
size: "xs",
variant: "outline",
})}
>
<ExternalLinkIcon />
Web UI
</a>
)}
{isActive(r) ? (
<Button
size="xs"
variant="outline"
onClick={async () =>
(await stopDeployment(r.id)) && reload()
}
>
<SquareIcon />
Stop
</Button>
) : (
<Button
size="xs"
onClick={async () =>
(await startDeployment(r.id)) && reload()
}
>
<PlayIcon />
Start
</Button>
)}
</span>
</div>
</Card>
);
})}
</div>
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { applyOverrides } from "@/lib/hardware";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import { getHardwareOverrides } from "@/lib/settings";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
export async function formData(): Promise<{
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
apiKeyCount: number;
}> {
const [runtimes, models, docker, keys, overrides] = await Promise.all([
listRuntimes(),
listDeployableModels(),
getDockerInfo(),
listApiKeys(),
getHardwareOverrides(),
]);
return {
runtimes: runtimes.map((r) => ({
id: r.id,
name: r.name,
engine: r.engine,
image: r.image,
imageState: r.imageState,
env: r.env,
extraArgs: r.extraArgs,
accelerator: r.accelerator,
})),
models,
host: docker
? {
cpus: docker.cpus,
memoryBytes: docker.memoryBytes,
cpuFeatures: docker.cpuFeatures,
nvidia: !!docker.nvidia,
gpus: docker.gpus ?? [],
hardwareGpus: applyOverrides(docker.hardware, overrides)?.gpus ?? [],
}
: null,
apiKeyCount: keys.length,
};
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { deployPreset } from "@/lib/deployments";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
const { model } = await searchParams;
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} initial={preset ?? undefined} />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { listDeployments } from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { DeploymentList } from "./deployment-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Deployments" };
export default async function DeploymentsPage() {
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Deployments</h1>
<Link href="/deployments/new" className={buttonVariants()}>
New deployment
</Link>
</div>
{!docker?.connected && (
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
<Link href="/settings/runtimes" className="underline">
Settings → Runtimes
</Link>
.
</p>
)}
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
+55
View File
@@ -0,0 +1,55 @@
"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,
marker,
}: {
label: string;
values: [string, number][];
selected: string[];
onChange: (next: string[]) => void;
format?: (value: string) => string;
/** Optional element before each value, e.g. a tag's color dot. */
marker?: (value: string) => React.ReactNode;
}) {
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))}
>
{marker?.(value)}
<span className="flex-1">{format(value)}</span>
<span className="ml-4 text-xs text-muted-foreground tabular-nums">{count}</span>
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
+16 -2
View File
@@ -1,15 +1,19 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { ApprovalBar } from "@/components/approval-bar";
import { cancelJob } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress } from "@/components/job-progress";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useLive } from "@/hooks/use-live";
import { formatDuration } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { jobLabel } from "@/lib/job-labels";
import type { JobSnapshot } from "@/lib/jobs";
const OPEN = ["queued", "downloading", "verifying"];
@@ -20,6 +24,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
const files = snapshot?.files ?? [];
const open = OPEN.includes(job.state);
const [busy, setBusy] = useState(false);
const router = useRouter();
const logRef = useRef<HTMLDivElement>(null);
const [follow, setFollow] = useState(true);
@@ -40,11 +45,12 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold">
{job.kind === "download" ? "Download" : job.kind} ·{" "}
<Link href={`/models/${job.modelId}`} className="hover:underline">
{jobLabel(job)} ·{" "}
<Link href={`/${job.repoId}`} className="hover:underline">
{job.repoId}
</Link>
</h1>
<RequestedByBadge name={job.requestedBy} />
{open && (
<Button
className="ml-auto"
@@ -62,12 +68,20 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
)}
</div>
{job.state === "pending_approval" && <ApprovalBar job={job} onRemoved={() => router.push("/")} />}
<Card>
<CardContent className="flex flex-col gap-3">
<JobProgress job={job} />
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 text-sm">
<dt className="text-muted-foreground">Created</dt>
<dd><LocalTime value={job.createdAt} /></dd>
{job.requestedBy && (
<>
<dt className="text-muted-foreground">Requested by</dt>
<dd>{job.requestedBy} (API token)</dd>
</>
)}
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={job.startedAt} />
+24 -23
View File
@@ -1,48 +1,49 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
import { Button } from "@/components/ui/button";
import { AppNav } from "@/components/app-nav";
import { LabelSettingsProvider } from "@/components/labels";
import { UserMenu } from "@/components/user-menu";
import { WorkerIndicator } from "@/components/worker-indicator";
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export default async function AppLayout({ children }: LayoutProps<"/">) {
const session = await auth();
if (!session?.user) redirect("/login");
const worker = await getWorkerStatus();
const [worker, fileRoles, recommendedRoles] = await Promise.all([
getWorkerStatus(),
getFileRoleStyles(),
getRecommendedRoles(),
]);
return (
<div className="flex min-h-screen flex-col">
<div className="flex min-h-screen flex-col overflow-x-clip">
<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
<span className="text-xs font-normal text-muted-foreground">{process.env.APP_VERSION ?? "dev"}</span>
<div className="mx-auto flex h-14 max-w-7xl items-center gap-3 px-4 sm:gap-6">
<Link href="/" className="flex items-center gap-2 font-semibold">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/icon.svg" alt="" className="size-6" />
Kaname
<span className="hidden text-xs font-normal text-muted-foreground sm:inline">{process.env.APP_VERSION ?? "dev"}</span>
</Link>
<nav className="flex items-center gap-4 text-sm text-muted-foreground">
<Link href="/" className="hover:text-foreground">
Library
</Link>
</nav>
<AppNav />
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
<span className="hidden text-sm text-muted-foreground sm:inline">
{session.user.name ?? session.user.email}
</span>
<form
action={async () => {
<UserMenu
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
signOutAction={async () => {
"use server";
await signOut({ redirectTo: "/login" });
}}
>
<Button type="submit" variant="ghost" size="sm">
Sign out
</Button>
</form>
/>
</div>
</div>
</header>
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-6">{children}</main>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
</main>
</div>
);
}
-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>
);
}
+288
View File
@@ -0,0 +1,288 @@
"use client";
import { RocketIcon, 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 { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button, buttonVariants } 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 { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
FACETS,
facetCounts,
type Filters,
matchesFilters,
matchesQuery,
PENDING_APPROVAL,
type SearchableModel,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
const FACET_LABEL: Record<Facet, string> = {
author: "Author",
family: "Family",
quant: "Quant",
tag: "Tag",
status: "Status",
requester: "Requested by",
};
const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (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,
hubStatus:
r.hubState && r.hubState !== "available"
? HUB_STATE_LABEL[r.hubState].label
: r.updateAvailable
? "update available"
: null,
requestedBy: r.requestedBy,
pendingApproval: r.pendingApproval,
};
}
/** 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 tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
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}
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : 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 === "tag" && <TagDot name={v} color={tagColors.get(v)} />}
{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>
<TableHead className="w-24">
<span className="sr-only">Deploy</span>
</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={`/${r.repoId}`} 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">
<RequestedByBadge name={r.requestedBy} className="h-4 text-[10px]" />
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
<Link
key={d.id}
href={`/deployments/${d.id}`}
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
>
<RocketIcon className="size-3" />
<span className="max-w-40 truncate">{d.name}</span>
<span
className={cn(
"size-1.5 rounded-full",
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
)}
/>
</Link>
))}
{r.tags.map((t) => (
<button
key={t.id}
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<TagBadge name={t.name} color={t.color} />
</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" && job.state !== "pending_approval" && <JobProgress job={job} compact />}
</Link>
) : (
<span className="flex flex-wrap gap-1">
<ModelStatusBadge status={r.status} />
<HubStateBadge state={r.hubState} />
{r.updateAvailable && (r.hubState === "available" || !r.hubState) && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium whitespace-nowrap text-sky-700 dark:text-sky-300">
update available
</span>
)}
</span>
)}
</TableCell>
<TableCell>
{r.deployable && (
<Link
href={`/deployments/new?model=${r.id}`}
className={buttonVariants({ variant: "outline", size: "xs" })}
title="Serve this model with a runtime"
aria-label={`Deploy ${r.repoId}`}
>
<RocketIcon />
Deploy
</Link>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
)}
</div>
);
}
-136
View File
@@ -1,136 +0,0 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { cancelJob, startDownload } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
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 } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import type { JobSnapshot } from "@/lib/jobs";
const OPEN = ["queued", "downloading", "verifying"];
export function ModelLive({ modelId, status }: { modelId: string; status: ModelStatus }) {
const { snapshot } = useLive({ model: modelId });
const [busy, setBusy] = useState(false);
const jobs = snapshot?.jobs ?? [];
const latest = jobs[0] as JobSnapshot | undefined;
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const workerOffline = snapshot && !snapshot.worker.online;
async function run(fn: () => Promise<void>) {
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
}
return (
<>
<Card>
<CardHeader>
<CardTitle className="flex flex-wrap items-center gap-2">
Download
{latest && <JobStateBadge job={latest} />}
</CardTitle>
<CardDescription>
{open
? open.state === "queued"
? workerOffline
? "Queued, but the worker is offline."
: "Queued, waiting for a free download slot."
: "Running in the background; you can close this page."
: status === "ready"
? "All selected files are present."
: "Downloads the selected files at the pinned SHA."}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{latest && !(latest.state === "completed" && status === "ready") && <JobProgress job={latest} compact />}
{latest?.errorMessage && latest.state === "failed" && (
<pre className="rounded-md bg-destructive/10 px-3 py-2 text-xs whitespace-pre-wrap text-destructive">
{latest.errorMessage}
</pre>
)}
<div className="flex flex-wrap gap-2">
{open ? (
<Button
variant="destructive"
size="sm"
disabled={busy || open.cancelRequested}
onClick={() => run(() => cancelJob(open.id))}
>
{open.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
status !== "ready" &&
snapshot && (
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
{latest ? "Download again" : "Download"}
</Button>
)
)}
{latest && (
<Link
href={`/jobs/${latest.id}`}
className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted"
>
View log
</Link>
)}
</div>
</CardContent>
{open && snapshot && snapshot.files.length > 0 && <JobFilesTable files={snapshot.files} />}
</Card>
{jobs.length > 0 && (
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>Jobs</CardTitle>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>Started</TableHead>
<TableHead>Kind</TableHead>
<TableHead>State</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden sm:table-cell">Finished</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<Link href={`/jobs/${j.id}`} className="hover:underline">
<LocalTime value={j.startedAt ?? j.createdAt} />
</Link>
</TableCell>
<TableCell className="text-sm">
{j.kind}
{j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""}
</TableCell>
<TableCell>
<JobStateBadge job={j} />
</TableCell>
<TableCell className="text-right text-sm tabular-nums">{formatBytes(j.totalBytes)}</TableCell>
<TableCell className="hidden text-sm text-muted-foreground sm:table-cell">
<LocalTime value={j.finishedAt} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
)}
</>
);
}
+9 -89
View File
@@ -1,94 +1,14 @@
import { notFound } from "next/navigation";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { getModel } from "@/lib/library";
import { ModelLive } from "./model-live";
import { RemoveModelButton } from "./remove-model-button";
import { eq } from "drizzle-orm";
import { notFound, permanentRedirect } from "next/navigation";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
export const dynamic = "force-dynamic";
export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
/** Old URL scheme (/models/<id>): redirect to /<org>/<name>. */
export default async function LegacyModelPage({ params }: PageProps<"/models/[id]">) {
const { id } = await params;
const data = await getModel(id);
if (!data) notFound();
const { model, files } = data;
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold break-all">{model.repoId}</h1>
<ModelStatusBadge status={model.status} />
<div className="ml-auto">{model.status === "pending" && <RemoveModelButton id={model.id} />}</div>
</div>
<Card>
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm">
<dt className="text-muted-foreground">Hub</dt>
<dd>
<a
href={`https://huggingface.co/${model.repoId}/tree/${model.pinnedSha}`}
target="_blank"
rel="noreferrer"
className="underline"
>
huggingface.co/{model.repoId}
</a>
</dd>
<dt className="text-muted-foreground">Tracked revision</dt>
<dd className="font-mono">{model.trackedRevision}</dd>
<dt className="text-muted-foreground">Pinned SHA</dt>
<dd className="font-mono break-all">{model.pinnedSha}</dd>
<dt className="text-muted-foreground">Local path</dt>
<dd className="font-mono break-all">$MODELS_DIR/{model.localPath}</dd>
<dt className="text-muted-foreground">Include</dt>
<dd className="font-mono text-xs break-all">{model.includePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Exclude</dt>
<dd className="font-mono text-xs break-all">{model.excludePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Added</dt>
<dd><LocalTime value={model.createdAt} /></dd>
</dl>
</CardContent>
</Card>
<ModelLive modelId={model.id} status={model.status} />
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>
Selected files · {selected.length} · {formatBytes(totalBytes)}
</CardTitle>
<CardDescription>
{files.length - selected.length} other files in the repo are not selected.
</CardDescription>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>File</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>State</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{selected.map((f) => (
<TableRow key={f.id}>
<TableCell className="font-mono text-xs break-all whitespace-normal">{f.path}</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="text-sm text-muted-foreground">{f.state}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</div>
);
const model = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.id, id) });
if (!model) notFound();
permanentRedirect(`/${model.repoId}`);
}
@@ -1,57 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
/** Removes a not-yet-downloaded model from the library (DB only, no files exist yet). */
export function RemoveModelButton({ id }: { id: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function remove() {
setBusy(true);
const res = await fetch(`/api/models/${id}`, { method: "DELETE" });
if (res.ok) {
toast.success("Removed from library");
router.push("/");
router.refresh();
} else {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Remove failed (${res.status})`);
setBusy(false);
}
}
return (
<AlertDialog>
<AlertDialogTrigger render={<Button variant="destructive" size="sm" />}>Remove</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove from library?</AlertDialogTitle>
<AlertDialogDescription>
Nothing has been downloaded yet, so this only removes the entry.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove} disabled={busy}>
Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
+10 -5
View File
@@ -1,18 +1,23 @@
import { listLibrary } from "@/lib/library";
import { listLocalFolders } from "@/lib/local-folders";
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";
export default async function LibraryPage() {
const [rows, worker] = await Promise.all([listLibrary(), getWorkerStatus()]);
const [rows, worker, folders] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders()]);
return (
<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} />}
{/* Opens by default while the library is empty and there's nothing on disk to import. */}
<AddModelPanel
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
defaultOpen={rows.length === 0 && folders.length === 0}
folders={folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes }))}
/>
{rows.length > 0 && <LibraryView rows={rows} />}
</div>
);
}
@@ -0,0 +1,172 @@
"use client";
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { ApiKeyRow } from "@/lib/api-keys";
/** Keys that deployments with "Require an API key" accept. */
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>Runtime API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewKeyRow onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">API key &ldquo;{created.name}&rdquo; added. You can show it again from the list.</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.key}</code>
<CopyButton value={created.key} label="Copy API key" />
</div>
</div>
)}
{keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{keys.map((k) => (
<KeyRow key={k.id} apiKey={k} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, key: key.trim() || undefined }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
return;
}
onCreated({ name: json.name, key: json.key });
setName("");
setKey("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
<Input
value={key}
maxLength={256}
disabled={busy}
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
placeholder="Key (empty: generate one)"
aria-label="Key value"
spellCheck={false}
autoComplete="off"
className="font-mono text-xs md:text-xs"
/>
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
<PlusIcon />
Add
</Button>
</form>
);
}
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
const router = useRouter();
const [shown, setShown] = useState<string | null>(null);
async function toggle() {
if (shown) return setShown(null);
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
else setShown(json.key);
}
async function remove() {
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`API key "${apiKey.name}" deleted`);
router.refresh();
}
return (
<div className="flex items-center gap-3 px-4 py-2.5">
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
{shown ? (
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
{shown}
</code>
<CopyButton value={shown} label="Copy API key" />
</span>
) : (
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
)}
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
{shown ? <EyeOffIcon /> : <EyeIcon />}
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
<LocalTime value={apiKey.createdAt} />
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API key &ldquo;{apiKey.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more