Compare commits

..
9 Commits
Author SHA1 Message Date
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
156 changed files with 24214 additions and 251 deletions

No files matched your search

+5
View File
@@ -19,6 +19,11 @@ OIDC_ALLOWED_GROUPS=
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
HF_TOKEN=
# 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
# ---------------------------------------------------------------------------
+205 -1
View File
@@ -4,7 +4,211 @@ 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.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
+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 ./
+4
View File
@@ -86,6 +86,10 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
(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`, within guardrails you set (approval, max
size, free space, jobs at once, allowed authors). See [docs/api.md](docs/api.md) (also how to let
`/api/v1/` past a forward-auth proxy) and the agent skill [docs/agent/SKILL.md](docs/agent/SKILL.md).
## How it works
+128
View File
@@ -0,0 +1,128 @@
---
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: tell the user when they need one of those.
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 "$KANAME_URL/api/v1/jobs/<jobId>"
```
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. Every check
costs a full round of your context, so check 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`:** check at most once, around the reported
`etaSeconds`; if there is no ETA, once after about 10 minutes. 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" "$@"
+248
View File
@@ -0,0 +1,248 @@
# Kaname API (`/api/v1`)
A small JSON API for programs and AI agents: look up Hugging Face repos, list the local library,
request downloads and follow them. Everything an agent can do here is bounded by
[guardrails](#guardrails); it can't delete models or files, change settings, or manage runtimes or
tokens.
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)
- [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 |
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`, `invalid_json`, `empty_selection` (quant or globs match nothing), `invalid_repo_id` |
| 401 / 403 | `unauthorized`, `forbidden` (scope), `author_not_allowed`, `gated_no_token`, `gated_no_access` |
| 404 | `not_found`, `repo_not_found`, `revision_not_found` |
| 409 | `already_exists` (repo is in the library at another commit), `busy` (the model has an open job) |
| 422 | `too_large` |
| 429 | `too_many_jobs`, `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: check GET /api/v1/jobs/01M… every few minutes." }
```
- **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}[?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).
### `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.
## Guardrails
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.
## 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.
+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;
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
+42
View File
@@ -92,6 +92,48 @@
"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
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.8.0",
"version": "0.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.8.0",
"version": "0.12.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.8.0",
"version": "0.12.0",
"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": {
+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
+12 -5
View File
@@ -2,7 +2,9 @@
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";
@@ -33,6 +35,8 @@ export function DownloadCard({
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");
@@ -58,12 +62,13 @@ export function DownloadCard({
: latest?.state === "failed" && latest.kind === "download"
? "Retry"
: "Download missing";
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
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 (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
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.";
@@ -83,7 +88,9 @@ export function DownloadCard({
</div>
<p className="text-xs text-muted-foreground">{hint}</p>
{showProgress && <JobProgress job={latest} compact />}
{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">
+2
View File
@@ -23,6 +23,7 @@ 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";
@@ -145,6 +146,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<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
+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,387 @@
"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 { RunMetaCard } from "@/components/run-meta";
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-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 === "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,
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}
/>
</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">
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.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} /> : <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 === "run" && (
<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>
);
}
+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 });
+151
View File
@@ -0,0 +1,151 @@
"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 { 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[]>([]);
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
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 && (
<div className="flex 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>
<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>
</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>
{rows.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="text-xs text-muted-foreground">
{r.label && `${s.deploymentName} · `}
{s.repoId} · <LocalTime value={r.createdAt} />
</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">{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>
);
}
+215
View File
@@ -0,0 +1,215 @@
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 { 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) => 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 })),
},
];
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) => m.get(s));
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,278 @@
"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 { metaRows } from "@/lib/benchmark-meta";
import { describeSettings, headline } from "@/lib/benchmark-view";
import type { benchmarkSweeps, BenchmarkSummary, 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 };
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
pending: "Waiting",
deploying: "Deploying",
benchmarking: "Benchmarking",
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;
};
function rowsOf(data: SweepData): Row[] {
return data.sweep.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId) ?? 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,
};
});
}
/**
* 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 === "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),
};
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">
<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.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>
<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))}
{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,248 @@
"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 [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,
}),
});
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>
<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,252 @@
"use client";
import { 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 { 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" | "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 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: "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 === "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 === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</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) : 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>
);
}
@@ -3,9 +3,10 @@
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
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,
@@ -23,11 +24,14 @@ 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;
@@ -35,7 +39,6 @@ type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "c
stoppedAt: string | null;
createdAt: string;
};
type LogLine = { id: number; ts: number; stream: string; line: string };
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
@@ -47,7 +50,7 @@ function Stat({ label, value, children }: { label: string; value: React.ReactNod
);
}
export function DeploymentDetail({ initial }: { initial: Deployment }) {
export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment; benchmarks: ListRow[] }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
@@ -186,11 +189,12 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
</CardContent>
</Card>
<Logs id={d.id} />
<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>
@@ -234,6 +238,11 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
<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} />
@@ -261,63 +270,6 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
}
/** Live container log (polls new lines every 1.5 s). */
function Logs({ id }: { id: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`/api/deployments/${id}/logs?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [id]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className="min-w-0">
<CardHeader>
<CardTitle>Log</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
/** 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.");
+4 -2
View File
@@ -1,5 +1,6 @@
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";
@@ -11,7 +12,8 @@ export async function generateMetadata({ params }: PageProps<"/deployments/[id]"
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const d = await getDeployment((await params).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))} />;
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} benchmarks={JSON.parse(JSON.stringify(runs))} />;
}
File diff suppressed because it is too large. Load diff
+35 -4
View File
@@ -1,16 +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] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
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 })),
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 } : null,
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,
};
}
+13
View File
@@ -1,10 +1,13 @@
"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";
@@ -21,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);
@@ -46,6 +50,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
{job.repoId}
</Link>
</h1>
<RequestedByBadge name={job.requestedBy} />
{open && (
<Button
className="ml-auto"
@@ -63,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} />
+9 -3
View File
@@ -8,6 +8,7 @@ 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";
@@ -28,11 +29,12 @@ import {
type Filters,
matchesFilters,
matchesQuery,
PENDING_APPROVAL,
type SearchableModel,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
const OPEN = ["queued", "downloading", "verifying"];
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
const FACET_LABEL: Record<Facet, string> = {
author: "Author",
@@ -40,9 +42,10 @@ const FACET_LABEL: Record<Facet, string> = {
quant: "Quant",
tag: "Tag",
status: "Status",
requester: "Requested by",
};
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (MODEL_STATUS[v as ModelStatus]?.label ?? v));
function toSearchable(r: LibraryRow): SearchableModel {
return {
@@ -63,6 +66,8 @@ function toSearchable(r: LibraryRow): SearchableModel {
: r.updateAvailable
? "update available"
: null,
requestedBy: r.requestedBy,
pendingApproval: r.pendingApproval,
};
}
@@ -197,6 +202,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{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) => (
@@ -243,7 +249,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
{job.state !== "queued" && job.state !== "pending_approval" && <JobProgress job={job} compact />}
</Link>
) : (
<span className="flex flex-wrap gap-1">
@@ -28,7 +28,7 @@ export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<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.
+1 -1
View File
@@ -3,7 +3,7 @@ import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export const metadata: Metadata = { title: "Runtime API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
@@ -0,0 +1,111 @@
"use client";
import { ShieldCheckIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import { type ApprovalMode, type Guardrails, parseAuthorList } from "@/lib/agent-guardrails";
const GB = 1_000_000_000;
const toGb = (b: number) => String(Math.round((b / GB) * 1000) / 1000);
/** Limits for downloads requested through the API. Saved together with one button. */
export function GuardrailSettings({ initial }: { initial: Guardrails }) {
const router = useRouter();
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
const [maxGb, setMaxGb] = useState(toGb(initial.maxRequestBytes));
const [minFreeGb, setMinFreeGb] = useState(toGb(initial.minFreeBytes));
const [maxJobs, setMaxJobs] = useState(String(initial.maxOpenJobs));
const [authors, setAuthors] = useState(initial.allowedAuthors.join(", "));
const [busy, setBusy] = useState(false);
let authorError: string | null = null;
let authorList: string[] = [];
try {
authorList = parseAuthorList(authors);
} catch (err) {
authorError = err instanceof Error ? err.message : String(err);
}
const num = (s: string) => Number(s.replace(",", "."));
async function save(e: React.FormEvent) {
e.preventDefault();
if (authorError) return;
setBusy(true);
try {
const res = await fetch("/api/settings/agent", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
approvalMode: mode,
maxRequestBytes: Math.round(num(maxGb) * GB),
minFreeBytes: Math.round(num(minFreeGb) * GB),
maxOpenJobs: Math.round(num(maxJobs)),
allowedAuthors: authorList,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
toast.success("Guardrails saved");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<ShieldCheckIcon className="size-4 text-muted-foreground" />
Guardrails for API downloads
</CardTitle>
<CardDescription>Apply to every download requested with a token, across all tokens. Downloads you start in the UI are not affected.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={save} className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-mode">Approval</Label>
<NativeSelect id="g-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
<option value="approve">Ask me: requests wait as &ldquo;pending approval&rdquo;</option>
<option value="auto">Automatic: downloads start right away</option>
</NativeSelect>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-max">Max size per request (GB)</Label>
<Input id="g-max" value={maxGb} onChange={(e) => setMaxGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-free">Keep free on the models folder (GB)</Label>
<Input id="g-free" value={minFreeGb} onChange={(e) => setMinFreeGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-jobs">Agent jobs at once</Label>
<Input id="g-jobs" value={maxJobs} onChange={(e) => setMaxJobs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-authors">Allowed authors</Label>
<Input id="g-authors" value={authors} onChange={(e) => setAuthors(e.target.value)} placeholder="Empty: any author. e.g. unsloth, ggml-org, Qwen" aria-invalid={!!authorError} />
<p className="text-xs text-muted-foreground">
{authorError ?? "Hugging Face users or organizations (the part before the slash), comma-separated."}
</p>
</div>
<p className="text-xs text-muted-foreground">
&ldquo;Agent jobs at once&rdquo; counts requests that are pending approval, queued or downloading. The free-space check also subtracts what other open
downloads still need.
</p>
<Button type="submit" className="self-start" disabled={busy || !!authorError}>
Save guardrails
</Button>
</form>
</CardContent>
</Card>
);
}
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { listTokens } from "@/lib/api-tokens";
import { getGuardrails } from "@/lib/settings";
import { GuardrailSettings } from "./guardrail-settings";
import { TokenSettings } from "./token-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API tokens · Settings" };
export default async function ApiTokenSettingsPage() {
const [tokens, guardrails] = await Promise.all([listTokens(), getGuardrails()]);
return (
<div className="flex flex-col gap-4">
<TokenSettings tokens={tokens} />
<GuardrailSettings initial={guardrails} />
</div>
);
}
@@ -0,0 +1,178 @@
"use client";
import { BotIcon, 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 { Badge } from "@/components/ui/badge";
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 { SCOPE_LABEL } from "@/lib/token-scopes";
import type { ApiTokenRow } from "@/lib/api-tokens";
import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
/** Bearer tokens for /api/v1 (e.g. an AI agent). The token is shown once, then only its prefix. */
export function TokenSettings({ tokens }: { tokens: ApiTokenRow[] }) {
const [created, setCreated] = useState<{ name: string; token: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API tokens</CardTitle>
<CardDescription>
For programs and agents calling Kaname&apos;s API at <code className="font-mono text-xs">/api/v1</code> with{" "}
<code className="font-mono text-xs">Authorization: Bearer &lt;token&gt;</code>. No token can delete models or files, change settings, or manage runtimes and
tokens.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewTokenForm 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">Token &ldquo;{created.name}&rdquo; created. Copy it now: it is not shown again.</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.token}</code>
<CopyButton value={created.token} label="Copy token" />
</div>
</div>
)}
{tokens.length === 0 ? (
<p className="text-sm text-muted-foreground">No tokens yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tokens.map((t) => (
<TokenRow key={t.id} token={t} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [scopes, setScopes] = useState<TokenScope[]>(["models:read"]);
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
try {
const res = await fetch("/api/api-tokens", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, scopes }) });
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not create the token (${res.status})`);
onCreated({ name: name.trim().toLowerCase(), token: json.token });
setName("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3">
<div className="flex items-center gap-2">
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))}
placeholder="Name, e.g. hermes"
aria-label="Token name"
className="max-w-56"
/>
<Button type="submit" size="sm" disabled={busy || !name || scopes.length === 0}>
<PlusIcon />
Create token
</Button>
</div>
<div className="flex flex-col gap-1.5">
{TOKEN_SCOPES.map((s) => (
<label key={s} className="flex cursor-pointer items-start gap-2 text-sm">
<Checkbox checked={scopes.includes(s)} onCheckedChange={(v) => setScopes((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
<span className="flex flex-col">
<code className="font-mono text-xs">{s}</code>
<span className="text-xs text-muted-foreground">{SCOPE_LABEL[s]}</span>
</span>
</label>
))}
</div>
<p className="text-xs text-muted-foreground">The name is shown as &ldquo;requested by&rdquo; on everything the token asks for.</p>
</form>
);
}
function TokenRow({ token }: { token: ApiTokenRow }) {
const router = useRouter();
const revoked = !!token.revokedAt;
async function act(method: "POST" | "DELETE") {
const res = await fetch(`/api/api-tokens/${token.id}`, { method });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Failed (${res.status})`);
else toast.success(method === "POST" ? `Token "${token.name}" revoked` : `Token "${token.name}" deleted`);
router.refresh();
}
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5">
<BotIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="text-sm font-medium">{token.name}</span>
<code className="font-mono text-xs text-muted-foreground">{token.prefix}…</code>
<span className="flex flex-wrap gap-1">
{token.scopes.map((s) => (
<Badge key={s} variant="outline" className="font-mono text-[10px]">
{s}
</Badge>
))}
</span>
{revoked && <Badge variant="destructive">revoked</Badge>}
<span className="ml-auto text-xs text-muted-foreground">
{token.lastUsedAt ? (
<>
used <LocalTime value={token.lastUsedAt} />
</>
) : (
"never used"
)}
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>{revoked ? <Trash2Icon /> : "Revoke"}</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{revoked ? "Delete" : "Revoke"} token &ldquo;{token.name}&rdquo;?
</AlertDialogTitle>
<AlertDialogDescription>
{revoked
? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label."
: "It stops working immediately. Downloads it already requested are not affected."}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={() => act(revoked ? "DELETE" : "POST")}>
{revoked ? "Delete" : "Revoke"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+8 -2
View File
@@ -1,10 +1,16 @@
import type { Metadata } from "next";
import { getRecommendedRoles } from "@/lib/settings";
import { getDownloadSpeedLimit, getRecommendedRoles } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings";
import { SpeedLimit } from "./speed-limit";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Downloads · Settings" };
export default async function DownloadSettingsPage() {
return <RecommendedSettings initial={await getRecommendedRoles()} />;
return (
<div className="flex flex-col gap-4">
<SpeedLimit initial={await getDownloadSpeedLimit()} />
<RecommendedSettings initial={await getRecommendedRoles()} />
</div>
);
}
@@ -0,0 +1,86 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const MB = 1_000_000;
/** Download speed limit in MB/s; empty means no limit. Applies to running downloads within seconds. */
export function SpeedLimit({ initial }: { initial: number | null }) {
const [saved, setSaved] = useState(initial);
const [text, setText] = useState(initial ? String(initial / MB) : "");
const [busy, setBusy] = useState(false);
const value = text.trim() === "" ? null : Number(text.replace(",", "."));
const invalid = value != null && !(value >= 0.1);
const dirty = value !== (saved == null ? null : saved / MB);
async function save(next: number | null) {
setBusy(true);
try {
const res = await fetch("/api/settings/downloads", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ maxBytesPerSecond: next == null ? null : Math.round(next * MB) }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
setSaved(body.maxBytesPerSecond);
setText(body.maxBytesPerSecond ? String(body.maxBytesPerSecond / MB) : "");
toast.success(body.maxBytesPerSecond ? `Downloads limited to ${body.maxBytesPerSecond / MB} MB/s` : "Download speed is no longer limited");
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Speed limit</CardTitle>
<CardDescription>
Caps the total download speed from Hugging Face, e.g. to leave bandwidth for others. It also applies to downloads that are already running. Leave empty for
no limit.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<form
className="flex items-end gap-2"
onSubmit={(e) => {
e.preventDefault();
if (!invalid) void save(value);
}}
>
<div className="flex flex-col gap-1.5">
<Label htmlFor="speed-limit">Maximum speed (MB/s)</Label>
<Input
id="speed-limit"
value={text}
onChange={(e) => setText(e.target.value.replace(/[^\d.,]/g, ""))}
inputMode="decimal"
placeholder="No limit"
className="w-40"
aria-invalid={invalid}
/>
</div>
<Button type="submit" disabled={busy || invalid || !dirty}>
Save
</Button>
{saved != null && (
<Button type="button" variant="ghost" disabled={busy} onClick={() => void save(null)}>
Remove limit
</Button>
)}
</form>
<p className="text-xs text-muted-foreground">
{invalid
? "At least 0.1 MB/s."
: `1 MB/s ≈ 8 Mbit/s. hf has no speed option of its own, so Kaname pauses it whenever it gets ahead; short bursts above the limit are normal, the average holds.`}
</p>
</CardContent>
</Card>
);
}
@@ -0,0 +1,267 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { LocalTime } from "@/components/local-time";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { HardwareOverrides, HostHardware } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { formatLink, onOff } from "@/lib/hardware";
type GpuForm = { name: string; vramMb: string; linkCurrent: string; linkMax: string; rebar: "" | "on" | "off" };
const toForm = (o: NonNullable<HardwareOverrides["gpus"]>[string] | undefined): GpuForm => ({
name: o?.name ?? "",
vramMb: o?.vramMb != null ? String(o.vramMb) : "",
linkCurrent: o?.linkCurrent ?? "",
linkMax: o?.linkMax ?? "",
rebar: o?.rebar == null ? "" : o.rebar ? "on" : "off",
});
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
/** What Kaname detected on the Docker host, with manual values for what it can't see. */
export function HardwareSettings({
detected,
overrides,
summary,
dockerConnected,
}: {
detected: HostHardware | null;
overrides: HardwareOverrides;
summary: string[];
dockerConnected: boolean;
}) {
const router = useRouter();
const [gpus, setGpus] = useState<Record<string, GpuForm>>(() => Object.fromEntries((detected?.gpus ?? []).map((g) => [g.pciAddress, toForm(overrides.gpus?.[g.pciAddress])])));
const [p2p, setP2p] = useState(overrides.p2p ?? "");
const [storage, setStorage] = useState(overrides.storage ?? "");
const [hypervisor, setHypervisor] = useState(overrides.hypervisor ?? "");
const [passthrough, setPassthrough] = useState(overrides.gpuPassthrough == null ? "" : overrides.gpuPassthrough ? "yes" : "no");
const [gpuDriver, setGpuDriver] = useState(overrides.gpuDriver ?? "");
const [busy, setBusy] = useState(false);
const setGpu = (addr: string, patch: Partial<GpuForm>) => setGpus((g) => ({ ...g, [addr]: { ...g[addr], ...patch } }));
async function save() {
setBusy(true);
try {
const body: HardwareOverrides = {
gpus: Object.fromEntries(
Object.entries(gpus).map(([addr, g]) => [
addr,
{
name: g.name || undefined,
vramMb: g.vramMb ? Number(g.vramMb) : undefined,
linkCurrent: g.linkCurrent || undefined,
linkMax: g.linkMax || undefined,
rebar: g.rebar ? g.rebar === "on" : undefined,
},
]),
),
p2p: (p2p || undefined) as HardwareOverrides["p2p"],
storage: storage || undefined,
hypervisor: hypervisor || undefined,
gpuPassthrough: passthrough ? passthrough === "yes" : undefined,
gpuDriver: gpuDriver || undefined,
};
const res = await fetch("/api/settings/hardware", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const out = await res.json().catch(() => ({}));
if (!res.ok) return void toast.error(out.error?.message ?? `Could not save (${res.status})`);
toast.success("Saved; new benchmark runs use these values");
router.refresh();
} finally {
setBusy(false);
}
}
if (!detected) {
return (
<Card>
<CardHeader>
<CardTitle>Hardware</CardTitle>
<CardDescription>
{dockerConnected ? "The worker hasn't reported its hardware yet (it checks every few minutes)." : "Hardware is detected by the worker once Docker is connected (Settings → Runtimes)."}
</CardDescription>
</CardHeader>
</Card>
);
}
const v = detected.virtualization;
return (
<form
className="flex flex-col gap-4"
onSubmit={(e) => {
e.preventDefault();
void save();
}}
>
<Card>
<CardHeader>
<CardTitle>GPUs</CardTitle>
<CardDescription>
Recorded with every benchmark run. Detected from sysfs as the worker sees it; in a VM the PCIe link is the one the VM sees, which may not be the physical
slot. Fill in a field to replace the detected value (empty = detected).
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{detected.gpus.length === 0 && <p className="text-sm text-muted-foreground">No NVIDIA, Intel or AMD GPU found.</p>}
{detected.gpus.map((g) => {
const f = gpus[g.pciAddress];
return (
<div key={g.pciAddress} className="flex flex-col gap-3 rounded-lg border p-3">
<div className="text-sm">
<span className="font-medium">{g.name ?? "Unknown GPU"}</span>
<span className="text-muted-foreground">
{" "}
· {g.pciAddress} · {g.driver ?? "no driver"}
{g.driverVersion ? ` ${g.driverVersion}` : ""}
</span>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<Field id={`n-${g.pciAddress}`} label="Name" detected={g.name} value={f.name} onChange={(x) => setGpu(g.pciAddress, { name: x })} />
<Field
id={`v-${g.pciAddress}`}
label="VRAM (MiB)"
detected={g.vramMb != null ? String(g.vramMb) : null}
value={f.vramMb}
onChange={(x) => setGpu(g.pciAddress, { vramMb: x.replace(/\D/g, "") })}
/>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`r-${g.pciAddress}`}>ReBAR</Label>
<NativeSelect id={`r-${g.pciAddress}`} value={f.rebar} onChange={(e) => setGpu(g.pciAddress, { rebar: e.target.value as GpuForm["rebar"] })}>
<option value="">Detected: {onOff(g.rebar)}</option>
<option value="on">on</option>
<option value="off">off</option>
</NativeSelect>
<p className="text-xs text-muted-foreground">Largest BAR {g.barMb != null ? formatBytes(g.barMb * 2 ** 20) : "unknown"}</p>
</div>
<Field
id={`lc-${g.pciAddress}`}
label="PCIe link (current)"
detected={formatLink(g.linkCurrent)}
value={f.linkCurrent}
placeholderHint="e.g. Gen4 x8"
onChange={(x) => setGpu(g.pciAddress, { linkCurrent: x })}
/>
<Field
id={`lm-${g.pciAddress}`}
label="PCIe link (maximum)"
detected={formatLink(g.linkMax)}
value={f.linkMax}
placeholderHint="e.g. Gen5 x16"
onChange={(x) => setGpu(g.pciAddress, { linkMax: x })}
/>
</div>
</div>
);
})}
{detected.gpus.length > 1 && (
<div className="flex max-w-xs flex-col gap-1.5">
<Label htmlFor="hw-p2p">Peer-to-peer between GPUs</Label>
<NativeSelect id="hw-p2p" value={p2p} onChange={(e) => setP2p(e.target.value as typeof p2p)}>
<option value="">Detected: {detected.p2p ?? "unknown"}</option>
<option value="on">on</option>
<option value="partial">partial</option>
<option value="off">off</option>
</NativeSelect>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>System</CardTitle>
<CardDescription>Part of the system summary recorded with each run, passed to BetterBench and shown in the launch80 preview.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid gap-3 sm:grid-cols-2">
<Field
id="hw-storage"
label="Models disk"
detected={detected.storage ? [detected.storage.model, detected.storage.kind && STORAGE_KIND[detected.storage.kind]].filter(Boolean).join(", ") : null}
value={storage}
onChange={setStorage}
/>
<Field
id="hw-virt"
label="Virtualization"
detected={v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}` : "bare metal"}
value={hypervisor}
placeholderHint="e.g. Proxmox VE 9 (KVM)"
onChange={setHypervisor}
/>
<div className="flex flex-col gap-1.5">
<Label htmlFor="hw-pt">GPU passthrough</Label>
<NativeSelect id="hw-pt" value={passthrough} onChange={(e) => setPassthrough(e.target.value)}>
<option value="">Detected: {v.vm ? (detected.gpus.length ? "yes" : "no") : v.vm === false ? "no (bare metal)" : "unknown"}</option>
<option value="yes">yes</option>
<option value="no">no</option>
</NativeSelect>
</div>
<Field
id="hw-driver"
label="GPU driver"
detected={[...new Set(detected.gpus.map((g) => [g.driver, g.driverVersion].filter(Boolean).join(" ")))].join(", ") || null}
value={gpuDriver}
placeholderHint="e.g. xe, compute runtime 25.35"
onChange={setGpuDriver}
/>
</div>
<div>
<Button type="submit" disabled={busy}>
Save
</Button>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>System summary</CardTitle>
<CardDescription>
Exactly what runs record and publish (after saving). Never the hostname, IP addresses, users or paths. Checked <LocalTime value={detected.checkedAt} />.
</CardDescription>
</CardHeader>
<CardContent>
<ul className="flex flex-col gap-1 text-sm">
{summary.map((l) => (
<li key={l}>{l}</li>
))}
</ul>
</CardContent>
</Card>
</form>
);
}
function Field({
id,
label,
detected,
value,
onChange,
placeholderHint,
}: {
id: string;
label: string;
detected: string | null;
value: string;
onChange: (v: string) => void;
placeholderHint?: string;
}) {
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={id}>{label}</Label>
<Input id={id} value={value} onChange={(e) => onChange(e.target.value)} placeholder={detected ?? placeholderHint ?? "unknown"} maxLength={120} />
<p className="text-xs text-muted-foreground">Detected: {detected ?? "unknown"}</p>
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { kanameVersion } from "@/lib/benchmark-snapshot";
import { applyOverrides, systemSummary, systemSummaryLines } from "@/lib/hardware";
import { getDockerInfo } from "@/lib/runtimes";
import { getHardwareOverrides } from "@/lib/settings";
import { HardwareSettings } from "./hardware-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Hardware · Settings" };
export default async function HardwareSettingsPage() {
const [docker, overrides] = await Promise.all([getDockerInfo(), getHardwareOverrides()]);
const hardware = docker?.hardware ?? null;
const effective = applyOverrides(hardware, overrides);
return (
<HardwareSettings
detected={hardware}
overrides={overrides}
summary={systemSummaryLines(systemSummary(effective, docker?.os ?? null, kanameVersion()))}
dockerConnected={!!docker?.connected}
/>
);
}
+4 -2
View File
@@ -1,4 +1,4 @@
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { BotIcon, BoxesIcon, CpuIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
@@ -6,7 +6,9 @@ const SECTIONS = [
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
{ href: "/settings/hardware", label: "Hardware", icon: <CpuIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "Runtime API keys", icon: <KeyRoundIcon className="size-4" /> },
{ href: "/settings/api-tokens", label: "API tokens", icon: <BotIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
@@ -6,9 +6,10 @@ import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { NativeSelect } from "@/components/ui/native-select";
import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { ACCELERATOR_DEVICES, ACCELERATOR_LABEL, formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
@@ -33,8 +34,10 @@ export function RuntimeForm({
}) {
const [name, setName] = useState(initial.name);
const [engine, setEngine] = useState<RuntimeEngine>(initial.engine);
const [accelerator, setAccelerator] = useState<RuntimeAccelerator>(initial.accelerator ?? "cpu");
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [engineName, setEngineName] = useState(initial.engineName ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
@@ -50,8 +53,10 @@ export function RuntimeForm({
value = validateRuntime({
name,
engine,
accelerator,
image,
description,
engineName,
env: parseEnvLines(envText),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
@@ -114,11 +119,46 @@ export function RuntimeForm({
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-acc">Runs on</Label>
<NativeSelect
id="rt-acc"
value={accelerator}
onChange={(e) => {
const next = e.target.value as RuntimeAccelerator;
setAccelerator(next);
// Suggest the device nodes the accelerator needs.
if (!devicesText.trim()) setDevicesText(ACCELERATOR_DEVICES[next].join(", "));
}}
>
{RUNTIME_ACCELERATORS.map((a) => (
<option key={a} value={a}>
{ACCELERATOR_LABEL[a]}
</option>
))}
</NativeSelect>
<p className="text-xs text-muted-foreground">
{accelerator === "nvidia"
? "GPUs are requested from Docker (NVIDIA Container Toolkit on the host); each deployment picks which ones."
: accelerator === "dri"
? "Intel and AMD GPUs are passed in as /dev/dri (Vulkan, Intel SYCL, vLLM XPU). The image must be built for it."
: accelerator === "rocm"
? "AMD GPUs with ROCm: /dev/kfd and /dev/dri are passed in."
: "CPU and RAM only."}
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-desc">Description</Label>
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-engine-name">Engine name</Label>
<Input id="rt-engine-name" value={engineName} onChange={(e) => setEngineName(e.target.value)} maxLength={60} placeholder={engine} spellCheck={false} />
<p className="text-xs text-muted-foreground">For forks: recorded with every benchmark next to the version the server reports, e.g. vllm-radiance.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
@@ -150,7 +190,7 @@ export function RuntimeForm({
onChange={(e) => setDevicesText(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="/dev/dri (Intel/AMD GPUs, later)"
placeholder="/dev/dri, /dev/kfd"
/>
</div>
</div>
@@ -30,7 +30,7 @@ import {
import { Progress } from "@/components/ui/progress";
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
import { formatBytes, percent } from "@/lib/format";
import { RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { ACCELERATOR_LABEL, RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
import { RuntimeForm } from "./runtime-form";
@@ -63,8 +63,10 @@ async function send(url: string, method: string, body?: unknown): Promise<boolea
const toInput = (r: Runtime): RuntimeInput => ({
name: r.name,
engine: r.engine,
accelerator: r.accelerator,
image: r.image,
description: r.description,
engineName: r.engineName,
env: r.env,
extraArgs: r.extraArgs,
devices: r.devices,
@@ -218,6 +220,24 @@ function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; wor
</dd>
<dt className="text-muted-foreground">Memory</dt>
<dd>{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}</dd>
<dt className="text-muted-foreground">GPUs</dt>
<dd className="flex flex-col gap-0.5">
{docker.gpus && docker.gpus.length > 0 ? (
docker.gpus.map((g) => (
<span key={g.uuid}>
{g.index}: {g.name} <span className="text-muted-foreground">· {formatBytes(g.memoryMb * 2 ** 20)} · driver {g.driver}</span>
</span>
))
) : docker.nvidia ? (
<span className={cn(docker.gpuError && "text-amber-700 dark:text-amber-300")}>
{docker.gpuError ? `NVIDIA runtime found, but listing GPUs failed: ${docker.gpuError}` : "NVIDIA runtime found, no GPUs listed."}
</span>
) : (
<span className="text-muted-foreground">
No NVIDIA GPUs (no NVIDIA runtime in Docker). Intel/AMD GPUs aren&apos;t listed; pass /dev/dri to a runtime to use them.
</span>
)}
</dd>
<dt className="text-muted-foreground">Network</dt>
<dd className={cn("font-mono text-xs", !docker.network && "text-amber-700 dark:text-amber-300")}>
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
@@ -260,6 +280,12 @@ function ImageState({ r }: { r: Runtime }) {
· built <LocalTime value={r.imageCreated} />
</span>
)}
{r.imageDigest && (
<span className="font-mono text-muted-foreground" title={r.imageDigest}>
{" "}
· {r.imageDigest.slice(0, 19)}…
</span>
)}
</span>
);
}
@@ -290,6 +316,9 @@ function RuntimeRow({
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{r.name}</span>
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">{r.engine === "vllm" ? "vLLM" : "llama.cpp"}</span>
{r.accelerator !== "cpu" && (
<span className="rounded-md border border-emerald-500/30 px-1.5 text-xs text-emerald-700 dark:text-emerald-300">{ACCELERATOR_LABEL[r.accelerator]}</span>
)}
{r.numaTuning && <span className="rounded-md border border-amber-500/30 px-1.5 text-xs text-amber-700 dark:text-amber-300">NUMA tuning</span>}
</div>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { deleteToken, revokeToken, TokenError } from "@/lib/api-tokens";
/** Revoke a token: it stops working immediately. */
export const POST = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
try {
await revokeToken((await params).id);
return NextResponse.json({ ok: true });
} catch (err) {
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
throw err;
}
});
/** Delete a revoked token (frees its name). */
export const DELETE = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
try {
await deleteToken((await params).id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+23
View File
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createToken, listTokens, TokenError } from "@/lib/api-tokens";
export const dynamic = "force-dynamic";
/** API tokens for machine clients (Settings → API tokens). Never includes the tokens themselves. */
export const GET = withAuth(async () => NextResponse.json(await listTokens()));
const Body = z.object({ name: z.string().max(40), scopes: z.array(z.string()).min(1).max(10) });
/** Create a token. The response is the only time the token is shown. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
return NextResponse.json(await createToken(body.name, body.scopes), { status: 201, headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { BenchmarkError, cancelBenchmark } from "@/lib/benchmarks";
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/cancel">>(async (_req, { params }) => {
try {
await cancelBenchmark((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+11
View File
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listBenchmarkLogs } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listBenchmarkLogs((await params).id, after));
});
@@ -0,0 +1,20 @@
import { readFile } from "node:fs/promises";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { payloadFile } from "@/lib/publications";
export const dynamic = "force-dynamic";
/** The exact payload the preview built, byte for byte what would be sent to launch80. */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]/payload">>(async (_req, { params }) => {
const { id, pubId } = await params;
let path: string;
try {
path = payloadFile(id, pubId);
} catch {
return apiError(404, "not_found", "No payload for this preview.");
}
const body = await readFile(path).catch(() => null);
if (!body) return apiError(404, "not_found", "No payload for this preview.");
return new Response(body, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="launch80-payload-${pubId.slice(-6).toLowerCase()}.json"` } });
});
@@ -0,0 +1,45 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { confirmPublication, discardPublication, PublicationError, readPayloadPreview } from "@/lib/publications";
export const dynamic = "force-dynamic";
/** What the previewed payload contains (read from the exact file that would be sent). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]">>(async (_req, { params }) => {
try {
const { id, pubId } = await params;
return NextResponse.json({ preview: await readPayloadPreview(id, pubId) });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
const Confirm = z.object({ confirm: z.literal(true) });
/** Opt-in 2: publish the previewed payload. Requires `{ "confirm": true }`. */
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]">>(async (req, { params, session }) => {
try {
const { id, pubId } = await params;
Confirm.parse(await req.json());
await confirmPublication(id, pubId, session.user.email ?? session.user.name ?? null);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Discard a preview. */
export const DELETE = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]">>(async (_req, { params }) => {
try {
const { id, pubId } = await params;
await discardPublication(id, pubId);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,24 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getL80Status, listPublications, PreviewBody, PublicationError, requestPreview } from "@/lib/publications";
export const dynamic = "force-dynamic";
/** This run's launch80 publications and whether publishing is available (never the token). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/publications">>(async (_req, { params }) => {
const { id } = await params;
const [status, publications] = await Promise.all([getL80Status(), listPublications(id)]);
return NextResponse.json({ status, publications });
});
/** Opt-in 1: prepare a preview (L80 dry run). Nothing is sent to launch80. */
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/publications">>(async (req, { params }) => {
try {
const { id } = await params;
return NextResponse.json(await requestPreview(id, PreviewBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,27 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { REPORT_FILE, runDir } from "@/lib/benchmark-paths";
import { getBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/**
* BetterBench's self-contained HTML report. Served sandboxed (opaque origin, no network): it is
* generated content and must not run with access to Kaname's session.
*/
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/report">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
if (!run?.hasReport) return apiError(404, "not_found", "This run has no report.");
const html = await readFile(join(runDir(run.id), REPORT_FILE)).catch(() => null);
if (!html) return apiError(404, "not_found", "The report file is missing.");
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, max-age=300",
},
});
});
@@ -0,0 +1,29 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { AB_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { getBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/** BetterBench's results.json without endpoint and host, as a download (works with `betterbench report/compare` and `L80 betterbench --results`). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/results">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
if (!run) return apiError(404, "not_found", "Benchmark not found.");
const ab = run.kind === "ab";
const raw = await readFile(join(runDir(run.id), ab ? AB_FILE : RESULTS_FILE), "utf8").catch(() => null);
if (!raw) return apiError(404, "not_found", "This run has no results file.");
// Like launch80's L80 CLI: the endpoint URL and host name never leave the machine.
const data = JSON.parse(raw) as { env?: Record<string, unknown>; endpoint_a?: unknown; endpoint_b?: unknown };
if (data.env) {
delete data.env.endpoint;
delete data.env.endpoint_b;
delete data.env.host;
}
delete data.endpoint_a;
delete data.endpoint_b;
const json = JSON.stringify(data, null, 2);
const name = `betterbench-${ab ? "ab-" : ""}${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } });
});
+36
View File
@@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { BenchmarkError, DESCRIPTION_MAX, deleteBenchmark, getBenchmark, updateBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
return run ? NextResponse.json(run) : apiError(404, "not_found", "Benchmark not found.");
});
const Patch = z.object({ label: z.string().max(120).nullable().optional(), description: z.string().max(DESCRIPTION_MAX).nullable().optional() });
/** Rename (label) a run or change its description. */
export const PATCH = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (req, { params }) => {
try {
await updateBenchmark((await params).id, Patch.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Delete a run with its log and files. */
export const DELETE = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, { params }) => {
try {
await deleteBenchmark((await params).id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { BenchmarkBody, BenchmarkError, createBenchmark, listBenchmarks } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/** All runs, newest first; `?deployment=<id>` or `?model=<id>` narrows them. */
export const GET = withAuth(async (req) => {
const sp = new URL(req.url).searchParams;
return NextResponse.json(await listBenchmarks({ deploymentId: sp.get("deployment") ?? undefined, modelId: sp.get("model") ?? undefined }));
});
/** Queue a BetterBench run against a running deployment. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createBenchmark(BenchmarkBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+17
View File
@@ -0,0 +1,17 @@
import { NextResponse } from "next/server";
import { approveJob } from "@/lib/agent-downloads";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError } from "@/lib/jobs";
/** Let a download requested through the API start. */
export const POST = withAuth<RouteContext<"/api/jobs/[id]/approve">>(async (_req, { params }) => {
const { id } = await params;
try {
await approveJob(id);
return NextResponse.json({ ok: true });
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { rejectJob } from "@/lib/agent-downloads";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError } from "@/lib/jobs";
/** Turn down a download requested through the API (a model only it added leaves the library). */
export const POST = withAuth<RouteContext<"/api/jobs/[id]/reject">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await rejectJob(id));
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+30
View File
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { APPROVAL_MODES } from "@/lib/agent-guardrails";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getGuardrails, saveGuardrails, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Guardrails for downloads requested through the API. */
export const GET = withAuth(async () => NextResponse.json(await getGuardrails()));
const Body = z
.object({
approvalMode: z.enum(APPROVAL_MODES),
maxRequestBytes: z.number(),
minFreeBytes: z.number(),
maxOpenJobs: z.number().int(),
allowedAuthors: z.array(z.string()).max(100),
})
.partial();
export const PUT = withAuth(async (req) => {
try {
return NextResponse.json(await saveGuardrails(Body.parse(await req.json())));
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+15 -6
View File
@@ -2,19 +2,28 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getRecommendedRoles, saveRecommendedRoles, SettingsError } from "@/lib/settings";
import { getDownloadSpeedLimit, getRecommendedRoles, saveDownloadSpeedLimit, saveRecommendedRoles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Download settings: which file kinds are picked along with model weights. */
export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() }));
async function current() {
return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit() };
}
const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) });
/** Download settings: which file kinds are picked along with model weights, and the speed limit. */
export const GET = withAuth(async () => NextResponse.json(await current()));
const Body = z.object({
recommendedRoles: z.array(z.string()).max(32).optional(),
maxBytesPerSecond: z.number().nullable().optional(),
});
export const PUT = withAuth(async (req) => {
try {
const { recommendedRoles } = Body.parse(await req.json());
return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) });
const body = Body.parse(await req.json());
if (body.recommendedRoles) await saveRecommendedRoles(body.recommendedRoles);
if (body.maxBytesPerSecond !== undefined) await saveDownloadSpeedLimit(body.maxBytesPerSecond);
return NextResponse.json(await current());
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
+18
View File
@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getHardwareOverrides, saveHardwareOverrides, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Manual hardware values for benchmark records (Settings → Hardware). */
export const GET = withAuth(async () => NextResponse.json(await getHardwareOverrides()));
export const PUT = withAuth(async (req) => {
try {
return NextResponse.json(await saveHardwareOverrides(await req.json()));
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+14
View File
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { cancelSweep, SweepRequestError } from "@/lib/sweeps";
export const POST = withAuth<RouteContext<"/api/sweeps/[id]/cancel">>(async (_req, { params }) => {
try {
await cancelSweep((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteSweep, getSweep, SweepRequestError } from "@/lib/sweeps";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/sweeps/[id]">>(async (_req, { params }) => {
const s = await getSweep((await params).id);
return s ? NextResponse.json(s) : apiError(404, "not_found", "Sweep not found.");
});
export const DELETE = withAuth<RouteContext<"/api/sweeps/[id]">>(async (_req, { params }) => {
try {
await deleteSweep((await params).id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+18
View File
@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createSweep, listSweeps, SweepBody, SweepRequestError } from "@/lib/sweeps";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listSweeps()));
/** Queue a sweep: one or two settings varied over a base deployment, one benchmark per variant. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createSweep(SweepBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+34
View File
@@ -0,0 +1,34 @@
import { reservedBytes } from "@/lib/agent-downloads";
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Json } from "@/lib/api-v1";
import { getGuardrails } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export const dynamic = "force-dynamic";
/**
* Space on the models folder (reported by the worker every few seconds), what open downloads
* still need, and how much an agent request may use before hitting the minimum-free guardrail.
*/
export const GET = withToken("models:read", async () => {
try {
const [w, reserved, g] = await Promise.all([getWorkerStatus(), reservedBytes(), getGuardrails()]);
const free = w.online ? w.modelsDirFreeBytes : null;
const total = w.online ? w.modelsDirTotalBytes : null;
const available = free == null ? null : Math.max(0, free - reserved - g.minFreeBytes);
return v1Json({
workerOnline: w.online,
freeBytes: free,
totalBytes: total,
usedBytes: free != null && total != null ? total - free : null,
reservedBytes: reserved,
minFreeBytes: g.minFreeBytes,
availableForRequestsBytes: available,
free: size(free),
total: size(total),
availableForRequests: size(available),
});
} catch (err) {
return v1Catch(err);
}
});
+45
View File
@@ -0,0 +1,45 @@
import { z } from "zod";
import { requestDownload } from "@/lib/agent-downloads";
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Json } from "@/lib/api-v1";
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
export const dynamic = "force-dynamic";
const Body = z
.object({
repoId: z.string().trim().regex(REPO_ID_RE, 'must be "org/name"'),
sha: z.string().trim().regex(SHA_RE, "must be the full 40-character commit SHA from GET /api/v1/hub/lookup"),
revision: z.string().trim().min(1).max(255).optional(),
quant: z.string().trim().min(1).max(64).optional(),
include: z.array(z.string().trim().min(1).max(1024)).min(1).max(100).optional(),
tags: z.array(z.string()).max(20).optional(),
})
.strict()
.refine((b) => !!b.quant !== !!b.include, { message: 'pass exactly one of "quant" (e.g. "Q4_K_M") or "include" (globs)' });
/**
* Request a download, within the guardrails. 201: queued or waiting for approval; 200: the same
* repo + commit + files was requested before, nothing new was queued.
*/
export const POST = withToken("downloads:create", async (req, { token }) => {
try {
const body = Body.parse(await req.json());
const r = await requestDownload(token, body);
return v1Json(
{
created: r.created,
modelId: r.modelId,
jobId: r.jobId,
state: r.state,
requestedBytes: r.requestedBytes,
requestedSize: size(r.requestedBytes),
files: r.files,
message: r.message.replace("{jobId}", r.jobId ?? "{jobId}"),
},
r.created ? 201 : 200,
);
} catch (err) {
return v1Catch(err);
}
});
+47
View File
@@ -0,0 +1,47 @@
import { eq } from "drizzle-orm";
import { quantSummary } from "@/lib/agent-selection";
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup";
export const dynamic = "force-dynamic";
/** Files listed inline up to this count; more with ?files=all. */
const FILE_LIMIT = 200;
/**
* Resolve a Hub repo (+ revision, default main) to its commit SHA, with the quants and files and
* their sizes: what a download request needs. The same lookup the Add model dialog uses.
*/
export const GET = withToken("models:read", async (req) => {
try {
const url = new URL(req.url);
const repo = url.searchParams.get("repo")?.trim();
if (!repo) return v1Error(400, "invalid_request", 'Pass the repo as ?repo=org/name, e.g. ?repo=unsloth/Qwen3-8B-GGUF.');
const { repoId, revision: urlRevision } = normalizeRepoInput(repo);
const revision = url.searchParams.get("revision")?.trim() || urlRevision || "main";
const r = await lookupRepo(repoId, revision);
const all = url.searchParams.get("files") === "all";
const model = r.existingModelId
? await db().query.models.findFirst({ columns: { id: true, pinnedSha: true, status: true }, where: eq(models.id, r.existingModelId) })
: null;
return v1Json({
repoId: r.repoId,
revision: r.revision,
sha: r.sha,
gated: r.gated,
lastModified: r.lastModified,
inLibrary: model ? { modelId: model.id, pinnedSha: model.pinnedSha, status: model.status } : null,
quants: quantSummary(r.files).map((q) => ({ ...q, size: size(q.bytes) })),
fileCount: r.files.length,
totalBytes: r.files.reduce((s, f) => s + f.size, 0),
files: (all ? r.files : r.files.slice(0, FILE_LIMIT)).map((f) => ({ path: f.path, bytes: f.size })),
filesTruncated: !all && r.files.length > FILE_LIMIT,
next: 'POST /api/v1/downloads with {"repoId", "sha", "quant"} (or "include": [globs]).',
});
} catch (err) {
return v1Catch(err);
}
});
+58
View File
@@ -0,0 +1,58 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
import { getJob, listJobFiles, listJobLogs } from "@/lib/jobs";
export const dynamic = "force-dynamic";
const MAX_LOG = 200;
const NEXT: Record<string, string> = {
pending_approval: "Waiting for the user to approve it. Don't retry; check again in a few minutes.",
queued: "Waiting for a free download slot.",
downloading: "Downloading; check again in a minute.",
verifying: "Checking the downloaded files.",
completed: "Done.",
failed: "Failed; see error. Tell the user; retrying the same request returns this job.",
cancelled: "Cancelled or rejected by the user. Don't request it again unless the user asks.",
interrupted: "Interrupted by a Kaname restart; the user can resume it.",
};
/** Job state with per-file progress. The hf log only with ?log=N (last N lines, max 200). */
export const GET = withToken<RouteContext<"/api/v1/jobs/[id]">>("models:read", async (req, { params }) => {
try {
const id = (await params).id;
const job = await getJob(id);
if (!job) return v1Error(404, "not_found", "No job with this id.");
const n = Math.min(MAX_LOG, Math.max(0, Number(new URL(req.url).searchParams.get("log")) || 0));
const files = await listJobFiles(id);
const log = n > 0 ? (await listJobLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined;
return v1Json({
id: job.id,
modelId: job.modelId,
repoId: job.repoId,
kind: job.kind,
purpose: job.purpose,
state: job.state,
cancelRequested: job.cancelRequested,
requestedBy: job.requestedBy,
progress: {
doneBytes: job.doneBytes,
totalBytes: job.totalBytes,
percent: job.totalBytes > 0 ? Math.round((job.doneBytes / job.totalBytes) * 1000) / 10 : 0,
done: size(job.doneBytes),
total: size(job.totalBytes),
speedBytesPerSecond: job.speedBps,
etaSeconds: job.etaSeconds,
},
error: job.errorCode || job.errorMessage ? { code: job.errorCode, message: job.errorMessage } : null,
files: files.map((f) => ({ path: f.path, state: f.state, doneBytes: f.doneBytes, totalBytes: f.expectedBytes })),
createdAt: new Date(job.createdAt).toISOString(),
startedAt: job.startedAt ? new Date(job.startedAt).toISOString() : null,
finishedAt: job.finishedAt ? new Date(job.finishedAt).toISOString() : null,
next: NEXT[job.state] ?? null,
...(log ? { log } : {}),
});
} catch (err) {
return v1Catch(err);
}
});
+34
View File
@@ -0,0 +1,34 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
import { listModelJobs } from "@/lib/jobs";
import { getModel } from "@/lib/library";
export const dynamic = "force-dynamic";
/** One model: status, pinned commit, selected files and its latest job. */
export const GET = withToken<RouteContext<"/api/v1/models/[id]">>("models:read", async (_req, { params }) => {
try {
const data = await getModel((await params).id);
if (!data) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models.");
const { model, files } = data;
const selected = files.filter((f) => f.selected);
const onDisk = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
const [job] = await listModelJobs(model.id, 1);
return v1Json({
id: model.id,
repoId: model.repoId,
status: model.status,
trackedRevision: model.trackedRevision,
pinnedSha: model.pinnedSha,
requestedBy: model.requestedBy,
onDiskBytes: onDisk,
onDisk: size(onDisk),
files: selected.map((f) => ({ path: f.path, bytes: f.size, state: f.state })),
latestJob: job ? { id: job.id, kind: job.kind, state: job.state, requestedBy: job.requestedBy } : null,
createdAt: model.createdAt.toISOString(),
downloadedAt: model.downloadedAt?.toISOString() ?? null,
});
} catch (err) {
return v1Catch(err);
}
});
+61
View File
@@ -0,0 +1,61 @@
import { withToken } from "@/lib/api-tokens";
import { parseModelFilters } from "@/lib/api-v1-filters";
import { size, v1Catch, v1Json } from "@/lib/api-v1";
import { listLibrary } from "@/lib/library";
import { matchesFilters, matchesQuery, type SearchableModel } from "@/lib/search";
export const dynamic = "force-dynamic";
/**
* The local library, filtered like the library page: ?q= (all terms must match) and facets
* author, family, quant, tag, status, requested_by (repeat or comma-separate values).
* Status values: pending, downloading, ready, incomplete, failed, deleting, pending_approval,
* update_available, repo_missing, commit_missing.
*/
export const GET = withToken("models:read", async (req) => {
try {
const { query, filters } = parseModelFilters(new URL(req.url).searchParams);
const rows = await listLibrary();
const out = rows
.filter((r) => {
const m: SearchableModel = {
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" ? r.hubState : r.updateAvailable ? "update_available" : null,
requestedBy: r.requestedBy,
pendingApproval: r.pendingApproval,
};
return matchesQuery(m, query) && matchesFilters(m, filters);
})
.map((r) => ({
id: r.id,
repoId: r.repoId,
status: r.status,
pendingApproval: r.pendingApproval,
pinnedSha: r.pinnedSha,
quants: r.quants,
tags: r.tags.map((t) => t.name),
selectedFiles: r.fileCount,
selectedBytes: r.totalBytes,
onDiskBytes: r.presentBytes,
onDisk: size(r.presentBytes),
updateAvailable: r.updateAvailable,
hubState: r.hubState,
requestedBy: r.requestedBy,
createdAt: r.createdAt.toISOString(),
downloadedAt: r.downloadedAt?.toISOString() ?? null,
}));
return v1Json({ count: out.length, models: out });
} catch (err) {
return v1Catch(err);
}
});
+30
View File
@@ -0,0 +1,30 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Json } from "@/lib/api-v1";
import { getGuardrails } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Who am I, what may I do, and within which limits. Any valid token. */
export const GET = withToken(null, async (_req, { token }) => {
const g = await getGuardrails();
return v1Json({
token: { name: token.name, scopes: token.scopes },
guardrails: {
approvalMode: g.approvalMode,
maxRequestBytes: g.maxRequestBytes,
maxRequestSize: size(g.maxRequestBytes),
minFreeBytes: g.minFreeBytes,
minFreeSize: size(g.minFreeBytes),
maxOpenAgentJobs: g.maxOpenJobs,
allowedAuthors: g.allowedAuthors,
},
endpoints: [
"GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]",
"GET /api/v1/models[?q=&author=&family=&quant=&tag=&status=&requested_by=]",
"GET /api/v1/models/{id}",
"POST /api/v1/downloads {repoId, sha, quant | include[], tags?, revision?}",
"GET /api/v1/jobs/{id}[?log=50]",
"GET /api/v1/disk",
],
});
});
+4
View File
@@ -21,6 +21,7 @@
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-series: var(--series);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
@@ -68,6 +69,8 @@
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
/* Single-series data color (benchmark charts); validated reference blue, light surface. */
--series: #2a78d6;
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
@@ -103,6 +106,7 @@
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--series: #3987e5;
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
+3 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import { GaugeIcon, LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
@@ -10,9 +10,10 @@ const LINKS = [
href: "/",
label: "Library",
icon: LibraryIcon,
active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/deployments"),
active: (p: string) => !["/settings", "/deployments", "/benchmarks"].some((x) => p.startsWith(x)),
},
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
{ href: "/benchmarks", label: "Benchmarks", icon: GaugeIcon, active: (p: string) => p.startsWith("/benchmarks") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { BotIcon, CheckIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { approveJob, rejectJob } from "@/components/job-actions";
import { Button } from "@/components/ui/button";
import { formatBytes } from "@/lib/format";
/** A download requested through the API that waits for approval: who asked, how much, approve/reject. */
export function ApprovalBar({ job, onRemoved }: { job: { id: string; requestedBy: string | null; totalBytes: number; purpose: string | null }; onRemoved?: () => void }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function run(fn: () => Promise<unknown>) {
setBusy(true);
try {
await fn();
router.refresh();
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2.5 text-sm">
<p className="flex items-center gap-1.5">
<BotIcon className="size-4 shrink-0 text-amber-700 dark:text-amber-300" />
<span>
<strong>{job.requestedBy ?? "An API token"}</strong> asks to download {formatBytes(job.totalBytes)}
{job.purpose === "add" ? " of additional files" : ""}. It starts once you approve it.
</span>
</p>
<div className="flex gap-2">
<Button size="sm" disabled={busy} onClick={() => run(() => approveJob(job.id))}>
<CheckIcon />
Approve
</Button>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() =>
run(async () => {
const r = await rejectJob(job.id);
if (r?.removedModel) onRemoved?.();
})
}
>
<XIcon />
Reject
</Button>
</div>
</div>
);
}
+125
View File
@@ -0,0 +1,125 @@
"use client";
import { useState } from "react";
import { cn } from "@/lib/utils";
export type BarRow = {
label: string;
/** Bar length (mode "bar") or median tick (mode "range"). */
value: number | null;
/** Mode "range": the span, e.g. 1% low → 99% high. */
range?: [number, number] | null;
/** Text at the bar tip. */
valueLabel?: string;
/** Tooltip lines. */
details?: string[];
};
/** Clean axis maximum and ticks (0 / 25 / 50 / 75 / 100 style). */
function niceTicks(max: number): number[] {
if (!(max > 0)) return [0, 1];
const raw = max / 4;
const mag = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;
const ticks: number[] = [];
for (let t = 0; t <= max + step * 0.001; t += step) ticks.push(Number(t.toPrecision(6)));
if (ticks[ticks.length - 1] < max) ticks.push(Number((ticks[ticks.length - 1] + step).toPrecision(6)));
return ticks;
}
const fmtTick = (v: number) => (v >= 1000 ? v.toLocaleString("en-US", { maximumFractionDigits: 0 }) : v.toLocaleString("en-US", { maximumFractionDigits: 2 }));
/**
* Horizontal single-series bars (one hue), value at the tip, a hover tooltip per row, an optional
* reference line (e.g. the weighted combined score). Mode "range" draws a span with a median tick.
*/
export function BarChart({
rows,
axisLabel,
reference,
mode = "bar",
className,
}: {
rows: BarRow[];
axisLabel: string;
reference?: { value: number; label: string } | null;
mode?: "bar" | "range";
className?: string;
}) {
const [hover, setHover] = useState<number | null>(null);
const max = Math.max(...rows.map((r) => (mode === "range" ? (r.range?.[1] ?? r.value ?? 0) : (r.value ?? 0))), reference?.value ?? 0);
const ticks = niceTicks(max);
const top = ticks[ticks.length - 1] || 1;
const pct = (v: number) => `${Math.max(0, Math.min(100, (v / top) * 100))}%`;
return (
<div className={cn("flex flex-col gap-1 text-xs", className)} role="img" aria-label={`${axisLabel} by ${rows.map((r) => r.label).join(", ")}`}>
<div className="relative grid grid-cols-[minmax(5rem,9rem)_1fr] gap-x-3">
{/* gridlines + reference line span the plot column */}
<div />
<div className="pointer-events-none relative">
<div className="absolute inset-0">
{ticks.map((t) => (
<div key={t} className="absolute top-0 bottom-0 w-px bg-border" style={{ left: pct(t), height: `${rows.length * 32}px` }} />
))}
{reference && (
<div className="absolute top-0 w-0.5 bg-foreground/70" style={{ left: pct(reference.value), height: `${rows.length * 32}px` }}>
<span className="absolute -top-4 left-1 whitespace-nowrap text-[11px] text-muted-foreground">{reference.label}</span>
</div>
)}
</div>
</div>
{rows.map((r, i) => (
<div key={r.label} className="contents" onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover((h) => (h === i ? null : h))}>
<div className={cn("flex h-8 items-center justify-end truncate text-right", hover === i ? "text-foreground" : "text-muted-foreground")} title={r.label}>
{r.label}
</div>
<div className="relative h-8">
{mode === "bar" && r.value != null && (
<div className="absolute top-1/2 left-0 h-5 -translate-y-1/2 rounded-r-[4px] bg-series" style={{ width: pct(r.value) }} />
)}
{mode === "range" && r.range && (
<>
<div
className="absolute top-1/2 h-3 -translate-y-1/2 rounded-[4px] bg-series/35"
style={{ left: pct(r.range[0]), width: `calc(${pct(r.range[1])} - ${pct(r.range[0])})` }}
/>
{r.value != null && <div className="absolute top-1/2 h-5 w-0.5 -translate-y-1/2 bg-series" style={{ left: pct(r.value) }} />}
</>
)}
{r.valueLabel && (
<span
className="absolute top-1/2 ml-1.5 -translate-y-1/2 whitespace-nowrap text-foreground tabular-nums"
style={{ left: pct(mode === "range" ? (r.range?.[1] ?? r.value ?? 0) : (r.value ?? 0)) }}
>
{r.valueLabel}
</span>
)}
{hover === i && r.details && r.details.length > 0 && (
<div className="absolute top-full left-0 z-20 mt-1 min-w-48 rounded-lg bg-popover px-3 py-2 text-popover-foreground shadow-lg ring-1 ring-foreground/10">
<div className="mb-1 font-medium">{r.label}</div>
{r.details.map((d) => (
<div key={d} className="text-muted-foreground tabular-nums">
{d}
</div>
))}
</div>
)}
</div>
</div>
))}
{/* axis */}
<div />
<div className="relative mt-1 h-4 text-[11px] text-muted-foreground tabular-nums">
{ticks.map((t) => (
<span key={t} className="absolute -translate-x-1/2" style={{ left: pct(t) }}>
{fmtTick(t)}
</span>
))}
</div>
<div />
<div className="mt-1 text-[11px] tracking-wide text-muted-foreground uppercase">{axisLabel}</div>
</div>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
import type { ResourceStats } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1));
const mib = (v: number | null | undefined) => (v == null ? "—" : formatBytes(v * 2 ** 20));
const round = (v: number | null | undefined, unit: string) => (v == null ? "—" : `${Math.round(v)}${unit}`);
function Cell({ label, value, note }: { label: string; value: string; note?: 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}</span>
{note && <span className="text-[11px] text-muted-foreground">{note}</span>}
</div>
);
}
/** Resource use sampled during a run: per deployment (A/B: both sides) and per GPU. */
export function BenchmarkResources({ stats, names }: { stats: ResourceStats; names?: { a: string; b?: string } }) {
if (stats.samples === 0 && stats.gpus.length === 0) return <p className="text-sm text-muted-foreground">No resource samples were recorded.</p>;
const multi = stats.containers.length > 1;
return (
<div className="flex flex-col gap-3">
{stats.containers.map((c) => (
<div key={c.side} className="flex flex-col gap-1.5">
{multi && <span className="text-xs font-medium">{c.side === "a" ? `A · ${names?.a ?? ""}` : `B · ${names?.b ?? ""}`}</span>}
<div className="grid gap-2 sm:grid-cols-3">
<Cell label="CPU, average" value={`${cores(c.cpuAvg)} cores`} note={`peak ${cores(c.cpuPeak)} cores`} />
<Cell
label="RAM, peak"
value={c.memPeakBytes != null ? formatBytes(c.memPeakBytes) : "—"}
note={`average ${c.memAvgBytes != null ? formatBytes(c.memAvgBytes) : "—"}${c.memLimitBytes ? ` · limit ${formatBytes(c.memLimitBytes)}` : ""}`}
/>
{c.memPeakBytes != null && c.memLimitBytes ? (
<Cell label="Of the limit" value={`${Math.round((c.memPeakBytes / c.memLimitBytes) * 100)}%`} note="peak RAM ÷ memory limit" />
) : (
<Cell label="Of the limit" value="—" note="no memory limit set" />
)}
</div>
</div>
))}
{stats.gpus.map((g) => (
<div key={g.index} className="flex flex-col gap-1.5">
<span className="text-xs font-medium">
GPU {g.index} · {g.name}
</span>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<Cell label="VRAM, peak" value={mib(g.vramPeakMb)} note={`of ${mib(g.vramTotalMb)} · average ${mib(g.vramAvgMb)}`} />
<Cell label="Utilization" value={round(g.utilAvg, "%")} note={g.utilPeak != null ? `average · peak ${round(g.utilPeak, "%")}` : "not reported"} />
<Cell label="Power" value={round(g.powerAvgW, " W")} note={g.powerPeakW != null ? `average · peak ${round(g.powerPeakW, " W")}` : "not reported"} />
<Cell label="Temperature" value={round(g.tempAvgC, " °C")} note={g.tempPeakC != null ? `average · peak ${round(g.tempPeakC, " °C")}` : "not reported"} />
</div>
</div>
))}
<p className="text-[11px] text-muted-foreground">
Sampled every ~2 s over {stats.seconds} s ({stats.samples} samples). RAM is the container&apos;s usage without page cache, like <code>docker stats</code>; GPU
figures are for the whole GPU, so other work on it counts too.
</p>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { LoaderCircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const STYLE: Record<string, string> = {
queued: "border-foreground/15 text-muted-foreground",
running: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
completed: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
failed: "border-destructive/30 bg-destructive/10 text-destructive",
cancelled: "border-foreground/15 text-muted-foreground",
};
export function BenchmarkStateBadge({ state, cancelling, className }: { state: string; cancelling?: boolean; className?: string }) {
const label = state === "running" && cancelling ? "cancelling" : state;
return (
<span className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-4xl border px-2 text-xs font-medium whitespace-nowrap", STYLE[state] ?? STYLE.queued, className)}>
{state === "running" && <LoaderCircleIcon className="size-3 animate-spin" />}
{label}
</span>
);
}
+18
View File
@@ -31,3 +31,21 @@ export async function startUpdate(modelId: string): Promise<boolean> {
if (ok) toast.success("Update queued");
return ok;
}
export async function approveJob(jobId: string): Promise<boolean> {
const ok = await post(`/api/jobs/${jobId}/approve`);
if (ok) toast.success("Approved; the download is queued");
return ok;
}
/** Returns whether the model left the library (it was only added by this request), or null on error. */
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> {
const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" });
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return null;
}
toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected");
return body;
}
+7 -1
View File
@@ -4,6 +4,7 @@ import { formatBytes, formatDuration, formatSpeed, percent } from "@/lib/format"
import type { JobSnapshot } from "@/lib/jobs";
const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
pending_approval: "outline",
queued: "outline",
downloading: "secondary",
verifying: "secondary",
@@ -14,7 +15,12 @@ const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "o
};
export function JobStateBadge({ job }: { job: Pick<JobSnapshot, "state" | "cancelRequested"> }) {
const label = job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state) ? "cancelling" : job.state;
const label =
job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state)
? "cancelling"
: job.state === "pending_approval"
? "awaiting approval"
: job.state;
return <Badge variant={STATE_VARIANT[job.state] ?? "outline"}>{label}</Badge>;
}
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "@/lib/utils";
type LogLine = { id: number; ts: number; stream: string; line: string };
/** Polls `url?after=<id>` for new lines and keeps the view pinned to the bottom unless scrolled up. */
export function LiveLog({ url, title = "Log", live = true, className }: { url: string; title?: string; live?: boolean; className?: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`${url}?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
if (!live) return () => void (stopped = true);
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [url, live]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className={cn("min-w-0", className)}>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { BotIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
/** "requested by hermes": added or downloaded through the API with that token. */
export function RequestedByBadge({ name, className }: { name: string | null | undefined; className?: string }) {
if (!name) return null;
return (
<Badge variant="outline" className={cn("gap-1 font-normal", className)} title={`Requested through the API with the token "${name}"`}>
<BotIcon className="size-3" />
{name}
</Badge>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { metaRows } from "@/lib/benchmark-meta";
import type { RunMeta, SystemSummary } from "@/lib/db/schema";
import { systemSummaryLines } from "@/lib/hardware";
/** Hardware, runtime and model a run measured (A and B side by side for an A/B), plus the system summary. */
export function RunMetaCard({ meta, metaB, system }: { meta: RunMeta | null; metaB?: RunMeta | null; system: SystemSummary | null }) {
if (!meta && !system) return null;
const a = meta ? metaRows(meta) : [];
const b = metaB ? metaRows(metaB) : null;
const keys = [...new Set([...a, ...(b ?? [])].map((r) => r.key))];
const label = (k: string) => (a.find((r) => r.key === k) ?? b?.find((r) => r.key === k))!.label;
const value = (rows: typeof a | null, k: string) => rows?.find((r) => r.key === k)?.value ?? "–";
return (
<Card size="sm">
<CardHeader>
<CardTitle>Hardware &amp; runtime</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{meta && (
<dl className={`grid gap-x-4 gap-y-1 text-xs ${b ? "grid-cols-[max-content_1fr_1fr]" : "grid-cols-[max-content_1fr]"}`}>
{b && (
<>
<span />
<span className="font-medium">A</span>
<span className="font-medium">B</span>
</>
)}
{keys.map((k) => (
<div key={k} className="contents">
<dt className="text-muted-foreground">{label(k)}</dt>
<dd className="min-w-0 font-mono break-all">{value(a, k)}</dd>
{b && <dd className="min-w-0 font-mono break-all">{value(b, k)}</dd>}
</div>
))}
</dl>
)}
{meta && meta.overridden.length > 0 && <p className="text-[11px] text-muted-foreground">From Settings → Hardware: {meta.overridden.join(", ")}.</p>}
{system && (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">System</span>
<ul className="flex flex-col gap-0.5 text-xs">
{systemSummaryLines(system).map((l) => (
<li key={l}>{l}</li>
))}
</ul>
</div>
)}
</CardContent>
</Card>
);
}
+10 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import { BotIcon, BoxesIcon, CpuIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -71,9 +71,17 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<BoxesIcon />
Runtimes
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/hardware" />}>
<CpuIcon />
Hardware
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
<KeyRoundIcon />
API keys
Runtime API keys
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-tokens" />}>
<BotIcon />
API tokens
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "./ab-report";
import type { AbSummary, PairedResult } from "./db/schema";
const r = (p: Partial<PairedResult>): PairedResult => ({
metric: "decode_tps",
n_pairs: 12,
mean_a: 115,
mean_b: 120,
mean_diff: 5,
pct_diff: 4.37,
ci_low_pct: 3.24,
ci_high_pct: 5.5,
conf: 0.95,
significant: true,
verdict: "B is 4.37% faster — SIGNIFICANT",
higher_is_better: true,
...p,
});
const ab: AbSummary = {
pairs: 12,
decode_tps: r({}),
gap_median: { ...r({ metric: "update_gap_median_ms", pct_diff: -4.6, ci_low_pct: -5.8, ci_high_pct: -3.4, higher_is_better: false }), batched: false },
paired_cv: 0.0178,
pairs_needed_for_mde: 7,
target_mde_pct: 2,
conf: 0.95,
maxPairs: 24,
raw: { a_tps: [], b_tps: [] },
betterbenchVersion: "0.6.1",
corpusVersion: "1.0",
timestamp: null,
config: { greedy: true, temperature: 0.7, warmup: 3, unique_nonce: true, ab_min_pairs: 12 },
};
describe("A/B report text", () => {
it("states the result as BetterBench does", () => {
assert.equal(abHeadline(ab.decode_tps), "B is 4.37% faster");
assert.equal(abHeadline(ab.gap_median), "B is 4.60% faster");
assert.equal(abHeadline(r({ significant: false, pct_diff: 0.3 })), "No measurable difference");
assert.equal(abHeadline(r({ pct_diff: -2 })), "B is 2.00% slower");
assert.ok(Math.abs(halfWidth(ab.decode_tps) - 1.13) < 1e-9);
assert.equal(abSummaryText(ab, "4 threads", "8 threads"), "8 threads (B) against 4 threads (A), 12 interleaved pairs: decode +4.37% (95% CI +3.24% to +5.50%), significant.");
});
it("flags imprecise and inconclusive results", () => {
assert.deepEqual(abCaveats(ab), []);
const wide = { ...ab, pairs: 24, decode_tps: r({ ci_low_pct: -1, ci_high_pct: 5, significant: false }), pairs_needed_for_mde: 90 };
const c = abCaveats(wide);
assert.match(c[0], /±3\.00%, wider than the 2% target: the run stopped at the 24-pair limit first\. About 90 pairs/);
assert.match(c[1], /can't be told apart/);
assert.match(abMethod(ab).join(" "), /narrower than ±2% \(after at least 12 pairs\), or after 24 pairs/);
});
});
+43
View File
@@ -0,0 +1,43 @@
// Text for a paired A/B report (betterbench ab). Every figure is one BetterBench reported. Pure.
import type { AbSummary, PairedResult } from "@/lib/db/schema";
export const halfWidth = (r: PairedResult) => (r.ci_high_pct - r.ci_low_pct) / 2;
const pct = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
/** "B is 4.37% faster" / "No measurable difference" — the headline, from BetterBench's verdict. */
export function abHeadline(r: PairedResult): string {
if (!r.significant) return "No measurable difference";
const better = r.higher_is_better ? r.pct_diff > 0 : r.pct_diff < 0;
return `B is ${Math.abs(r.pct_diff).toFixed(2)}% ${better ? "faster" : "slower"}`;
}
export function abCaveats(ab: AbSummary): string[] {
const out: string[] = [];
const min = ab.config.ab_min_pairs ?? 12;
const hw = halfWidth(ab.decode_tps);
if (ab.pairs < min) out.push(`Only ${ab.pairs} pairs survived (BetterBench's minimum is ${min}); a pair counts only when both calls succeed. Treat the result as indicative.`);
if (hw > ab.target_mde_pct) {
out.push(
`The 95% interval is ±${hw.toFixed(2)}%, wider than the ${ab.target_mde_pct}% target: the run ${ab.maxPairs && ab.pairs >= ab.maxPairs ? `stopped at the ${ab.maxPairs}-pair limit` : "ended"} first. About ${ab.pairs_needed_for_mde} pairs would be needed; differences smaller than ±${hw.toFixed(1)}% can't be told apart here.`,
);
}
if (!ab.decode_tps.significant) out.push("The interval includes zero: A and B can't be told apart at this precision. That is a result, not a failure.");
if (ab.gap_median.batched) out.push("At least one side streamed several tokens per update (speculative or batched decoding), so smoothness is compared as the stream-update gap, not per-token latency.");
return out;
}
export function abMethod(ab: AbSummary): string[] {
const c = ab.config;
return [
`Paired A/B with BetterBench ${ab.betterbenchVersion}${ab.corpusVersion ? `, corpus v${ab.corpusVersion}` : ""}: the same prompt goes to A and B back to back, the order alternating every pair, so drift (heat, caches, background load) hits both sides equally.`,
`${c.greedy ? "Greedy decoding (identical token counts on both sides)" : `Sampled decoding${c.temperature != null ? `, temperature ${c.temperature}` : ""}`}, ${c.unique_nonce === false ? "warm prefix cache" : "cold prefix cache (a unique nonce per pair)"}${c.warmup != null ? `, ${c.warmup} warmup pairs` : ""}.`,
`It stops once the ${Math.round(ab.conf * 100)}% confidence interval of the decode difference is narrower than ±${ab.target_mde_pct}% (after at least ${c.ab_min_pairs ?? 12} pairs)${ab.maxPairs ? `, or after ${ab.maxPairs} pairs` : ""}. The interval is a paired t-interval on the per-pair differences; a difference is significant when it excludes zero.`,
`Decode is tokens per second per request (higher is better); smoothness is the median gap between streamed updates in ms (lower is better). Paired CV ${(ab.paired_cv * 100).toFixed(2)}%: how much the per-pair difference varies.`,
];
}
export function abSummaryText(ab: AbSummary, a: string, b: string): string {
const d = ab.decode_tps;
return `${b} (B) against ${a} (A), ${ab.pairs} interleaved pairs: decode ${pct(d.pct_diff)} (95% CI ${pct(d.ci_low_pct)} to ${pct(d.ci_high_pct)}), ${d.significant ? "significant" : "within noise"}.`;
}
+180
View File
@@ -0,0 +1,180 @@
import "server-only";
import { and, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
import { checkAuthor, checkGuardrails, type Guardrails } from "@/lib/agent-guardrails";
import { newPaths, resolveRequestPaths } from "@/lib/agent-selection";
import type { TokenIdentity } from "@/lib/api-tokens";
import { db } from "@/lib/db/client";
import { jobs, modelFiles, models } from "@/lib/db/schema";
import { lookupRepo } from "@/lib/hub/lookup";
import { JobError, OPEN_STATES, queueDownload } from "@/lib/jobs";
import { purgeModelRows } from "@/lib/model-purge";
import { addFilesToModel, addModel, ModelError, restoreSelection } from "@/lib/models";
import { escapeGlob } from "@/lib/selection";
import { getGuardrails, getRecommendedRoles } from "@/lib/settings";
import { addTag, normalizeTagName } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
export type DownloadRequest = {
repoId: string;
sha: string;
/** Branch to track for update checks (default "main"). */
revision?: string;
quant?: string;
include?: string[];
tags?: string[];
};
export type DownloadOutcome = {
/** false: the same repo + commit + files was requested before; nothing new was queued. */
created: boolean;
modelId: string;
jobId: string | null;
state: string;
requestedBytes: number;
files: string[];
message: string;
};
/** Bytes that open download jobs still have to fetch (pending approval included). */
export async function reservedBytes(): Promise<number> {
const [r] = await db()
.select({ n: sql<number>`coalesce(sum(${jobs.totalBytes} - ${jobs.doneBytes}), 0)` })
.from(jobs)
.where(and(eq(jobs.kind, "download"), inArray(jobs.state, [...OPEN_STATES])));
return Number(r.n);
}
/** API-requested jobs that are pending approval, queued or running (all tokens). */
export async function openAgentJobs(): Promise<number> {
const [r] = await db()
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(and(isNotNull(jobs.requestedByTokenId), inArray(jobs.state, [...OPEN_STATES])));
return Number(r.n);
}
function stateMessage(state: string, created: boolean): string {
if (state === "pending_approval") {
return `${created ? "Requested" : "Already requested"}; waiting for the user to approve it in Kaname. Do not retry: check GET /api/v1/jobs/{jobId} every few minutes.`;
}
if (state === "queued" || state === "downloading" || state === "verifying") return `${created ? "Queued" : "Already queued"}; poll GET /api/v1/jobs/{jobId} for progress.`;
if (state === "completed") return "Already downloaded.";
return `The last download ended as "${state}"; ask the user to retry it in Kaname.`;
}
/** Latest job of a model, for answers to repeated requests. */
async function latestJob(modelId: string) {
return db().query.jobs.findFirst({ columns: { id: true, state: true }, where: eq(jobs.modelId, modelId), orderBy: (j, { desc }) => desc(j.createdAt) });
}
/**
* A download requested through the API. Checks the author allowlist, resolves the files at the
* pinned commit, applies the guardrails, then uses the same addModel / addFilesToModel / queue path
* as the UI. Repeating a request returns what exists instead of queueing a duplicate.
*/
export async function requestDownload(token: TokenIdentity, req: DownloadRequest, guardrails?: Guardrails): Promise<DownloadOutcome> {
const g = guardrails ?? (await getGuardrails());
// The allowlist first, before anything goes to the Hub.
checkAuthor(g, req.repoId);
(req.tags ?? []).forEach(normalizeTagName); // validate before anything is written
const hub = await lookupRepo(req.repoId, req.sha);
const paths = resolveRequestPaths(hub.files, req, await getRecommendedRoles());
const size = new Map(hub.files.map((f) => [f.path, f.size]));
const requestedBy = { tokenId: token.id, name: token.name };
const pendingApproval = g.approvalMode === "approve";
const existing = await db().query.models.findFirst({ where: sql`lower(${models.repoId}) = lower(${hub.repoId})` });
if (existing && existing.pinnedSha !== hub.sha) {
throw new ModelError(
"already_exists",
`${existing.repoId} is already in the library, pinned to commit ${existing.pinnedSha}; you asked for ${hub.sha}. Updating a model is done by the user in Kaname, not through the API.`,
409,
);
}
let add = paths;
if (existing) {
const selected = await db().select({ path: modelFiles.path }).from(modelFiles).where(and(eq(modelFiles.modelId, existing.id), eq(modelFiles.selected, true)));
add = newPaths(paths, selected.map((f) => f.path));
if (add.length === 0) {
const job = await latestJob(existing.id);
const state = job?.state ?? existing.status;
return { created: false, modelId: existing.id, jobId: job?.id ?? null, state, requestedBytes: 0, files: paths, message: stateMessage(state, false) };
}
const open = await db().query.jobs.findFirst({ columns: { id: true, state: true }, where: and(eq(jobs.modelId, existing.id), inArray(jobs.state, [...OPEN_STATES])) });
if (open) {
throw new JobError("busy", `${existing.repoId} has a download that is still ${open.state.replace("_", " ")} (job ${open.id}). Request the other files once it has finished.`, 409);
}
}
const requestBytes = add.reduce((s, p) => s + (size.get(p) ?? 0), 0);
const worker = await getWorkerStatus();
checkGuardrails(g, {
repoId: hub.repoId,
requestBytes,
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
reservedBytes: await reservedBytes(),
openAgentJobs: await openAgentJobs(),
});
let modelId: string;
let jobId: string;
if (existing) {
modelId = existing.id;
({ jobId } = await addFilesToModel(existing.id, add, { pendingApproval, requestedBy }));
} else {
({ id: modelId } = await addModel({
repoId: hub.repoId,
revision: req.revision?.trim() || "main",
sha: hub.sha,
rule: { include: paths.map(escapeGlob), exclude: [] },
requestedBy,
}));
({ jobId } = await queueDownload(modelId, "initial", { pendingApproval, requestedBy }));
}
for (const tag of req.tags ?? []) await addTag(modelId, tag);
const state = pendingApproval ? "pending_approval" : "queued";
return { created: true, modelId, jobId, state, requestedBytes: requestBytes, files: paths, message: stateMessage(state, true) };
}
async function pendingJob(jobId: string) {
const job = await db().query.jobs.findFirst({ where: eq(jobs.id, jobId) });
if (!job) throw new JobError("not_found", "Job not found.", 404);
if (job.state !== "pending_approval") throw new JobError("not_cancellable", `This job doesn't wait for approval (it is ${job.state}).`, 409);
return job;
}
/** Let an API-requested download start. */
export async function approveJob(jobId: string): Promise<void> {
const job = await pendingJob(jobId);
const d = db();
await d.batch([
d.update(jobs).set({ state: "queued" }).where(and(eq(jobs.id, job.id), eq(jobs.state, "pending_approval"))),
d.update(models).set({ status: "downloading" }).where(eq(models.id, job.modelId)),
]);
}
/**
* Turn an API-requested download down. A new model that was only added by this request leaves the
* library again; for added files, the model's previous selection is restored.
*/
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean }> {
const job = await pendingJob(jobId);
await db()
.update(jobs)
.set({ state: "cancelled", finishedAt: new Date(), errorMessage: "Rejected by the user." })
.where(eq(jobs.id, job.id));
if (job.purpose === "initial") {
// Only this request ever touched the model: nothing on disk, so it leaves the library again.
const [{ n }] = await db().select({ n: sql<number>`count(*)` }).from(jobs).where(and(eq(jobs.modelId, job.modelId), ne(jobs.id, job.id)));
if (Number(n) === 0) {
await purgeModelRows(job.modelId);
return { removedModel: true };
}
}
// A pending job never changed the model's status, so only the selection needs restoring.
if (job.result?.previousRule) await restoreSelection(job.modelId, job.result.previousRule);
return { removedModel: false };
}
+133
View File
@@ -0,0 +1,133 @@
// Guardrails for downloads requested through the API (an autonomous agent, not a person in the
// UI). Pure: settings parsing and the checks themselves; the request flow is in agent-downloads.ts.
export const APPROVAL_MODES = ["approve", "auto"] as const;
export type ApprovalMode = (typeof APPROVAL_MODES)[number];
export type Guardrails = {
/** approve: requests wait as "pending approval" until someone confirms them in the UI. */
approvalMode: ApprovalMode;
/** Largest download one request may add. */
maxRequestBytes: number;
/** Free space that must remain on the models folder after the download. */
minFreeBytes: number;
/** API-requested jobs that may be pending approval, queued or running at once (all tokens). */
maxOpenJobs: number;
/** Hub authors (orgs/users) the API may download from; empty = any. Case-insensitive. */
allowedAuthors: string[];
};
const GB = 1_000_000_000;
export const DEFAULT_GUARDRAILS: Guardrails = {
approvalMode: "approve",
maxRequestBytes: 60 * GB,
minFreeBytes: 100 * GB,
maxOpenJobs: 2,
allowedAuthors: [],
};
export class GuardrailError extends Error {
constructor(
public code: "too_large" | "disk_space" | "disk_unknown" | "too_many_jobs" | "author_not_allowed",
message: string,
public status = 422,
) {
super(message);
}
}
const AUTHOR_RE = /^[A-Za-z0-9][\w.-]{0,95}$/;
/** Stored value merged over the defaults; anything invalid falls back to the default. */
export function parseGuardrails(v: unknown): Guardrails {
const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
const num = (x: unknown, min: number, def: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? Math.round(x) : def);
return {
approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_GUARDRAILS.approvalMode,
maxRequestBytes: num(o.maxRequestBytes, 1, DEFAULT_GUARDRAILS.maxRequestBytes),
minFreeBytes: num(o.minFreeBytes, 0, DEFAULT_GUARDRAILS.minFreeBytes),
maxOpenJobs: num(o.maxOpenJobs, 1, DEFAULT_GUARDRAILS.maxOpenJobs),
allowedAuthors: Array.isArray(o.allowedAuthors) ? o.allowedAuthors.filter((a): a is string => typeof a === "string" && AUTHOR_RE.test(a)) : [],
};
}
/** "unsloth, ggml-org Qwen" → ["unsloth", "ggml-org", "Qwen"]; throws on an invalid name. */
export function parseAuthorList(text: string): string[] {
const out: string[] = [];
for (const a of text.split(/[\s,]+/).filter(Boolean)) {
if (!AUTHOR_RE.test(a)) throw new Error(`"${a}" is not a valid Hugging Face user or organization name.`);
if (!out.some((x) => x.toLowerCase() === a.toLowerCase())) out.push(a);
}
return out;
}
/** Plain GB (10^9), as the Hub and the settings use: "74.2 GB". */
export function gb(bytes: number): string {
return `${(bytes / GB).toFixed(1)} GB`;
}
export type GuardrailInput = {
repoId: string;
/** Bytes this request would download. */
requestBytes: number;
/** Free bytes on the models folder (worker heartbeat), or null if unknown. */
freeBytes: number | null;
/** Bytes other open jobs still have to download. */
reservedBytes: number;
/** API-requested jobs that are pending approval, queued or running right now. */
openAgentJobs: number;
};
/** The author allowlist alone (checked before anything goes to the Hub). */
export function checkAuthor(g: Guardrails, repoId: string): void {
const author = repoId.split("/")[0];
if (g.allowedAuthors.length > 0 && !g.allowedAuthors.some((a) => a.toLowerCase() === author.toLowerCase())) {
throw new GuardrailError(
"author_not_allowed",
`author "${author}" is not on the allowlist (${g.allowedAuthors.join(", ")}). Pick a repo from one of these authors, or ask the user to extend the allowlist.`,
403,
);
}
}
/** Throws a GuardrailError with a message an agent can act on; returns normally if allowed. */
export function checkGuardrails(g: Guardrails, x: GuardrailInput): void {
checkAuthor(g, x.repoId);
if (x.requestBytes > g.maxRequestBytes) {
throw new GuardrailError(
"too_large",
`exceeds max size per request ${gb(g.maxRequestBytes)}: requested ${gb(x.requestBytes)}. Pick a smaller quant or fewer files.`,
);
}
if (x.openAgentJobs >= g.maxOpenJobs) {
throw new GuardrailError(
"too_many_jobs",
`too many agent downloads at once: ${x.openAgentJobs} pending or running, the limit is ${g.maxOpenJobs}. Wait until one has finished (or been approved and finished) before requesting another.`,
429,
);
}
if (x.freeBytes == null) {
throw new GuardrailError("disk_unknown", "free disk space is unknown (the Kaname worker is offline). Try again later.", 503);
}
const after = x.freeBytes - x.reservedBytes - x.requestBytes;
if (after < g.minFreeBytes) {
throw new GuardrailError(
"disk_space",
`not enough disk space: ${gb(x.requestBytes)} requested, ${gb(x.freeBytes)} free` +
(x.reservedBytes > 0 ? ` (${gb(x.reservedBytes)} of it reserved by other downloads)` : "") +
`, and at least ${gb(g.minFreeBytes)} must stay free (${gb(Math.max(0, after))} would be left). Pick a smaller quant or ask the user to free space.`,
507,
);
}
}
export function describeGuardrails(g: Guardrails): string {
return [
g.approvalMode === "approve" ? "requests wait for approval" : "downloads start immediately",
`max ${gb(g.maxRequestBytes)} per request`,
`${gb(g.minFreeBytes)} must stay free`,
`max ${g.maxOpenJobs} agent jobs at once`,
g.allowedAuthors.length ? `authors: ${g.allowedAuthors.join(", ")}` : "any author",
].join(" · ");
}
+62
View File
@@ -0,0 +1,62 @@
// Which files an API download request means, from a quant name or include globs, the same way the
// Add model dialog picks them. Pure.
import { fileRole, type FileRole } from "@/lib/file-roles";
import { recommendFiles } from "@/lib/recommend";
import { matchesAny, quantGroup } from "@/lib/selection";
type File = { path: string; size: number };
export class SelectionError extends Error {
code = "empty_selection";
status = 400;
}
/** Quant group of a model-weight file (not mmproj/MTP/imatrix), e.g. "Q4_K_M", "UD-Q4_K_XL". */
function weightQuant(path: string): string | null {
return fileRole(path) === "model" ? quantGroup(path) : null;
}
/** Quants in a repo (model weights only) with file count and total size, in file order. */
export function quantSummary(files: File[]): { quant: string; files: number; bytes: number }[] {
const out = new Map<string, { quant: string; files: number; bytes: number }>();
for (const f of files) {
const q = weightQuant(f.path);
if (!q) continue;
const e = out.get(q) ?? { quant: q, files: 0, bytes: 0 };
e.files++;
e.bytes += f.size;
out.set(q, e);
}
return [...out.values()];
}
/**
* Paths for a request: the weight files of `quant` (all split parts) plus the companion files of the
* recommended kinds (Settings → Downloads), or every file matching one of the `include` globs.
*/
export function resolveRequestPaths(files: File[], req: { quant?: string; include?: string[] }, recommendedRoles: FileRole[]): string[] {
if (req.quant) {
const want = req.quant.trim().toLowerCase();
const weights = files.filter((f) => weightQuant(f.path)?.toLowerCase() === want).map((f) => f.path);
if (weights.length === 0) {
const available = quantSummary(files).map((q) => q.quant);
throw new SelectionError(
available.length
? `quant "${req.quant}" not found in this repo. Available: ${available.join(", ")}.`
: `quant "${req.quant}" not found: this repo has no GGUF quants. Use "include" globs instead (e.g. ["*.safetensors", "*.json"]).`,
);
}
return [...new Set([...weights, ...recommendFiles(files, weights, recommendedRoles)])].sort();
}
const globs = req.include ?? [];
const paths = files.filter((f) => matchesAny(f.path, globs)).map((f) => f.path);
if (paths.length === 0) throw new SelectionError(`no file in this repo matches ${JSON.stringify(globs)}. Look up the repo to see its files.`);
return paths.sort();
}
/** Files a request adds to what's already selected, for size checks and idempotency. */
export function newPaths(requested: string[], selected: Iterable<string>): string[] {
const have = new Set(selected);
return requested.filter((p) => !have.has(p));
}
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more