Compare commits
No files matched your search
+6
-1
@@ -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
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -37,7 +42,7 @@ KANAME_VERSION=
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MAX_CONCURRENT_DOWNLOADS=1
|
||||
# How often the worker checks every model on the Hub (still there? later: newer commits); 0 disables it
|
||||
# How often the worker checks every model on the Hub (still there? newer commit?); 0 disables it
|
||||
UPDATE_CHECK_INTERVAL_HOURS=12
|
||||
# 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk.
|
||||
# 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps.
|
||||
|
||||
@@ -14,10 +14,11 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# No `cache: npm`: the runner's cache server isn't reachable from job containers here, and the
|
||||
# restore + save timeouts cost ~9 minutes per run. `npm ci` alone takes ~20 s.
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Resolve version and image name
|
||||
run: |
|
||||
|
||||
+466
-1
@@ -4,7 +4,472 @@ 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.15.1] - 2026-10-27
|
||||
|
||||
### Added
|
||||
|
||||
- Settings → Downloads → **Models folder scan**: choose when Kaname looks for importable folders
|
||||
in the models folder: every 2 minutes (as before, the default), hourly, daily, weekly or monthly
|
||||
at a time you pick (in your browser's time zone), or only manually. **Scan now** starts one right
|
||||
away; the card shows the last scan, what it found and when the next one is due. A scan missed
|
||||
while the worker was down runs when it is back; a restart no longer scans by itself unless one
|
||||
is due.
|
||||
|
||||
## [0.15.0] - 2026-10-26
|
||||
|
||||
Kaname is back to two jobs: downloading models, and benchmarking the servers that run them. It no
|
||||
longer starts servers itself. Benchmarks run against **endpoints**, any OpenAI-compatible server you
|
||||
add by URL (llama.cpp, vLLM, SGLang, Ollama, …), wherever it runs. The state before this release is
|
||||
kept in the branch `backup` and the tag `backup-0.14.3`.
|
||||
|
||||
**Upgrading:** replace `compose.yaml` with the new one from `deploy/` (the `docker-proxy` service and
|
||||
`DOCKER_HOST` are gone; a `sandbox` service and its volume are new) and run `docker compose up -d
|
||||
--remove-orphans`. Containers Kaname started for deployments keep running; stop them yourself if
|
||||
you don't need them. The database migrates on start: runtimes, deployments, sweeps, API tokens and
|
||||
their settings are deleted; benchmark runs, models and downloads stay.
|
||||
|
||||
### Added
|
||||
|
||||
- **Endpoints** (new top-level page): name, URL, optional API key, the model to benchmark, and
|
||||
**hardware notes** (GPUs, VRAM, PCIe link, P2P, ReBAR, driver, CPU, RAM, OS, virtualization,
|
||||
engine name/version, image, quant, KV cache, context, parallel slots, free text). **Test
|
||||
connection** lists the models the server serves and detects llama.cpp, vLLM, SGLang and Ollama
|
||||
with their version, context and slots where the server tells. The API key never reaches the
|
||||
browser, logs or runs; it goes to BetterBench only through its environment.
|
||||
- Runs against endpoints: BetterBench speed runs, paired A/B between two endpoints serving the same
|
||||
model (each with its own API key), and the quality eval. Kaname asks the server before queuing and
|
||||
again when the run starts; what it reports and the hardware notes are recorded with the run and
|
||||
go into BetterBench's notes and launch80 previews (never the URL or the endpoint's name).
|
||||
- A **sandbox** container for the quality eval's coding section: no network, read-only, no
|
||||
capabilities, memory/CPU/process limits, and only an exchange folder shared with the worker
|
||||
(replaces the throwaway containers the worker used to start through Docker).
|
||||
- Model pages list the benchmark runs of that model (when the endpoint serves it under its repo id).
|
||||
|
||||
### Removed
|
||||
|
||||
- Runtimes, deployments (and their logs, chat, stats), sweeps, the llama.cpp/vLLM presets and the
|
||||
resource/GPU telemetry sampled from deployment containers.
|
||||
- Hardware detection (Settings → Hardware, the probe containers, `pci.ids` in the image): Kaname
|
||||
can't see the machine behind an endpoint; describe it in the endpoint's hardware notes instead.
|
||||
- The API for programs and agents (`/api/v1`, API tokens, guardrails, approvals, the activity log,
|
||||
the agent skills and `docs/api.md`). Every route now requires the login.
|
||||
- Docker access: `DOCKER_HOST`, `KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` and the
|
||||
`docker-proxy` service.
|
||||
|
||||
### Changed
|
||||
|
||||
- Runs from before this release stay readable (with the deployment they measured), but can't be
|
||||
run again.
|
||||
|
||||
## [0.14.3] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Downloads over Xet (any download with a file over 50 GB, or all of them with
|
||||
`HF_HUB_DISABLE_XET=false`) showed little or no progress. Xet keeps downloaded data in memory and
|
||||
writes the file in large chunks, sometimes minutes apart, so the bytes on disk don't show what has
|
||||
arrived. For Xet downloads the worker now turns on `hf`'s progress bars and reads its running
|
||||
byte count; the bars stay out of the job log. Ordinary downloads still measure the files on disk.
|
||||
|
||||
## [0.14.2] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- A running download's progress could jump back and forth between the real value and 0 B while
|
||||
`hf` kept downloading. A single progress reading that missed the partial file (a folder changing
|
||||
while the worker listed it, or a stale size on a network share) counted as nothing downloaded.
|
||||
Folders that vanish mid-listing are now skipped instead of failing the whole listing, and a file's
|
||||
progress no longer goes backwards during a run.
|
||||
|
||||
## [0.14.1] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Downloads with a file over 50 GB failed with "The file is too large to be downloaded using the
|
||||
regular download method". `hf` (huggingface_hub 2.1.1) only downloads such files over Xet, which
|
||||
Kaname turns off by default for steady progress; a download that includes one now uses Xet (noted
|
||||
in the job log; its progress grows in bursts).
|
||||
|
||||
## [0.14.0] - 2026-10-21
|
||||
|
||||
A quality eval next to the speed benchmarks: a short, deterministic check of tool calling, coding and
|
||||
long-context retrieval, so a launch option that makes a model faster but worse shows up.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new column is added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Quality eval** as a run type (deployment page → Benchmark → Quality), run against a deployment
|
||||
with greedy decoding, a fixed seed and thinking turned off:
|
||||
- **tool calling**: 12 requests; one tool call with valid JSON, the right function and arguments;
|
||||
- **coding**: 8 short Python functions, checked by unit tests in a throwaway container from Kaname's
|
||||
own image (no network, read-only, unprivileged user, no capabilities, CPU/memory/process limits);
|
||||
- **long-context retrieval**: a code hidden at 10/50/90 % depth in texts of 25/50/100 % of the
|
||||
context, sized with the server's own tokenizer.
|
||||
The score (0–100) is the mean pass rate of the sections that could run; a server that refuses tool
|
||||
calls doesn't count as 0. The eval set is versioned data in the repo (`src/evals/v1`), and every
|
||||
result records its version (`kaname-eval-1`).
|
||||
- The run page shows the score, each section and every item with the reason it failed. Compare views
|
||||
get a "Quality" group; the benchmark list shows the score; sweeps can run the eval on every variant
|
||||
("Also run the quality eval") and show it as a column.
|
||||
- API: `POST /api/v1/benchmarks` with `kind: "eval"` (optional `sections`), `quality` in run, sweep
|
||||
and compare answers, `"quality": true` for sweeps; the same guardrails as other runs.
|
||||
- The tuning skill checks quality after speed and reports both.
|
||||
|
||||
## [0.13.0] - 2026-10-21
|
||||
|
||||
The agent API can now deploy and benchmark models, so an AI agent can tune launch options for the
|
||||
hardware: within guardrails you set, only on deployments its own token created, and by default only
|
||||
after you approve each start, run and sweep.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new columns and table are added on start. Existing
|
||||
tokens keep their scopes; grant the new ones with **Scopes** in Settings → API tokens.
|
||||
|
||||
### Added
|
||||
|
||||
- **Token scopes** `deployments:read`, `deployments:write`, `benchmarks:read`, `benchmarks:run`, and
|
||||
editing an existing token's scopes.
|
||||
- **`/api/v1` for deployments** ([docs/api.md](docs/api.md)):
|
||||
- `GET /api/v1/runtimes`: pulled runtimes, what they serve, whether agents may use them and which
|
||||
extra arguments; the host's GPUs.
|
||||
- `GET /api/v1/deployments`, `GET /api/v1/deployments/{id}`: state, endpoint, options, the engine
|
||||
version and slots, live CPU/RAM; the log with `?log=N`.
|
||||
- `POST /api/v1/deployments` with the same validation, memory/VRAM estimate and `docker run`
|
||||
command as the form (returned in the answer); `dryRun: true` only checks. Unknown fields are
|
||||
refused instead of ignored.
|
||||
- `PATCH`, `POST …/start`, `POST …/stop`, `DELETE` for the token's own deployments.
|
||||
- **`/api/v1` for benchmarks**: `POST /api/v1/benchmarks` (run or A/B, quick or full, phases,
|
||||
description), `GET /api/v1/benchmarks/{id}` with a compact result (headline numbers, the run's
|
||||
hardware/runtime/model setup, GPU and RAM use; the full summary with `?full=1`), cancel, a list,
|
||||
`GET /api/v1/benchmarks/compare?ids=` (what differs, what's the same), and sweeps
|
||||
(`POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}`, cancel).
|
||||
- **`?wait=<seconds>`** (max 900) on the job, deployment, run and sweep status endpoints: the request
|
||||
returns once the state settles, so agents make one call instead of polling. Things that wait for
|
||||
approval answer right away.
|
||||
- **Guardrails for API deployments and benchmarks** (Settings → API tokens): approval (default: ask
|
||||
me), agent deployments at once (1), one agent run or sweep at a time and no agent start while one
|
||||
runs, time limits per run and sweep (30 min / 3 h, enforced by the worker), max sweep variants (8),
|
||||
a runtime allowlist, an allowlist of extra argument flags per engine (values can't be paths or
|
||||
URLs; the error names the argument), host ports only within a range (none by default), and caps
|
||||
for memory and CPUs (agent deployments always get a memory limit).
|
||||
- **Protected deployments**: the Protect button on a deployment's page. Agents can't edit, stop,
|
||||
delete or benchmark it, nor start anything on the same GPUs that would crowd it out of VRAM
|
||||
(estimated).
|
||||
- **Approval** for agent starts, runs and sweeps on the deployment, run and sweep pages; "awaiting
|
||||
approval" in the lists.
|
||||
- Everything an agent creates shows **requested by <token>**, with a filter in the deployment
|
||||
and benchmark lists; an **activity log** per token (Settings → API tokens) lists every request,
|
||||
including refusals with their error code.
|
||||
- **Agent skill for tuning** ([docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md)): check the
|
||||
limits, pick a runtime, deploy (dry run first), wait until ready, benchmark, change one variable at a
|
||||
time (or sweep), compare, report a compact table, stop the deployment; no polling loops, stop when
|
||||
something needs approval, never work around a guardrail.
|
||||
|
||||
### Changed
|
||||
|
||||
- The download skill and messages use `?wait=` instead of "check again later".
|
||||
|
||||
## [0.12.0] - 2026-10-21
|
||||
|
||||
Intel GPU support (Arc A- and B-series, Arc Pro): telemetry during benchmarks, presets, render group
|
||||
handling and a VRAM estimate for NVIDIA and Intel alike. Host prerequisites are on the wiki page
|
||||
"Intel GPUs".
|
||||
|
||||
No changes to `compose.yaml` or `.env`.
|
||||
|
||||
### Added
|
||||
|
||||
- **GPU telemetry for Intel and AMD** in benchmark runs, A/B and sweeps, with the same fields as
|
||||
NVIDIA (VRAM in use, utilization, power, temperature):
|
||||
- power and temperature from the GPU's hwmon sensors (energy counter or power reading);
|
||||
- AMD: VRAM in use and busy percent from sysfs;
|
||||
- Intel: VRAM in use and utilization summed from every process's DRM fdinfo (the only place the
|
||||
`xe`/`i915` drivers report them), read by a probe container that runs only during the run: host
|
||||
PID namespace, `SYS_PTRACE` and `DAC_READ_SEARCH` only, no network, read-only, removed at the
|
||||
end. Utilization is the busiest engine class, like `intel_gpu_top`.
|
||||
- **Temperature** for every GPU (NVIDIA too), shown in the run's resources and, with GPU power, as
|
||||
sweep table columns.
|
||||
- **VRAM estimate** in the deployment form for NVIDIA and Intel/AMD: weights, KV cache and compute
|
||||
buffers for llama.cpp with all layers on the GPU, the reserved share for vLLM, against the GPUs'
|
||||
VRAM, with a hint when it doesn't fit.
|
||||
- **Render group handling**: the worker reads the group IDs of the host's `/dev/dri` nodes (render,
|
||||
video) and adds them to Intel/AMD runtime containers, so images that don't run as root can use the
|
||||
GPU.
|
||||
- The llama.cpp **Intel SYCL and Vulkan runtimes are added** the first time an Intel GPU is detected.
|
||||
|
||||
### Changed
|
||||
|
||||
- The llama.cpp Intel (SYCL) preset sets `ZES_ENABLE_SYSMAN=1`, so llama.cpp sees free VRAM (needed
|
||||
by `-ngl auto`). Preset descriptions mention the B-series.
|
||||
- GPU figures a source doesn't report are now shown as "—" instead of 0.
|
||||
|
||||
## [0.11.0] - 2026-10-20
|
||||
|
||||
Every benchmark run now records what it ran on: GPUs with their PCIe link and Resizable BAR, the
|
||||
runtime image and the engine version the server reports, model, quant and KV cache type, context and
|
||||
concurrency, plus a system summary and your own description. All of it is shown on the run page, in
|
||||
compare views and sweep tables, and goes to BetterBench and the launch80 preview.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new columns are added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Run metadata**, recorded when a run starts (single runs, A/B and sweep variants):
|
||||
- GPU count, name and VRAM; PCIe link, current and maximum (e.g. "Gen4 x8 of Gen5 x16"), read
|
||||
from sysfs at the card's upstream port (behind on-card switches like Intel's Arc B-series) or
|
||||
from `nvidia-smi`; peer-to-peer between GPUs (`nvidia-smi topo -p2p`, "n/a" with one GPU);
|
||||
Resizable BAR (on when a BAR covers the VRAM).
|
||||
- GPUs slow their link down when idle, so the current link is sampled during the run and the
|
||||
fastest one seen under load is recorded ("at idle" when it couldn't be sampled).
|
||||
- Runtime image, tag and registry digest, and the engine version the server reports once it's
|
||||
ready (llama.cpp `/props` build, vLLM `/version`, falling back to the startup log). Runtimes have
|
||||
an optional **engine name** for forks (e.g. `vllm-radiance`).
|
||||
- Model, quant and KV cache type (e.g. "Q4_K_M with q8_0 KV cache"), context length and
|
||||
concurrency (llama.cpp slots as reported by the server, vLLM max sequences).
|
||||
- **System summary** per run: CPU model, cores and threads, RAM, the disk holding the models
|
||||
folder, OS and kernel, GPU driver versions, VM or bare metal with GPU passthrough, Kaname version.
|
||||
Only these whitelisted facts; never the hostname, IP addresses, users or paths.
|
||||
- **Description** per run: set it when starting a run or edit it on the run page.
|
||||
- Everything goes to BetterBench as `--note`s (in `results.json` and its report) and into the
|
||||
launch80 dry-run preview as page sections (description, hardware and runtime, system), visible in
|
||||
the preview before anything is sent.
|
||||
- **Settings → Hardware**: what was detected, with manual values for what detection can't see (in a
|
||||
VM the PCIe link is the one the VM sees; new GPUs missing from the PCI ID list). New runs use them.
|
||||
- The run page shows the metadata; compare views get a "Hardware & runtime" section and a prefill
|
||||
row in the headline; sweep tables list the setup shared by all variants and show what differs as
|
||||
columns.
|
||||
- `scripts/intel-probe.sh`: read-only diagnostics for Intel GPU hosts (link, BARs, hwmon, DRM
|
||||
fdinfo, `/dev/dri` groups), for the upcoming Intel GPU support.
|
||||
|
||||
### Changed
|
||||
|
||||
- The image includes the PCI ID database (`pci.ids`) for GPU names.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A run or sweep with both "quick" and an explicit number of passes failed (BetterBench refuses
|
||||
`--quick` with `--passes`); the passes now win.
|
||||
- Agent skill (`docs/agent/SKILL.md`) works with how Hermes Agent runs commands: a `kaname` helper
|
||||
script (`docs/agent/kaname`) instead of a shell function that didn't survive between commands,
|
||||
`KANAME_URL`/`KANAME_TOKEN` declared in the frontmatter, and far less polling (none while a
|
||||
request waits for approval, one check around the ETA while downloading).
|
||||
|
||||
## [0.10.0] - 2026-10-20
|
||||
|
||||
An API for AI agents: a token-authenticated `/api/v1` lets a program look up models, request
|
||||
downloads and follow them, within guardrails you set and, by default, only after you approve each
|
||||
request.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. If Kaname is behind a forward-auth proxy, let `/api/v1/`
|
||||
through without forward auth (example in [docs/api.md](docs/api.md)). The new table is created on
|
||||
start.
|
||||
|
||||
### Added
|
||||
|
||||
- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), name,
|
||||
scopes `models:read` and `downloads:create`, last used, revoke. Sent as
|
||||
`Authorization: Bearer kn_…`; only `/api/v1` accepts them, and it accepts nothing else (the rest of
|
||||
Kaname stays OIDC-only). No token can delete models or files, change settings, or manage runtimes
|
||||
or tokens.
|
||||
- **`/api/v1`**, compact JSON with actionable error messages ([docs/api.md](docs/api.md)):
|
||||
- `GET /api/v1`: the token's name, scopes and the guardrails.
|
||||
- `GET /api/v1/hub/lookup?repo=`: commit SHA, quants and files with sizes (the Add model lookup).
|
||||
- `GET /api/v1/models`: the library with its search and filters (author, family, quant, tag,
|
||||
status, requested by) and the size on disk; `GET /api/v1/models/{id}`.
|
||||
- `POST /api/v1/downloads`: repo + pinned commit + a quant (weights plus the recommended companion
|
||||
files, as in Add model) or include globs, optional tags. Uses the same add-model and queue code
|
||||
as the UI. Repeating a request returns the existing model and job instead of queueing a
|
||||
duplicate; for a model already in the library it adds the missing files.
|
||||
- `GET /api/v1/jobs/{id}`: state, per-file progress, error; the `hf` log only with `?log=N`.
|
||||
- `GET /api/v1/disk`: free, used and reserved space on the models folder.
|
||||
- **Guardrails for API downloads** (Settings → API tokens): approval mode (default: requests wait
|
||||
as *pending approval* until you approve or reject them on the model or job page), max size per
|
||||
request (60 GB), free space that must remain after the download, counting what other open
|
||||
downloads still need (100 GB), API jobs at once (2), and an optional author allowlist. Rejecting a
|
||||
request removes a model it added, or restores the previous file selection.
|
||||
- Everything requested with a token shows **requested by <token name>** in the library, on the
|
||||
model and job pages, with a "Requested by" filter (and "awaiting approval" under Status).
|
||||
- **Agent skill** for Hermes Agent and similar ([docs/agent/SKILL.md](docs/agent/SKILL.md)): how to
|
||||
search, look up, request and monitor a download with `curl`, the guardrails, and to wait for
|
||||
approval instead of retrying.
|
||||
|
||||
### Changed
|
||||
|
||||
- Settings → API keys is now **Runtime API keys** (the keys deployments require), to keep it apart
|
||||
from API tokens.
|
||||
- Tests can now use the database: `npm test` runs with `--conditions=react-server`.
|
||||
|
||||
## [0.9.0] - 2026-10-13
|
||||
|
||||
Model testing, part three: benchmarks. Measure deployments with BetterBench (the benchmark behind
|
||||
launch80.com) and get a launch80-style report: single runs, paired A/B runs and sweeps over launch
|
||||
options, with CPU, RAM and GPU usage recorded during each run. Runs can be published to launch80
|
||||
with a preview and an explicit confirmation. Runtimes can use NVIDIA, Intel/AMD and ROCm GPUs, and
|
||||
downloads can be speed-limited.
|
||||
|
||||
No changes to `compose.yaml`. Optional new `.env` setting: `L80_TOKEN` (launch80 publishing). The
|
||||
new database tables are created on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Download speed limit** (Settings → Downloads), in MB/s, for all downloads together; changes
|
||||
apply to running downloads within seconds. `hf download` and hf_xet have no bandwidth option
|
||||
(checked with huggingface_hub 2.1.1 / hf_xet 1.6.0), so the worker pauses and resumes the hf
|
||||
process (SIGSTOP/SIGCONT) whenever it gets ahead of the limit: short bursts above it, the
|
||||
average holds (tested: 145 MB at a 2 MB/s limit took 67 s). Linux only; ignored on Windows.
|
||||
- **Paired A/B benchmarks** (`betterbench ab`): from a deployment's Benchmark card, pick another
|
||||
running deployment of the same model as B. The same prompts go to both, alternating, with greedy
|
||||
decoding, until the difference is known to ±the target precision (default 1 %, at most 200
|
||||
pairs). The report shows the verdict (faster/slower/no measurable difference), the confidence
|
||||
interval, both sides, what differs between them and the caveats, after launch80's rules.
|
||||
- **Sweeps**: vary one or two settings of a deployment (context size, KV cache type, quant file,
|
||||
threads, parallel slots, batch sizes, flash attention, prompt cache, GPU layers, CPU limit; vLLM:
|
||||
dtype, max sequences, KV cache, GPU memory share), up to 16 variants. Kaname deploys each variant
|
||||
in turn, benchmarks it, removes it again, and shows all of them side by side (chart and table,
|
||||
best values in bold), with a link to compare the runs in detail. Compare now takes up to 16 runs.
|
||||
- **Resource usage in every run**: CPU (cores, average and peak), RAM (average and peak against the
|
||||
container limit) from Docker, and per GPU VRAM, utilization and power from nvidia-smi, sampled
|
||||
every 2 s while the benchmark runs. Shown on the report, the A/B report and the sweep table.
|
||||
- **Benchmarks** (new main menu entry) with [BetterBench](https://github.com/GGZ14/BetterBench)
|
||||
(Apache-2.0, the benchmark behind launch80.com), built into the image (v0.6.1, archive pinned by
|
||||
checksum).
|
||||
- Start a run from a running deployment: quick (5 passes) or full (20), choose generation,
|
||||
prompt processing (input lengths up to the context size) and parallel requests, add a label.
|
||||
- Runs go one at a time; the run page shows the current step, the live BetterBench output, then
|
||||
headline numbers (weighted decode t/s, time to first token, prefill t/s, peak throughput) and
|
||||
the per-category, per-length and per-load tables, BetterBench's own HTML report (sandboxed)
|
||||
and its `results.json`.
|
||||
- Each run keeps a snapshot of the deployment's settings (and the CPU/GPU it ran on). Select runs
|
||||
to **compare** them: differing settings are highlighted, numbers show the change against the
|
||||
first run.
|
||||
- Cancel, run again with the same settings, rename, delete.
|
||||
- **Benchmark report page** after launch80's `bench.betterbench.v1`: headline tiles (combined
|
||||
decode, ITL 1% low or stream-update p99, TTFT p50), "Read these first" caveats with launch80's
|
||||
rules (quick run, under-sampled percentiles marked †, runs stopped at max_tokens, batched streams,
|
||||
failed requests, skipped prefill depths, prefix-cache hits), charts for decode by category, ITL
|
||||
range, prefill and parallel load, the full tables, the reasoning split and a Method section. Every
|
||||
figure comes from BetterBench's own report functions; existing runs are recomputed on start.
|
||||
- **Publish to launch80** (double opt-in, as the L80 docs describe): step 1 runs
|
||||
`L80 betterbench --results … --dry-run --payload-out` and shows exactly what would be sent
|
||||
(template, size, title, summary, notes; endpoint and host removed; the payload is downloadable);
|
||||
step 2 publishes that same file with `L80 publish` only after an explicit confirmation. Needs
|
||||
`L80_TOKEN` (launch80 Supporter) for the worker; the L80 CLI 0.4.0 ships in the image, pinned by
|
||||
checksum. The link, who confirmed it and when it expires (5 days) are kept per run.
|
||||
- `results.json` downloads no longer contain the endpoint URL or host name.
|
||||
- **GPUs.** Runtimes have a type: CPU, NVIDIA (CUDA), Intel/AMD via `/dev/dri` (Vulkan, SYCL,
|
||||
XPU) or AMD ROCm, with presets for the official CUDA, Vulkan, Intel and ROCm builds of
|
||||
llama.cpp and vLLM.
|
||||
- The worker lists NVIDIA GPUs (name, VRAM, driver) with a short-lived probe container and shows
|
||||
them under Settings → Runtimes; the first time one shows up, a "llama.cpp (CUDA)" runtime is
|
||||
added.
|
||||
- Deployments on GPU runtimes pick which GPUs to use and set GPU layers (`-ngl`), split mode,
|
||||
tensor split and MoE experts in RAM (llama.cpp) or tensor parallelism and GPU memory share
|
||||
(vLLM).
|
||||
- llama.cpp **prompt cache in RAM** (`--cache-ram`) as a deployment option, 1 GiB for new
|
||||
deployments.
|
||||
|
||||
### Fixed
|
||||
|
||||
- llama-server keeps up to 8 GiB of earlier prompts in RAM by default. Under a container memory
|
||||
limit it grew until the limit and then slowed to a crawl (the memory-mapped model got evicted).
|
||||
The memory estimate now counts the prompt cache and the KV cache (by context size and cache
|
||||
type).
|
||||
|
||||
## [0.8.0] - 2026-10-06
|
||||
|
||||
Model testing, part two: deployments. Serve a downloaded model with a llama.cpp or vLLM runtime
|
||||
container, tune its launch options, protect it with API keys and try it from Kaname.
|
||||
|
||||
No changes to `compose.yaml`; the new database tables are created on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Deployments** (new main menu entry): serve a downloaded model with a runtime container.
|
||||
- **New deployment:** pick a runtime (only pulled images), then a model it can serve (llama.cpp:
|
||||
downloaded GGUF files with the quant, optional mmproj for vision and MTP head / draft model for
|
||||
speculative decoding; vLLM: safetensors repos with a config.json), then launch options: context
|
||||
size, threads, parallel slots, KV cache types, flash attention, batch sizes (llama.cpp) or data
|
||||
type, max sequences, KV cache GiB (vLLM), CPU and memory limits (with an estimate), an optional
|
||||
published host port and extra arguments. A live preview shows the exact `docker run` command.
|
||||
- The worker starts the container on Kaname's Docker network with the models mounted read-only,
|
||||
waits for `/health`, follows the log, samples CPU/RAM every 5 s and refuses to start when the
|
||||
memory limits of running deployments wouldn't fit. Containers keep running across worker
|
||||
restarts; orphaned ones are removed.
|
||||
- Deployment page: state, load time, live CPU/RAM, endpoint URLs (Docker network and published
|
||||
port), live log, start/stop/edit/delete, and a "Try it" chat that streams the answer and shows
|
||||
time to first token and tokens/s.
|
||||
- llama.cpp's built-in **web UI** can be switched on or off per deployment (`--no-webui`); with a
|
||||
published host port the deployment page links to it.
|
||||
- A failed start names the cause from the log (e.g. vLLM's `ValueError` instead of the end of the
|
||||
traceback), followed by the last lines of output.
|
||||
- A deployment's vLLM data type replaces the runtime's `--dtype` instead of repeating the flag.
|
||||
- Models and runtimes used by a deployment can't be deleted until the deployment is.
|
||||
- **API keys** (Settings → API keys): add generated or own keys, show and copy them again later.
|
||||
A deployment with "Require an API key" accepts any of them (`LLAMA_API_KEY`, `VLLM_API_KEY` or
|
||||
`--api-key` for several vLLM keys); the values are masked in the shown command and in the log, and
|
||||
Kaname's own "Try it" chat sends one. Key changes apply when a deployment restarts.
|
||||
- **Deploy from the library:** a "Deploy" button in the library and on the model page opens a new
|
||||
deployment with the model and a fitting runtime preselected. The library and the model page link
|
||||
to the deployments that use a model.
|
||||
- Deployment form reorganized: launch options in groups (General, Context, Performance, KV cache,
|
||||
Resources, Extra arguments) with each field's flag next to its label, the command in its own step,
|
||||
and extra arguments as flag/value rows with "+ Add argument" (also in the runtime form).
|
||||
|
||||
### Fixed
|
||||
|
||||
- Dropdowns were unreadable in dark mode (white option list with light text): native controls now
|
||||
follow the theme.
|
||||
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
|
||||
written (Drizzle queries only run when awaited).
|
||||
|
||||
## [0.7.0] - 2026-10-06
|
||||
|
||||
First part of model testing: runtimes (llama.cpp, vLLM and your own images) and the Docker
|
||||
connection through a socket proxy. Starting containers with a model comes next.
|
||||
|
||||
**Upgrade note:** `compose.yaml` has a new `docker-proxy` service and `DOCKER_HOST` on the worker;
|
||||
copy them from `deploy/compose.yaml`.
|
||||
|
||||
### Added
|
||||
|
||||
- **Runtimes** (Settings → Runtimes): container images that serve models. Presets for the official
|
||||
llama.cpp CPU server (`ghcr.io/ggml-org/llama.cpp:server`) and vLLM CPU
|
||||
(`vllm/vllm-openai-cpu:v0.31.0`), plus your own images from any registry (e.g. patched forks) with
|
||||
an engine type (llama.cpp- or vLLM-compatible), environment, extra arguments, shared memory,
|
||||
device passthrough (only `/dev/dri…`, `/dev/kfd`) and an opt-in "NUMA tuning" switch (the
|
||||
`CAP_SYS_NICE` + `seccomp=unconfined` that vLLM recommends on CPU; off by default).
|
||||
- Pull and update runtime images from the UI, with progress and readable errors.
|
||||
- Docker host card: Docker version, CPU model and features (AVX2, AVX-512, AMX, …), memory, and the
|
||||
network and models source the worker detected from its own container.
|
||||
- `docker-proxy` service (`tecnativa/docker-socket-proxy:v0.5.0`) in both compose files; the worker
|
||||
reaches Docker only through it (`DOCKER_HOST`). New settings `DOCKER_HOST`,
|
||||
`KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` (see the wiki).
|
||||
|
||||
## [0.6.0] - 2026-10-06
|
||||
|
||||
Delete models (with their files), verify and deep verify, one-click repair, and update checks
|
||||
with a deliberate Update. Database migrations run automatically on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Delete** any model (also failed or incomplete ones), with confirmation. By default the worker
|
||||
deletes its files from disk: only the repo's files and hf's `.cache`; files you put in the folder
|
||||
yourself are kept, empty folders are removed. Unchecked, only the library entry goes and the folder
|
||||
shows up under "Found in the models folder".
|
||||
- **Verify** a model: every selected file is checked for existence, size and the version hf recorded;
|
||||
reports missing files, size mismatches and extra files in the folder. **Deep verify** hashes every
|
||||
file (SHA-256 for LFS files, git blob SHA-1 for small files) against the Hub, with progress.
|
||||
- **Repair** re-downloads only what's missing or broken. Broken files are deleted before `hf` runs,
|
||||
because `hf` skips a file whose metadata matches without checking its content or size.
|
||||
- **Update checks:** the Hub check (every `UPDATE_CHECK_INTERVAL_HOURS` and "Check now") also
|
||||
resolves the tracked revision. If there's a newer commit, the model shows "update available" (badge
|
||||
in the library and a Status filter value, banner on the model page) with the selected files that
|
||||
changed, were added or were removed. **Update** is a deliberate action: it pins the new commit (the
|
||||
old one stays in the revision history), downloads changed and new files, and deletes files that are
|
||||
no longer selected once the download succeeded.
|
||||
- Download card: **Resume** for interrupted or cancelled downloads, **Retry** for failed ones.
|
||||
- Job names in the job list and job page: Download, Download more, Import, Repair, Update, Verify,
|
||||
Deep verify, Delete.
|
||||
|
||||
## [0.5.0] - 2026-10-06
|
||||
|
||||
|
||||
+29
-6
@@ -1,4 +1,6 @@
|
||||
# One image for both services; the first argument picks the role: `web` (default) or `worker`.
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# One image for all services; the first argument picks the role: `web` (default), `worker` or
|
||||
# `sandbox` (runs the quality eval's coding answers, see compose.yaml).
|
||||
|
||||
FROM node:24-trixie-slim AS node
|
||||
|
||||
@@ -15,19 +17,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++, so no apt.
|
||||
FROM python:3.13-slim-trixie AS runtime
|
||||
COPY --from=node /usr/local/bin/node /usr/local/bin/node
|
||||
|
||||
# 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 endpoints. 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
|
||||
&& mkdir -p /data /models /sandbox \
|
||||
&& chown app:app /data /models /sandbox
|
||||
|
||||
ARG APP_VERSION=dev
|
||||
ENV PATH=/opt/hf/bin:$PATH \
|
||||
@@ -38,7 +59,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 ./
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
<img src="docs/banner.png" alt="Kaname: self-hosted model manager for Hugging Face" width="100%" />
|
||||
</p>
|
||||
|
||||
**Kaname** (要, "the pivot") is a self-hosted web app for downloading and managing local LLMs from
|
||||
Hugging Face. Look up a repo, pick the quant you want, and Kaname downloads exactly those files with
|
||||
the official `hf` CLI, pinned to a specific commit so every download is reproducible.
|
||||
**Kaname** (要, "the pivot") is a self-hosted web app for downloading local LLMs from Hugging Face
|
||||
and benchmarking the servers that run them. Look up a repo, pick the quant you want, and Kaname
|
||||
downloads exactly those files with the official `hf` CLI, pinned to a specific commit so every
|
||||
download is reproducible. Point it at your llama.cpp, vLLM, SGLang or Ollama servers and it measures
|
||||
their speed and answer quality with [BetterBench](https://github.com/GGZ14/BetterBench).
|
||||
|
||||
- **Pick files, not whole repos:** one-click quant selection for GGUF repos, or include/exclude globs.
|
||||
- **Pinned and reproducible:** every model is pinned to the exact commit SHA you reviewed.
|
||||
@@ -12,8 +14,11 @@ the official `hf` CLI, pinned to a specific commit so every download is reproduc
|
||||
the browser; cancel any time.
|
||||
- **Find things again:** search and filter by author, model family (e.g. Qwen, Gemma), quant, status
|
||||
and your own tags like `roleplay` or `security`.
|
||||
- **Homelab-friendly:** two containers, SQLite, OIDC single sign-on (e.g. Pocket ID), models on any
|
||||
folder or NAS share.
|
||||
- **Benchmark your endpoints:** speed runs, paired A/B tests and a quality eval against any
|
||||
OpenAI-compatible server, with the hardware you describe recorded next to every number; publish
|
||||
results to [launch80](https://launch80.com) if you like.
|
||||
- **Homelab-friendly:** a few containers, SQLite, OIDC single sign-on (e.g. Pocket ID), models on any
|
||||
folder or NAS share. Kaname needs no access to Docker.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -76,24 +81,44 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
"Found in the models folder"; **Import** matches them with the Hub repo and verifies the files
|
||||
instead of downloading them again. See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models).
|
||||
- **Deleted on the Hub:** if a repo (or its pinned commit) disappears from Hugging Face, the model
|
||||
is flagged and your local copy is kept.
|
||||
- **Verify / repair:** Verify checks every file's presence and size, Deep verify hashes them against
|
||||
the Hub; Repair downloads only what's missing or broken.
|
||||
- **Updates:** Kaname checks the Hub regularly and shows which of your files a newer commit changes;
|
||||
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
|
||||
model is flagged and your local copy is kept.
|
||||
- **Delete:** removes the model and, if you want, its files from disk.
|
||||
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
|
||||
- **Endpoints:** add the URL (and API key, if any) of an OpenAI-compatible server under Endpoints.
|
||||
**Test connection** shows the models it serves and, where it tells, the engine, version and context.
|
||||
Describe the machine behind it (GPUs, PCIe link, CPU, RAM, OS, engine build, quant, KV cache):
|
||||
Kaname can't see it, and these notes go into every run so results stay comparable. The API key
|
||||
stays on the server.
|
||||
- **Benchmarks:** from an endpoint's page, start a BetterBench **speed** run (generation, prompt
|
||||
processing, parallel requests), a paired **A/B** against another endpoint serving the same model,
|
||||
or the **quality** eval (tool calling, coding, long-context retrieval; deterministic). Runs go one
|
||||
at a time. Select runs on the Benchmarks page to compare them; publish a run to launch80 after a
|
||||
preview and an explicit confirmation (needs `L80_TOKEN`). No host names or addresses are published.
|
||||
|
||||
## How it works
|
||||
|
||||
Two containers from the same image share one SQLite database:
|
||||
Three containers from the same image; web and worker share one SQLite database:
|
||||
|
||||
- **web:** Next.js UI and API, OIDC login (Auth.js); live updates via Server-Sent Events.
|
||||
- **worker:** runs the download queue, spawns `hf download --revision <sha> --include <files>`, and
|
||||
measures progress from bytes on disk. Only one worker runs at a time.
|
||||
measures progress from bytes on disk; runs benchmarks against endpoints (BetterBench, the quality
|
||||
eval). Only one worker runs at a time.
|
||||
- **sandbox:** runs the quality eval's coding answers (Python written by the model under test) with
|
||||
no network, a read-only filesystem, no capabilities and small limits. It shares only an exchange
|
||||
folder with the worker. Optional: without it the eval skips the coding section.
|
||||
|
||||
Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image):
|
||||
|
||||
- Interrupted files are **not resumed**: a re-run skips finished files and restarts unfinished ones.
|
||||
Kaname cleans up the leftover partial files.
|
||||
- With Xet transfers the partial file only grows in large bursts, so Kaname disables Xet by default
|
||||
to show accurate progress.
|
||||
to show accurate progress. Files over 50 GB can only be downloaded with Xet, so a download that
|
||||
includes one uses Xet anyway; its progress then comes from `hf`'s own byte counter (the file on
|
||||
disk can sit still for minutes while Xet holds the data in memory).
|
||||
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
|
||||
metadata after each download.
|
||||
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
|
||||
@@ -117,7 +142,7 @@ the image locally.
|
||||
| `npm test` | unit tests |
|
||||
| `npm run typecheck`, `npm run lint` | checks |
|
||||
| `npm run db:generate` | new migration after changing `src/lib/db/schema.ts` |
|
||||
| `npm run build:worker` | bundle worker + migrate script into `dist/` (used by the image) |
|
||||
| `npm run build:worker` | bundle worker, sandbox and migrate script into `dist/` (used by the image) |
|
||||
|
||||
**Releases:** bump `version` in `package.json`, add a `## [X.Y.Z]` section to
|
||||
[`CHANGELOG.md`](CHANGELOG.md), commit and push a `vX.Y.Z` tag. Gitea Actions
|
||||
|
||||
+24
-1
@@ -16,13 +16,36 @@ services:
|
||||
worker:
|
||||
<<: *app
|
||||
command: worker
|
||||
volumes: [data:/data, models:/models]
|
||||
environment:
|
||||
DATABASE_URL: file:/data/app.db
|
||||
MODELS_DIR: /models
|
||||
HF_HOME: /data/hf-home
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes: [data:/data, models:/models, sandbox:/sandbox]
|
||||
|
||||
web:
|
||||
<<: *app
|
||||
ports: ["${WEB_PORT:-3000}:3000"]
|
||||
volumes: [data:/data]
|
||||
|
||||
# Runs the quality eval's coding answers (Python written by the model under test) with no
|
||||
# network, a read-only root, no capabilities and small limits. It shares only the exchange folder
|
||||
# with the worker. Optional: without it the quality eval skips the coding section.
|
||||
sandbox:
|
||||
image: kaname:local
|
||||
command: sandbox
|
||||
network_mode: none
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=64m,mode=1777"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 512m
|
||||
pids_limit: 64
|
||||
cpus: 1
|
||||
volumes: [sandbox:/sandbox]
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
data:
|
||||
models:
|
||||
sandbox:
|
||||
@@ -8,9 +8,12 @@ services:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
command: worker
|
||||
env_file: .env
|
||||
environment:
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
|
||||
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
|
||||
- sandbox:/sandbox # exchange folder with the code sandbox
|
||||
restart: unless-stopped
|
||||
|
||||
web:
|
||||
@@ -20,3 +23,23 @@ services:
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data
|
||||
restart: unless-stopped
|
||||
|
||||
# Runs the quality eval's coding answers (Python written by the model under test) with no
|
||||
# network, a read-only root, no capabilities and small limits. It shares only the exchange folder
|
||||
# with the worker. Optional: without it the quality eval skips the coding section.
|
||||
sandbox:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
command: sandbox
|
||||
network_mode: none
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=64m,mode=1777"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 512m
|
||||
pids_limit: 64
|
||||
cpus: 1
|
||||
volumes: [sandbox:/sandbox]
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
sandbox:
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Usage: docker run <image> [web|worker|<any command>] (default: web)
|
||||
# Usage: docker run <image> [web|worker|sandbox|<any command>] (default: web)
|
||||
set -e
|
||||
|
||||
role="${1:-web}"
|
||||
@@ -25,5 +25,10 @@ esac
|
||||
case "$role" in
|
||||
web) exec node_modules/.bin/next start ;;
|
||||
worker) exec node dist/worker.mjs ;;
|
||||
sandbox)
|
||||
echo sandbox > /tmp/kaname-role
|
||||
require_writable "${SANDBOX_DIR:-/sandbox}"
|
||||
exec node dist/sandbox.mjs
|
||||
;;
|
||||
*) exec "$@" ;;
|
||||
esac
|
||||
@@ -3,6 +3,8 @@
|
||||
case "$(cat /tmp/kaname-role 2>/dev/null)" in
|
||||
# The worker touches this file on every heartbeat (every 5s).
|
||||
worker) find /tmp/kaname-worker-alive -mmin -1 | grep -q . ;;
|
||||
# The sandbox touches this every 2s.
|
||||
sandbox) find "${SANDBOX_DIR:-/sandbox}/.alive" -mmin -1 | grep -q . ;;
|
||||
web) node -e 'fetch("http://127.0.0.1:" + (process.env.PORT || 3000) + "/login").then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))' ;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `jobs` ADD `result` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `update_diff` text;
|
||||
@@ -0,0 +1,26 @@
|
||||
CREATE TABLE `runtimes` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`engine` text NOT NULL,
|
||||
`image` text NOT NULL,
|
||||
`description` text,
|
||||
`env` text DEFAULT '{}' NOT NULL,
|
||||
`extra_args` text DEFAULT '[]' NOT NULL,
|
||||
`devices` text DEFAULT '[]' NOT NULL,
|
||||
`shm_size_mb` integer,
|
||||
`numa_tuning` integer DEFAULT false NOT NULL,
|
||||
`preset` text,
|
||||
`image_state` text DEFAULT 'unknown' NOT NULL,
|
||||
`image_id` text,
|
||||
`image_size` integer,
|
||||
`image_created` text,
|
||||
`pull_requested_at` integer,
|
||||
`pull_started_at` integer,
|
||||
`pull_progress` text,
|
||||
`pull_error` text,
|
||||
`image_checked_at` integer,
|
||||
`created_at` integer NOT NULL,
|
||||
`updated_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `worker_state` ADD `docker` text;
|
||||
@@ -0,0 +1,37 @@
|
||||
CREATE TABLE `deployment_logs` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`deployment_id` text NOT NULL,
|
||||
`ts` integer NOT NULL,
|
||||
`stream` text NOT NULL,
|
||||
`line` text NOT NULL,
|
||||
FOREIGN KEY (`deployment_id`) REFERENCES `deployments`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `deployment_logs_idx` ON `deployment_logs` (`deployment_id`,`id`);--> statement-breakpoint
|
||||
CREATE TABLE `deployments` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`runtime_id` text NOT NULL,
|
||||
`model_id` text NOT NULL,
|
||||
`options` text NOT NULL,
|
||||
`cpus` real,
|
||||
`memory_mb` integer,
|
||||
`host_port` integer,
|
||||
`desired_state` text DEFAULT 'stopped' NOT NULL,
|
||||
`state` text DEFAULT 'stopped' NOT NULL,
|
||||
`delete_requested_at` integer,
|
||||
`container_id` text,
|
||||
`container_name` text,
|
||||
`command` text,
|
||||
`image_id` text,
|
||||
`started_at` integer,
|
||||
`ready_at` integer,
|
||||
`stopped_at` integer,
|
||||
`exit_code` integer,
|
||||
`error` text,
|
||||
`stats` text,
|
||||
`created_at` integer NOT NULL,
|
||||
`updated_at` integer NOT NULL,
|
||||
FOREIGN KEY (`runtime_id`) REFERENCES `runtimes`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE `api_keys` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`key` text NOT NULL,
|
||||
`created_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_keys_key_unique` ON `api_keys` (`key`);
|
||||
@@ -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`);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `runtimes` ADD `accelerator` text DEFAULT 'cpu' NOT NULL;
|
||||
@@ -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`);
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE `agent_activity` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`token_id` text NOT NULL,
|
||||
`token_name` text NOT NULL,
|
||||
`action` text NOT NULL,
|
||||
`target_type` text,
|
||||
`target_id` text,
|
||||
`outcome` text NOT NULL,
|
||||
`code` text,
|
||||
`message` text,
|
||||
`created_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `agent_activity_token_idx` ON `agent_activity` (`token_id`,`created_at`);--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `run_time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `protected` integer DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `start_requested_at` integer;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `benchmark_runs` ADD `quality` text;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Approvals were for API requests, which are gone; anything still waiting is cancelled.
|
||||
UPDATE `jobs` SET `state` = 'cancelled', `finished_at` = unixepoch() * 1000 WHERE `state` = 'pending_approval';--> statement-breakpoint
|
||||
UPDATE `benchmark_runs` SET `state` = 'cancelled', `finished_at` = unixepoch() * 1000 WHERE `state` = 'pending_approval';--> statement-breakpoint
|
||||
DELETE FROM `settings` WHERE `key` IN ('agent.guardrails', 'agent.tuning', 'hardware.overrides', 'runtimes.presetsSeeded', 'runtimes.cudaPresetSeeded', 'runtimes.intelPresetSeeded');--> statement-breakpoint
|
||||
DROP TABLE `agent_activity`;--> statement-breakpoint
|
||||
DROP TABLE `api_keys`;--> statement-breakpoint
|
||||
DROP TABLE `api_tokens`;--> statement-breakpoint
|
||||
DROP TABLE `benchmark_sweeps`;--> statement-breakpoint
|
||||
DROP TABLE `deployment_logs`;--> statement-breakpoint
|
||||
DROP TABLE `deployments`;--> statement-breakpoint
|
||||
DROP TABLE `runtimes`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `deployment_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `deployment_b_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `resources`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `sweep_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `requested_by_token_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `requested_by`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `time_limit_s`;--> statement-breakpoint
|
||||
ALTER TABLE `jobs` DROP COLUMN `requested_by_token_id`;--> statement-breakpoint
|
||||
ALTER TABLE `jobs` DROP COLUMN `requested_by`;--> statement-breakpoint
|
||||
ALTER TABLE `models` DROP COLUMN `requested_by_token_id`;--> statement-breakpoint
|
||||
ALTER TABLE `models` DROP COLUMN `requested_by`;--> statement-breakpoint
|
||||
ALTER TABLE `worker_state` DROP COLUMN `docker`;
|
||||
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE `endpoints` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`base_url` text NOT NULL,
|
||||
`api_key` text,
|
||||
`model` text,
|
||||
`engine` text,
|
||||
`hardware` text DEFAULT '{}' NOT NULL,
|
||||
`probe` text,
|
||||
`created_at` integer NOT NULL,
|
||||
`updated_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `endpoints_name_uq` ON `endpoints` (`name`);--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `endpoint_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `endpoint_b_id` text;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `worker_state` ADD `last_scan_at` integer;--> statement-breakpoint
|
||||
ALTER TABLE `worker_state` ADD `last_scan_found` integer;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,111 @@
|
||||
"when": 1791233749207,
|
||||
"tag": "0008_local_folders",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "6",
|
||||
"when": 1791238659338,
|
||||
"tag": "0009_verify_update",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "6",
|
||||
"when": 1791242201063,
|
||||
"tag": "0010_runtimes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 11,
|
||||
"version": "6",
|
||||
"when": 1791278463453,
|
||||
"tag": "0011_deployments",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 12,
|
||||
"version": "6",
|
||||
"when": 1791281615301,
|
||||
"tag": "0012_api_keys",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 13,
|
||||
"version": "6",
|
||||
"when": 1791654372298,
|
||||
"tag": "0013_benchmarks",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 14,
|
||||
"version": "6",
|
||||
"when": 1791655909335,
|
||||
"tag": "0014_runtime_accelerator",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 15,
|
||||
"version": "6",
|
||||
"when": 1791657884019,
|
||||
"tag": "0015_benchmark_publications",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 16,
|
||||
"version": "6",
|
||||
"when": 1791658947930,
|
||||
"tag": "0016_ab_resources_sweeps",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 17,
|
||||
"version": "6",
|
||||
"when": 1792504668583,
|
||||
"tag": "0017_api_tokens",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 18,
|
||||
"version": "6",
|
||||
"when": 1792513935880,
|
||||
"tag": "0018_benchmark_metadata",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 19,
|
||||
"version": "6",
|
||||
"when": 1792587768766,
|
||||
"tag": "0019_agent_tuning",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 20,
|
||||
"version": "6",
|
||||
"when": 1792588720328,
|
||||
"tag": "0020_quality_eval",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 21,
|
||||
"version": "6",
|
||||
"when": 1793045191010,
|
||||
"tag": "0021_slim_down",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 22,
|
||||
"version": "6",
|
||||
"when": 1793045228739,
|
||||
"tag": "0022_endpoints",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 23,
|
||||
"version": "6",
|
||||
"when": 1793115558680,
|
||||
"tag": "0023_scan_schedule",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.15.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.15.1",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
"@libsql/client": "^0.18.0",
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.15.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
@@ -13,8 +13,8 @@
|
||||
"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\"",
|
||||
"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"
|
||||
"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 && esbuild src/sandbox/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/sandbox.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
|
||||
/**
|
||||
* Delete a model, whatever its state (failed, incomplete, ready, …). By default its files are
|
||||
* deleted from disk too (by the worker); unchecked, only the library entry goes.
|
||||
*/
|
||||
export function DeleteModelButton({
|
||||
id,
|
||||
repoId,
|
||||
localPath,
|
||||
mayHaveFiles,
|
||||
}: {
|
||||
id: string;
|
||||
repoId: string;
|
||||
localPath: string;
|
||||
/** False if nothing was ever downloaded, so there's nothing on disk to ask about. */
|
||||
mayHaveFiles: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [deleteFiles, setDeleteFiles] = useState(true);
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
async function remove() {
|
||||
setPending(true);
|
||||
const res = await fetch(`/api/models/${id}${mayHaveFiles && deleteFiles ? "?files=1" : ""}`, { method: "DELETE" });
|
||||
if (res.ok) {
|
||||
toast.success(res.status === 202 ? `Deleting ${repoId} and its files…` : `${repoId} removed from the library`);
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Delete failed (${res.status})`);
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {repoId}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{mayHaveFiles
|
||||
? "The model is removed from the library, including its tags and job history."
|
||||
: "Nothing was downloaded yet, so this only removes the library entry."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{mayHaveFiles && (
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-md bg-muted/50 px-3 py-2.5 text-sm">
|
||||
<Checkbox checked={deleteFiles} onCheckedChange={(v) => setDeleteFiles(v === true)} className="mt-0.5" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span>Also delete the files from disk</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Deletes the repo's files in <code className="font-mono">{localPath}</code>. Files you put there yourself are
|
||||
kept. Unchecked, the folder stays and shows up under “Found in the models folder”.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove} disabled={pending}>
|
||||
{mayHaveFiles && deleteFiles ? "Delete with files" : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { cancelJob, startDownload } from "@/components/job-actions";
|
||||
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
|
||||
import { JobProgress, JobStateBadge } from "@/components/job-progress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { VerifyResult } from "@/components/verify-result";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import type { ModelStatus } from "@/lib/db/schema";
|
||||
import { groupJobFiles } from "@/lib/file-groups";
|
||||
import { formatBytes, percent } from "@/lib/format";
|
||||
import { jobLabel } from "@/lib/job-labels";
|
||||
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
const VERIFY_KINDS = ["verify", "deep_verify"];
|
||||
|
||||
/** Sidebar card: current download state, actions and (while running) per-file progress. */
|
||||
/** Sidebar card: current job with progress, the last verify result, and the model's actions. */
|
||||
export function DownloadCard({
|
||||
modelId,
|
||||
status,
|
||||
@@ -27,11 +30,18 @@ export function DownloadCard({
|
||||
}) {
|
||||
const { snapshot } = useLive({ model: modelId });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const latest = snapshot?.jobs[0];
|
||||
const jobs = snapshot?.jobs ?? [];
|
||||
const latest = jobs[0];
|
||||
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
|
||||
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
|
||||
// The newest verify, unless a download ran after it (its result would be stale).
|
||||
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
|
||||
const verify = lastCheck && VERIFY_KINDS.includes(lastCheck.kind) && lastCheck.state === "completed" ? lastCheck : undefined;
|
||||
const verifyProblems = verify?.result
|
||||
? (verify.result.missing?.length ?? 0) + (verify.result.sizeMismatch?.length ?? 0) + (verify.result.hashMismatch?.length ?? 0)
|
||||
: 0;
|
||||
|
||||
async function run(fn: () => Promise<void>) {
|
||||
async function run(fn: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
@@ -40,24 +50,40 @@ export function DownloadCard({
|
||||
}
|
||||
}
|
||||
|
||||
const neverRan = jobs.length === 0;
|
||||
const downloadLabel = neverRan
|
||||
? "Download"
|
||||
: latest?.state === "interrupted" || latest?.state === "cancelled"
|
||||
? "Resume"
|
||||
: latest?.state === "failed" && latest.kind === "download"
|
||||
? "Retry"
|
||||
: "Download missing";
|
||||
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !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 download slot." : "Queued, but the worker is offline.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
else if (open) hint = "Runs in the background; you can close this page.";
|
||||
else if (status === "deleting") hint = "Deleting…";
|
||||
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
else if (status === "ready") hint = "All selected files are present.";
|
||||
else if (hubMissing) hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
|
||||
const showProgress =
|
||||
latest && latest.kind !== "delete" && !(latest.state === "completed" && (status === "ready" || VERIFY_KINDS.includes(latest.kind)));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
|
||||
<DownloadIcon className="size-4 text-muted-foreground" />
|
||||
Download
|
||||
{open ? jobLabel(open) : "Download"}
|
||||
</h3>
|
||||
{latest && <JobStateBadge job={latest} />}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
|
||||
{latest && !(latest.state === "completed" && status === "ready") && <JobProgress job={latest} compact />}
|
||||
{showProgress && <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">
|
||||
@@ -82,30 +108,58 @@ export function DownloadCard({
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{verify?.result && !open && (
|
||||
<div className="rounded-md bg-muted/50 px-2.5 py-2">
|
||||
<VerifyResult result={verify.result} deep={verify.kind === "deep_verify"} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{open ? (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={busy || open.cancelRequested}
|
||||
onClick={() => run(() => cancelJob(open.id))}
|
||||
>
|
||||
<Button variant="destructive" size="sm" disabled={busy || open.cancelRequested} onClick={() => run(() => cancelJob(open.id))}>
|
||||
{open.cancelRequested ? "Cancelling…" : "Cancel"}
|
||||
</Button>
|
||||
) : (
|
||||
status !== "ready" &&
|
||||
!hubMissing &&
|
||||
snapshot && (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
|
||||
{latest ? "Download again" : "Download"}
|
||||
</Button>
|
||||
)
|
||||
<>
|
||||
{needsRepair ? (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startRepair(modelId))}>
|
||||
<WrenchIcon />
|
||||
Repair
|
||||
</Button>
|
||||
) : (
|
||||
canDownload && (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
|
||||
{downloadLabel}
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
{canVerify && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, false))}
|
||||
title="Check that every selected file exists with the right size (seconds)"
|
||||
>
|
||||
<ShieldCheckIcon />
|
||||
Verify
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, true))}
|
||||
title="Hash every file and compare with the Hub (slow: reads every byte)"
|
||||
>
|
||||
Deep verify
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{latest && (
|
||||
<Link
|
||||
href={`/jobs/${latest.id}`}
|
||||
className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted"
|
||||
>
|
||||
{latest && latest.kind !== "delete" && (
|
||||
<Link href={`/jobs/${latest.id}`} className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted">
|
||||
View log
|
||||
</Link>
|
||||
)}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Re-check right now whether the repo and pinned commit are still on the Hub. */
|
||||
/** Check the Hub right now: repo and pinned commit still there, newer commit on the tracked revision. */
|
||||
export function HubCheckButton({ modelId, label = "Check now" }: { modelId: string; label?: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -18,7 +18,8 @@ export function HubCheckButton({ modelId, label = "Check now" }: { modelId: stri
|
||||
const res = await fetch(`/api/models/${modelId}/hub-check`, { method: "POST" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) toast.error(json.error?.message ?? `Check failed (${res.status})`);
|
||||
else if (json.state === "available") toast.success("Still available on Hugging Face");
|
||||
else if (json.state === "available" && json.update) toast.info("Update available");
|
||||
else if (json.state === "available") toast.success(json.warning ?? "Up to date");
|
||||
else if (json.state === "repo_missing") toast.warning("The repo is no longer on Hugging Face");
|
||||
else if (json.state === "commit_missing") toast.warning("The pinned commit is no longer on Hugging Face");
|
||||
else toast.error(`Could not check: ${json.error ?? "unknown error"}`);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LocalTime } from "@/components/local-time";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { jobLabel } from "@/lib/job-labels";
|
||||
|
||||
/** Job history of one model (live). */
|
||||
export function JobsTab({ modelId }: { modelId: string }) {
|
||||
@@ -35,8 +36,7 @@ export function JobsTab({ modelId }: { modelId: string }) {
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{j.kind}
|
||||
{j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""}
|
||||
{jobLabel(j)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<JobStateBadge job={j} />
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
LanguagesIcon,
|
||||
ListChecksIcon,
|
||||
MessagesSquareIcon,
|
||||
GaugeIcon,
|
||||
ScaleIcon,
|
||||
SparklesIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -17,14 +18,18 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { HubStateBadge } from "@/components/hub-state-badge";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { ModelStatusBadge } from "@/components/model-status-badge";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { headline, targetName } from "@/lib/benchmark-view";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
import { getModelByRepo, relatedModels } from "@/lib/library";
|
||||
import { fileRole } from "@/lib/file-roles";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
@@ -35,8 +40,9 @@ import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCard } from "./model-card";
|
||||
import { RemoveModelButton } from "./remove-model-button";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -95,12 +101,18 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const hubTags = model.hubTags ?? [];
|
||||
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
|
||||
|
||||
const [tags, related, card, worker] = await Promise.all([
|
||||
const [tags, related, card, worker, recentJobs, runs] = await Promise.all([
|
||||
modelTagList(model.id),
|
||||
relatedModels(model.id, baseModels),
|
||||
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
|
||||
getWorkerStatus(),
|
||||
listModelJobs(model.id, 1),
|
||||
listBenchmarks({ modelId: model.id }),
|
||||
]);
|
||||
const update =
|
||||
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
|
||||
? model.updateDiff
|
||||
: null;
|
||||
|
||||
const selected = files.filter((f) => f.selected);
|
||||
const others = files.filter((f) => !f.selected);
|
||||
@@ -130,8 +142,18 @@ 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} />
|
||||
{update && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
|
||||
update available
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{model.status === "pending" && <RemoveModelButton id={model.id} />}
|
||||
<DeleteModelButton
|
||||
id={model.id}
|
||||
repoId={model.repoId}
|
||||
localPath={model.localPath}
|
||||
mayHaveFiles={model.status !== "pending" || recentJobs.length > 0}
|
||||
/>
|
||||
<ExternalButton href={hub}>🤗 Hugging Face</ExternalButton>
|
||||
</div>
|
||||
</div>
|
||||
@@ -190,6 +212,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
|
||||
{update && (
|
||||
<UpdateBanner modelId={model.id} revision={model.trackedRevision} pinnedSha={model.pinnedSha} diff={update} hubUrl={hub} />
|
||||
)}
|
||||
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
|
||||
{/* Content card with the tabs as a segmented control in its header */}
|
||||
<Panel className="min-w-0 overflow-hidden">
|
||||
@@ -266,6 +292,30 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
|
||||
</SideCard>
|
||||
|
||||
{runs.length > 0 && (
|
||||
<SideCard title="Benchmarks" icon={GaugeIcon}>
|
||||
<div className="flex flex-col gap-1">
|
||||
{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-2 py-1.5 text-sm hover:bg-muted">
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
|
||||
</span>
|
||||
</span>
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
<Link href={`/benchmarks?model=${model.id}`} className="self-start px-2 text-xs text-muted-foreground hover:text-foreground">
|
||||
All runs of this model →
|
||||
</Link>
|
||||
</div>
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
<SideCard title="Local copy" icon={ListChecksIcon}>
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
|
||||
<dt className="text-muted-foreground">Selection</dt>
|
||||
@@ -305,9 +355,11 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
)}
|
||||
<dt className="text-muted-foreground">On the Hub</dt>
|
||||
<dd className="flex flex-col items-start gap-0.5">
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300")}>
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
|
||||
{model.hubState === "available"
|
||||
? "Available"
|
||||
? update
|
||||
? "Update available"
|
||||
: "Up to date"
|
||||
: model.hubState === "repo_missing"
|
||||
? "Repo deleted"
|
||||
: model.hubState === "commit_missing"
|
||||
@@ -316,9 +368,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</span>
|
||||
{model.lastCheckedAt && (
|
||||
<span className="text-xs text-muted-foreground" title={model.lastCheckError ?? undefined}>
|
||||
{model.lastCheckError ? "check failed" : "checked"} <LocalTime value={model.lastCheckedAt} />
|
||||
checked <LocalTime value={model.lastCheckedAt} />
|
||||
</span>
|
||||
)}
|
||||
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
|
||||
<HubCheckButton modelId={model.id} />
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Added</dt>
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** Removes a not-yet-downloaded model from the library (DB only, no files exist yet). */
|
||||
export function RemoveModelButton({ id }: { id: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
const res = await fetch(`/api/models/${id}`, { method: "DELETE" });
|
||||
if (res.ok) {
|
||||
toast.success("Removed from library");
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Remove failed (${res.status})`);
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="destructive" size="sm" />}>Remove</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove from library?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Nothing has been downloaded yet, so this only removes the entry.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove} disabled={busy}>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowUpCircleIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { startUpdate } from "@/components/job-actions";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
|
||||
function FileGroup({ title, files, tone }: { title: string; files: UpdateDiffFile[]; tone: string }) {
|
||||
if (files.length === 0) return null;
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className={`text-xs font-medium ${tone}`}>
|
||||
{title} ({files.length})
|
||||
</span>
|
||||
<ul className="flex flex-col gap-0.5 text-xs">
|
||||
{files.slice(0, 20).map((f) => (
|
||||
<li key={f.path} className="flex justify-between gap-3">
|
||||
<span className="font-mono break-all">{f.path}</span>
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">
|
||||
{f.oldSize != null && f.oldSize !== f.size ? `${formatBytes(f.oldSize)} → ` : ""}
|
||||
{formatBytes(f.size)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{files.length > 20 && <li className="text-muted-foreground">… {files.length - 20} more</li>}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Update available": what would change in the selection, and the deliberate Update action. */
|
||||
export function UpdateBanner({
|
||||
modelId,
|
||||
revision,
|
||||
pinnedSha,
|
||||
diff,
|
||||
hubUrl,
|
||||
}: {
|
||||
modelId: string;
|
||||
revision: string;
|
||||
pinnedSha: string;
|
||||
diff: UpdateDiff;
|
||||
hubUrl: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const changes = diff.changed.length + diff.added.length + diff.removed.length;
|
||||
const download = [...diff.changed, ...diff.added].reduce((s, f) => s + f.size, 0);
|
||||
|
||||
async function update() {
|
||||
setBusy(true);
|
||||
try {
|
||||
if (await startUpdate(modelId)) router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-xl border border-sky-500/30 bg-sky-500/10 px-4 py-3 text-sm">
|
||||
<div className="flex flex-wrap items-start gap-3">
|
||||
<ArrowUpCircleIcon className="mt-0.5 size-4 shrink-0 text-sky-600 dark:text-sky-400" />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<p className="font-medium text-sky-900 dark:text-sky-100">
|
||||
Update available: {revision} is at{" "}
|
||||
<a href={`${hubUrl}/commit/${diff.sha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline">
|
||||
{shortSha(diff.sha)}
|
||||
</a>
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
You have <span className="font-mono">{shortSha(pinnedSha)}</span>.{" "}
|
||||
{changes === 0
|
||||
? "None of your selected files changed; updating only moves the pin."
|
||||
: `${changes} of your selected files would change (${formatBytes(download)} to download).`}{" "}
|
||||
Checked <LocalTime value={diff.checkedAt} />.
|
||||
</p>
|
||||
</div>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button size="sm" disabled={busy} />}>Update</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Update to {shortSha(diff.sha)}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The model is pinned to the new commit (the old one stays in the history) and changed or new files are
|
||||
downloaded. Files that are no longer part of your selection are deleted after the download succeeded.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={update} disabled={busy}>
|
||||
Update
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
{changes > 0 && (
|
||||
<div className="grid gap-3 rounded-lg bg-background/60 px-3 py-2.5 md:grid-cols-3">
|
||||
<FileGroup title="Changed" files={diff.changed} tone="text-amber-700 dark:text-amber-300" />
|
||||
<FileGroup title="Added" files={diff.added} tone="text-emerald-700 dark:text-emerald-300" />
|
||||
<FileGroup title="Removed" files={diff.removed} tone="text-destructive" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { TriangleAlertIcon } from "lucide-react";
|
||||
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib/ab-report";
|
||||
import { CONFIG_ROWS, targetName } 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'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 ?? `${targetName(a)} vs ${targetName(b)}`}</h2>
|
||||
<p className="max-w-3xl text-sm leading-relaxed">{abSummaryText(ab, targetName(a), targetName(b))}</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={targetName(a)} value={d.mean_a} unit="t/s" />
|
||||
<Side label="B · decode, mean" name={targetName(b)} 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 · {targetName(a)}</th>
|
||||
<th className="px-3 py-2 font-medium">B · {targetName(b)}</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>
|
||||
|
||||
<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's own.
|
||||
</footer>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
"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, engineName, isEndpointSnapshot, modelName, targetName } 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 { QualityReport } from "./quality-report";
|
||||
import { BenchmarkReport } from "./benchmark-report";
|
||||
import { PublishCard } from "./publish-card";
|
||||
|
||||
function duration(a: string | null, b: string | null, now: number) {
|
||||
if (!a) return null;
|
||||
const s = Math.max(
|
||||
0,
|
||||
((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000,
|
||||
);
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
return h
|
||||
? `${h} h ${m} min`
|
||||
: m
|
||||
? `${m} min ${Math.round(s % 60)} s`
|
||||
: `${Math.round(s)} s`;
|
||||
}
|
||||
|
||||
export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
const router = useRouter();
|
||||
const [r, setR] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [label, setLabel] = useState(initial.label ?? "");
|
||||
const [description, setDescription] = useState(initial.description ?? "");
|
||||
const active = r.state === "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.endpointId) return;
|
||||
const res = await fetch("/api/benchmarks", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
endpointId: r.endpointId,
|
||||
endpointBId: r.kind === "ab" ? r.endpointBId : null,
|
||||
model: modelName(r.snapshot),
|
||||
kind: r.kind,
|
||||
label: r.label,
|
||||
description: r.description,
|
||||
...r.settings,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok)
|
||||
return toast.error(
|
||||
json.error?.message ?? `Could not start (${res.status})`,
|
||||
);
|
||||
router.push(`/benchmarks/${json.id}`);
|
||||
}
|
||||
|
||||
const s = r.snapshot;
|
||||
const sB = r.snapshotB;
|
||||
const sum = r.summary;
|
||||
// Runs from before 0.15 measured a deployment (gone now); newer ones an endpoint.
|
||||
const legacy = !isEndpointSnapshot(s);
|
||||
const endpointLink = (id: string | null, name: string) =>
|
||||
legacy ? name : id ? (
|
||||
<Link href={`/endpoints/${id}`} className="hover:underline">
|
||||
{name}
|
||||
</Link>
|
||||
) : (
|
||||
`${name} (deleted)`
|
||||
);
|
||||
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" && sB ? `${targetName(s)} vs ${targetName(sB)}` : targetName(s))}
|
||||
</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">
|
||||
{endpointLink(r.endpointId, targetName(s))} ·{" "}
|
||||
{r.modelId ? (
|
||||
<Link href={`/models/${r.modelId}`} className="hover:underline">
|
||||
{modelName(s)}
|
||||
</Link>
|
||||
) : (
|
||||
modelName(s)
|
||||
)}{" "}
|
||||
· {engineName(s)}
|
||||
{r.kind === "ab" && sB && (
|
||||
<>
|
||||
{" "}
|
||||
· B: {endpointLink(r.endpointBId, targetName(sB))} ({engineName(sB)})
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
|
||||
{r.kind === "ab"
|
||||
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
|
||||
: describeSettings(r.settings)}{" "}
|
||||
· created <LocalTime value={r.createdAt} />
|
||||
{took &&
|
||||
` · ${r.state === "running" ? "running for" : "took"} ${took}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{r.hasReport && (
|
||||
<a
|
||||
href={`/api/benchmarks/${r.id}/report`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={buttonVariants({ variant: "outline" })}
|
||||
>
|
||||
<ExternalLinkIcon />
|
||||
Full report
|
||||
</a>
|
||||
)}
|
||||
{r.state === "completed" && (
|
||||
<a
|
||||
href={`/api/benchmarks/${r.id}/results`}
|
||||
className={buttonVariants({ variant: "outline" })}
|
||||
>
|
||||
<DownloadIcon />
|
||||
{r.kind === "ab" ? "ab.json" : "results.json"}
|
||||
</a>
|
||||
)}
|
||||
{active ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={!!r.cancelRequestedAt}
|
||||
onClick={async () =>
|
||||
(await cancelBenchmark(r.id)) && router.refresh()
|
||||
}
|
||||
>
|
||||
<SquareIcon />
|
||||
Cancel
|
||||
</Button>
|
||||
) : (
|
||||
r.endpointId &&
|
||||
(r.kind !== "ab" || r.endpointBId) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={again}
|
||||
title="Queue a new run with the same settings against the same endpoint"
|
||||
>
|
||||
<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} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <BenchmarkReport run={r} />}
|
||||
<LiveLog
|
||||
url={`/api/benchmarks/${r.id}/logs`}
|
||||
title="BetterBench output"
|
||||
live={active}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<aside className="flex flex-col gap-4">
|
||||
{r.kind === "run" && r.state === "completed" && r.summary && (
|
||||
<PublishCard
|
||||
runId={r.id}
|
||||
defaultTitle={r.label ?? `${modelName(s).split("/").pop()} ${weightsLabel(s)}`}
|
||||
defaultSummary={reportSummary(r)}
|
||||
/>
|
||||
)}
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Label</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Input
|
||||
value={label}
|
||||
maxLength={120}
|
||||
placeholder="e.g. q8_0 KV cache"
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
onBlur={async () =>
|
||||
label !== (r.label ?? "") &&
|
||||
(await renameBenchmark(r.id, label || null)) &&
|
||||
setR({ ...r, label: label.trim() || null })
|
||||
}
|
||||
onKeyDown={(e) =>
|
||||
e.key === "Enter" && (e.target as HTMLInputElement).blur()
|
||||
}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Description</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-1.5">
|
||||
<textarea
|
||||
value={description}
|
||||
maxLength={4000}
|
||||
rows={3}
|
||||
placeholder="What this run tries out, e.g. q8_0 KV cache to fit 64k context"
|
||||
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
onBlur={async () =>
|
||||
description !== (r.description ?? "") &&
|
||||
(await describeBenchmark(r.id, description || null)) &&
|
||||
setR({ ...r, description: description.trim() || null })
|
||||
}
|
||||
/>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Passed to BetterBench (when set before the run starts) and to the launch80 preview, together with the system summary.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
|
||||
{r.kind !== "ab" && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{legacy ? "Settings measured" : "Setup"}</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>
|
||||
{!isEndpointSnapshot(s) && (
|
||||
<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>
|
||||
)}
|
||||
{isEndpointSnapshot(s) && s.hardware.description && (
|
||||
<p className="text-xs whitespace-pre-wrap text-muted-foreground">{s.hardware.description}</p>
|
||||
)}
|
||||
{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,382 @@
|
||||
"use client";
|
||||
|
||||
import { TriangleAlertIcon } from "lucide-react";
|
||||
import { BarChart } from "@/components/bar-chart";
|
||||
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, engineName, modelName } 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 ?? `${modelName(s)} ${weightsLabel(s) !== "safetensors" && !modelName(s).includes(weightsLabel(s)) ? 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">{engineName(s)}</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'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>
|
||||
)}
|
||||
|
||||
<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's own report
|
||||
functions; Kaname adds none.
|
||||
</footer>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getBenchmark } from "@/lib/benchmarks";
|
||||
import { targetName } from "@/lib/benchmark-view";
|
||||
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 ?? targetName(run.snapshot)} · 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't available in this installation, so runs can'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'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 “self-reported, not verified by launch80”.</li>
|
||||
<li>Removed after {RETENTION_DAYS} days. Counts against your token's 10 publishes per day.</li>
|
||||
</ul>
|
||||
{!status.tokenSet && (
|
||||
<p className="text-xs text-amber-700 dark:text-amber-300">No launch80 token: set L80_TOKEN (launch80 Supporter) for the worker to publish.</p>
|
||||
)}
|
||||
<label className="flex cursor-pointer items-start gap-2 text-xs">
|
||||
<Checkbox checked={ack} onCheckedChange={(v) => setAck(v === true)} className="mt-0.5" disabled={!status.tokenSet || !p?.hostRemoved} />
|
||||
<span>I want this run published as a public page on launch80.com, exactly as previewed.</span>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button onClick={() => publish(current.id)} disabled={!ack || busy || !status.tokenSet || !p?.hostRemoved}>
|
||||
<SendIcon />
|
||||
Publish
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => discard(current.id)} disabled={busy}>
|
||||
<Trash2Icon />
|
||||
Discard
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{current?.state === "publish" && (
|
||||
<p className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<LoaderCircleIcon className="size-3.5 animate-spin" />
|
||||
Publishing…
|
||||
</p>
|
||||
)}
|
||||
|
||||
{current?.state === "failed" && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<pre className="rounded-lg bg-destructive/10 px-3 py-2 font-sans text-xs break-words whitespace-pre-wrap text-destructive">{current.error}</pre>
|
||||
<Button variant="outline" size="sm" className="self-start" onClick={() => discard(current.id)}>
|
||||
Start over
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{published.length > 0 && !current && (
|
||||
<a href="https://launch80.com" target="_blank" rel="noreferrer" className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground">
|
||||
launch80.com <ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import type { QualityResult } from "@/lib/db/schema";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** A quality eval's result: the score, each section's pass rate and every item. */
|
||||
export function QualityReport({ quality, running }: { quality: QualityResult | null; running: boolean }) {
|
||||
if (!quality) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="text-sm text-muted-foreground">{running ? "The quality eval is running; results appear when it's done." : "No result."}</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quality</CardTitle>
|
||||
<CardDescription>
|
||||
Eval set {quality.evalSet}: greedy decoding (temperature {quality.config.temperature}, seed {quality.config.seed}), thinking{" "}
|
||||
{quality.config.thinking ? "on" : "off"}
|
||||
{quality.config.contextTokens ? `, context ${quality.config.contextTokens.toLocaleString("en-US")} tokens` : ""}. Scores are the share of items that pass;
|
||||
only results of the same eval set compare.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-4xl font-semibold tabular-nums">{quality.score != null ? `${quality.score}%` : "—"}</span>
|
||||
<span className="text-sm text-muted-foreground">overall (mean of the sections)</span>
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Section</TableHead>
|
||||
<TableHead className="text-right">Passed</TableHead>
|
||||
<TableHead className="text-right">Score</TableHead>
|
||||
<TableHead className="text-right">Time</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{quality.sections.map((s) => (
|
||||
<TableRow key={s.section}>
|
||||
<TableCell className="whitespace-normal">
|
||||
<div className="font-medium">{SECTION_LABEL[s.section]}</div>
|
||||
<div className="text-xs text-muted-foreground">{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{s.unsupported ? "—" : `${s.passed} / ${s.total}`}</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{s.score != null ? `${s.score}%` : "—"}</TableCell>
|
||||
<TableCell className="text-right text-muted-foreground tabular-nums">{s.seconds} s</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<ul className="flex flex-col gap-1 text-xs">
|
||||
{quality.items.map((i) => (
|
||||
<li key={`${i.section}-${i.id}`} className="flex items-start gap-1.5">
|
||||
{i.pass ? <CheckIcon className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> : <XIcon className="mt-0.5 size-3.5 shrink-0 text-destructive" />}
|
||||
<span className="font-mono">{i.id}</span>
|
||||
<span className={cn("min-w-0 break-words text-muted-foreground", !i.pass && "text-foreground")}>{i.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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 });
|
||||
@@ -0,0 +1,253 @@
|
||||
"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 { NativeSelect } from "@/components/ui/native-select";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { BenchmarkRow } from "@/lib/benchmarks";
|
||||
import { configChips, describeSettings, engineName, headline, modelName, targetName } 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,
|
||||
filter,
|
||||
}: {
|
||||
rows: ListRow[];
|
||||
compact?: boolean;
|
||||
/** The list's filter, kept when polling: an endpoint's or a model's runs. */
|
||||
filter?: { endpoint?: string; model?: string };
|
||||
}) {
|
||||
const [rows, setRows] = useState(initial);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
// "" = every endpoint, else an endpoint's name.
|
||||
const [by, setBy] = useState("");
|
||||
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
|
||||
const targets = [...new Set(rows.map((r) => targetName(r.snapshot)))].sort();
|
||||
const shown = rows.filter((r) => !by || targetName(r.snapshot) === by);
|
||||
|
||||
const query = new URLSearchParams(Object.entries(filter ?? {}).filter((e): e is [string, string] => !!e[1])).toString();
|
||||
|
||||
useEffect(() => {
|
||||
if (!busy || compact) return;
|
||||
const t = setInterval(async () => {
|
||||
const res = await fetch(`/api/benchmarks${query ? `?${query}` : ""}`, { cache: "no-store" }).catch(() => null);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}, 3_000);
|
||||
return () => clearInterval(t);
|
||||
}, [busy, compact, query]);
|
||||
|
||||
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 an{" "}
|
||||
<Link href="/endpoints" className="underline">
|
||||
endpoint
|
||||
</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 || targets.length > 1) && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{selected.length === 0
|
||||
? "Select completed runs to compare them."
|
||||
: `${selected.length} selected (up to ${MAX_COMPARE}).`}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
{targets.length > 1 && (
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
aria-label="Endpoint"
|
||||
>
|
||||
<option value="">All endpoints</option>
|
||||
{targets.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Link
|
||||
href={`/benchmarks/compare?ids=${selected.join(",")}`}
|
||||
className={cn(
|
||||
buttonVariants({ size: "sm" }),
|
||||
selected.length < 2 && "pointer-events-none opacity-50",
|
||||
)}
|
||||
aria-disabled={selected.length < 2}
|
||||
>
|
||||
<GitCompareIcon />
|
||||
Compare
|
||||
</Link>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Card className="py-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
{!compact && <TableHead className="w-8" />}
|
||||
<TableHead>Run</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Settings</TableHead>
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Weighted single-stream decode speed"
|
||||
>
|
||||
Decode t/s
|
||||
</TableHead>
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Median time to first token"
|
||||
>
|
||||
TTFT
|
||||
</TableHead>
|
||||
<TableHead
|
||||
className="hidden text-right md:table-cell"
|
||||
title="Prompt processing at the deepest measured input"
|
||||
>
|
||||
Prefill t/s
|
||||
</TableHead>
|
||||
<TableHead
|
||||
className="hidden text-right md:table-cell"
|
||||
title="Best aggregate throughput under parallel load"
|
||||
>
|
||||
Peak t/s
|
||||
</TableHead>
|
||||
<TableHead className="w-28">State</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{shown.map((r) => {
|
||||
const h = headline(r.summary);
|
||||
const s = r.snapshot;
|
||||
return (
|
||||
<TableRow
|
||||
key={r.id}
|
||||
data-state={selected.includes(r.id) ? "selected" : undefined}
|
||||
>
|
||||
{!compact && (
|
||||
<TableCell>
|
||||
<Checkbox
|
||||
checked={selected.includes(r.id)}
|
||||
disabled={r.state !== "completed"}
|
||||
onCheckedChange={() => toggle(r.id)}
|
||||
aria-label={`Select ${r.label ?? targetName(s)} for comparison`}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link
|
||||
href={`/benchmarks/${r.id}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{r.label ?? targetName(s)}
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{r.label && `${targetName(s)} · `}
|
||||
{modelName(s)} · <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">
|
||||
{engineName(s)}
|
||||
</span>
|
||||
{configChips(s).map((c) => (
|
||||
<span
|
||||
key={c}
|
||||
className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground"
|
||||
>
|
||||
{c}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[11px] text-muted-foreground">
|
||||
{describeSettings(r.settings)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">
|
||||
{r.kind === "eval" ? (
|
||||
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
|
||||
) : (
|
||||
fmt(h.decode)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="hidden text-right tabular-nums md:table-cell"
|
||||
title={
|
||||
h.prefill ? `at ${h.prefill.depth} tokens` : undefined
|
||||
}
|
||||
>
|
||||
{fmt(h.prefill?.tps, 0)}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="hidden text-right tabular-nums md:table-cell"
|
||||
title={h.peak ? `at ${h.peak.level} parallel` : undefined}
|
||||
>
|
||||
{fmt(h.peak?.tps)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { getBenchmarks } from "@/lib/benchmarks";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { CONFIG_ROWS, deltaPct, describeSettings, headline, targetName } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Compare benchmarks" };
|
||||
|
||||
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null, runIndex?: number) => number | null };
|
||||
|
||||
/** Differences smaller than this are shown without color: below what a single run can resolve. */
|
||||
const NOISE_PCT = 2;
|
||||
|
||||
function Delta({ v, base, higherIsBetter }: { v: number | null; base: number | null; higherIsBetter: boolean }) {
|
||||
const d = deltaPct(v, base);
|
||||
if (d == null) return null;
|
||||
const good = higherIsBetter ? d > 0 : d < 0;
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-1.5 text-[11px] tabular-nums",
|
||||
Math.abs(d) < NOISE_PCT ? "text-muted-foreground" : good ? "text-emerald-600 dark:text-emerald-400" : "text-destructive",
|
||||
)}
|
||||
>
|
||||
{d > 0 ? "+" : ""}
|
||||
{d.toFixed(1)}%
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function ComparePage({ searchParams }: PageProps<"/benchmarks/compare">) {
|
||||
const { ids } = await searchParams;
|
||||
const runs = await getBenchmarks(
|
||||
String(ids ?? "")
|
||||
.split(",")
|
||||
.filter(Boolean)
|
||||
.slice(0, 16),
|
||||
);
|
||||
if (runs.length < 2) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Pick at least two completed runs on the{" "}
|
||||
<Link href="/benchmarks" className="underline">
|
||||
Benchmarks
|
||||
</Link>{" "}
|
||||
page.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
const sums = runs.map((r) => r.summary);
|
||||
const depths = [...new Set(sums.flatMap((s) => s?.prefill.filter((p) => !p.skipped).map((p) => p.target_depth) ?? []))].sort((a, b) => a - b);
|
||||
const levels = [...new Set(sums.flatMap((s) => s?.concurrency.map((c) => c.level) ?? []))].sort((a, b) => a - b);
|
||||
const categories = [...new Set(sums.flatMap((s) => s?.single.map((c) => c.category) ?? []))];
|
||||
|
||||
const groups: { group: string; rows: Metric[] }[] = [
|
||||
{
|
||||
group: "Headline",
|
||||
rows: [
|
||||
{ label: "Prefill (deepest prompt)", unit: "t/s", higherIsBetter: true, digits: 0, get: (s) => headline(s).prefill?.tps ?? null },
|
||||
{ label: "Decode (weighted)", unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => headline(s).decode },
|
||||
{ label: "Time to first token", unit: "ms", higherIsBetter: false, digits: 0, get: (s) => headline(s).ttftMs },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Decode per category",
|
||||
rows: categories.map((c) => ({ label: c, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.single.find((x) => x.category === c)?.decode_med ?? null })),
|
||||
},
|
||||
{
|
||||
group: "Prompt processing",
|
||||
rows: depths.map((d) => ({
|
||||
label: `${d.toLocaleString()} tokens`,
|
||||
unit: "t/s",
|
||||
higherIsBetter: true,
|
||||
digits: 0,
|
||||
get: (s) => s?.prefill.find((p) => p.target_depth === d && !p.skipped)?.pp_med ?? null,
|
||||
})),
|
||||
},
|
||||
{
|
||||
group: "Parallel requests (total)",
|
||||
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
|
||||
},
|
||||
];
|
||||
// Quality evals: the score and each section's pass rate (only when some of the runs are evals).
|
||||
const quality = runs.map((r) => r.quality);
|
||||
if (quality.some(Boolean)) {
|
||||
const sections = [...new Set(quality.flatMap((q) => q?.sections.map((s) => s.section) ?? []))];
|
||||
groups.push({
|
||||
group: `Quality (${[...new Set(quality.filter(Boolean).map((q) => q!.evalSet))].join(", ")})`,
|
||||
rows: [
|
||||
{ label: "Score", unit: "%", higherIsBetter: true, digits: 1, get: (_s, i) => quality[i!]?.score ?? null },
|
||||
...sections.map((sec) => ({
|
||||
label: SECTION_LABEL[sec],
|
||||
unit: "%",
|
||||
higherIsBetter: true,
|
||||
digits: 1,
|
||||
get: (_s: BenchmarkSummary | null, i?: number) => quality[i!]?.sections.find((x) => x.section === sec)?.score ?? null,
|
||||
})),
|
||||
],
|
||||
});
|
||||
}
|
||||
const metrics = groups.filter((g) => g.rows.length > 0);
|
||||
|
||||
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
|
||||
const metaByRun = runs.map((r) => (r.meta ? metaRows(r.meta) : null));
|
||||
const metaKeys = [...new Map(metaByRun.flatMap((rows) => rows ?? []).map((x) => [x.key, x.label])).entries()];
|
||||
const metaTable = metaKeys.map(([key, label]) => ({ key, label, values: metaByRun.map((rows) => (rows ? (rows.find((x) => x.key === key)?.value ?? null) : null)) }));
|
||||
const configRows = CONFIG_ROWS.map((row) => ({ row, values: runs.map((r) => row.value(r.snapshot)) })).filter((x) => x.values.some((v) => v != null));
|
||||
const corpora = new Set(sums.map((s) => s?.corpusVersion).filter(Boolean));
|
||||
const anyQuick = runs.some((r) => r.summary?.quick);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">Compare benchmarks</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Differences are against the first run. Separate runs aren'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'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 ?? targetName(r.snapshot)}
|
||||
</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 & runtime
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{metaTable.map(({ key, label, values }) => {
|
||||
const differs = new Set(values.map((v) => v ?? "")).size > 1;
|
||||
return (
|
||||
<TableRow key={`meta-${key}`} className={cn(differs && "bg-amber-500/5")}>
|
||||
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{label}</TableCell>
|
||||
{values.map((v, i) => (
|
||||
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
|
||||
{v ?? <span className="text-muted-foreground">not recorded</span>}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
<TableRow className="bg-muted/40 hover:bg-muted/40">
|
||||
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||
Settings
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{configRows.map(({ row, values }) => {
|
||||
const differs = new Set(values.map((v) => v ?? "")).size > 1;
|
||||
return (
|
||||
<TableRow key={row.key} className={cn(differs && "bg-amber-500/5")}>
|
||||
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{row.label}</TableCell>
|
||||
{values.map((v, i) => (
|
||||
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
|
||||
{v ?? <span className="text-muted-foreground">default</span>}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
{metrics.map((g) => (
|
||||
<MetricGroup key={g.group} group={g.group} rows={g.rows} sums={sums} cols={runs.length} />
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[]; sums: (BenchmarkSummary | null)[]; cols: number }) {
|
||||
return (
|
||||
<>
|
||||
<TableRow className="bg-muted/40 hover:bg-muted/40">
|
||||
<TableCell colSpan={cols + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||
{group}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{rows.map((m) => {
|
||||
const vals = sums.map((s, i) => m.get(s, i));
|
||||
const present = vals.filter((v): v is number => v != null);
|
||||
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
|
||||
return (
|
||||
<TableRow key={m.label}>
|
||||
<TableCell className="text-xs">{m.label}</TableCell>
|
||||
{vals.map((v, i) => (
|
||||
<TableCell key={i} className="tabular-nums whitespace-nowrap">
|
||||
{v == null ? (
|
||||
<span className="text-muted-foreground">–</span>
|
||||
) : (
|
||||
<>
|
||||
<span className={cn(v === best && "font-semibold")}>
|
||||
{v.toFixed(m.digits)} <span className="text-[11px] text-muted-foreground">{m.unit}</span>
|
||||
</span>
|
||||
{i > 0 && <Delta v={v} base={vals[0]} higherIsBetter={m.higherIsBetter} />}
|
||||
</>
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { getModel } from "@/lib/library";
|
||||
import { BenchmarkList } from "./benchmark-list";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Benchmarks" };
|
||||
|
||||
export default async function BenchmarksPage({ searchParams }: PageProps<"/benchmarks">) {
|
||||
const modelId = (await searchParams).model;
|
||||
const model = typeof modelId === "string" ? await getModel(modelId) : null;
|
||||
const rows = await listBenchmarks({ modelId: model?.model.id });
|
||||
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">
|
||||
{model ? (
|
||||
<>
|
||||
Runs of{" "}
|
||||
<Link href={`/${model.model.repoId}`} className="underline">
|
||||
{model.model.repoId}
|
||||
</Link>
|
||||
.{" "}
|
||||
<Link href="/benchmarks" className="underline">
|
||||
Show all
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Speed (BetterBench), A/B and quality runs against your{" "}
|
||||
<Link href="/endpoints" className="underline">
|
||||
endpoints
|
||||
</Link>
|
||||
. Start one from an endpoint; select runs to compare their settings and numbers.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} filter={{ model: model?.model.id }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
"use client";
|
||||
|
||||
import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Loader2Icon } 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, 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 { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
|
||||
{ id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
|
||||
{ id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
|
||||
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
|
||||
];
|
||||
|
||||
type Mode = "run" | "ab" | "quality";
|
||||
type Peer = { id: string; name: string; model: string | null; models: string[] };
|
||||
|
||||
/** Benchmark an endpoint: a BetterBench run, a paired A/B against another endpoint, or the quality eval. */
|
||||
export function BenchmarkStart({ endpoint, peers }: { endpoint: { id: string; name: string; model: string | null; models: string[] }; peers: Peer[] }) {
|
||||
const router = useRouter();
|
||||
const [tab, setTab] = useState<Mode>("run");
|
||||
const [model, setModel] = useState(endpoint.model ?? "");
|
||||
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 [peerId, setPeerId] = useState("");
|
||||
const [mde, setMde] = useState("1");
|
||||
const [maxPairs, setMaxPairs] = useState("200");
|
||||
const [sections, setSections] = useState<QualitySection[]>([...QUALITY_SECTIONS]);
|
||||
|
||||
// The model a run requests: the one picked here, the endpoint's, or the only one it serves.
|
||||
const runModel = model || (endpoint.models.length === 1 ? endpoint.models[0] : "");
|
||||
const peer = peers.find((p) => p.id === peerId);
|
||||
const peerServes = !peer || !runModel || peer.models.length === 0 || peer.models.includes(runModel);
|
||||
|
||||
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({ endpointId: endpoint.id, model: runModel || null, 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 TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
|
||||
{ id: "run", label: "Speed", icon: GaugeIcon },
|
||||
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
|
||||
{ id: "quality", label: "Quality", icon: BadgeCheckIcon },
|
||||
];
|
||||
|
||||
const labelInputs = (
|
||||
<>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
|
||||
{tab !== "quality" && (
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="What this run tries out (optional; published with it, default: the endpoint's notes)" />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
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="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="inline-flex 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>
|
||||
{endpoint.models.length > 1 && (
|
||||
<NativeSelect value={model} onChange={(e) => setModel(e.target.value)} className="h-8 max-w-72 text-xs" aria-label="Model">
|
||||
<option value="">Choose a model…</option>
|
||||
{endpoint.models.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
</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>
|
||||
{labelInputs}
|
||||
<Button
|
||||
onClick={() => start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })}
|
||||
disabled={busy || phases.length === 0}
|
||||
>
|
||||
{busy ? <Loader2Icon className="animate-spin" /> : <GaugeIcon />}
|
||||
Run benchmark
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">Kaname checks the server first. Keep other load off it while the run lasts; on a CPU a full run can take hours.</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "ab" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Paired A/B: the same prompts go to this endpoint (A) and another one serving the same model (B), alternating, until the difference is known to ±the target.
|
||||
</p>
|
||||
{peers.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">Add a second endpoint serving the same model (e.g. with another KV cache type or engine build) to compare.</p>
|
||||
) : (
|
||||
<>
|
||||
<NativeSelect value={peerId} onChange={(e) => setPeerId(e.target.value)} aria-label="Endpoint B">
|
||||
<option value="">Choose B…</option>
|
||||
{peers.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
{runModel && p.models.length > 0 && !p.models.includes(runModel) ? " (doesn't serve this model)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
{!peerServes && <p className="text-xs text-amber-700 dark:text-amber-300">{peer?.name} doesn't list {runModel}. Both sides get the same model name.</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>
|
||||
{labelInputs}
|
||||
<Button onClick={() => start({ endpointBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })} disabled={busy || !peer || !peerServes}>
|
||||
{busy ? <Loader2Icon className="animate-spin" /> : <GitCompareArrowsIcon />}
|
||||
Start A/B
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "quality" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality, next to
|
||||
the speed numbers.
|
||||
</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{QUALITY_SECTIONS.map((s) => (
|
||||
<label key={s} className="flex cursor-pointer items-start gap-2">
|
||||
<Checkbox checked={sections.includes(s)} onCheckedChange={(v) => setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
|
||||
<span className="flex flex-col">
|
||||
<span>{SECTION_LABEL[s]}</span>
|
||||
<span className="text-xs text-muted-foreground">{SECTION_HINT[s]}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{labelInputs}
|
||||
<Button onClick={() => start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={busy || sections.length === 0}>
|
||||
{busy ? <Loader2Icon className="animate-spin" /> : <BadgeCheckIcon />}
|
||||
Run quality eval
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getEndpoint } from "@/lib/endpoints";
|
||||
import { EndpointForm } from "../../endpoint-form";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Edit endpoint" };
|
||||
|
||||
export default async function EditEndpointPage({ params }: PageProps<"/endpoints/[id]/edit">) {
|
||||
const endpoint = await getEndpoint((await params).id);
|
||||
if (!endpoint) notFound();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">Edit {endpoint.name}</h1>
|
||||
<EndpointForm initial={endpoint} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2Icon, PencilIcon, PlugZapIcon, Trash2Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import type { EndpointView } from "@/lib/endpoints";
|
||||
import { ProbeResult } from "../endpoint-form";
|
||||
import { EndpointStatus } from "../endpoint-status";
|
||||
|
||||
/** Name, URL, connection test, edit and delete. */
|
||||
export function EndpointHeader({ endpoint, runCount }: { endpoint: EndpointView; runCount: number }) {
|
||||
const router = useRouter();
|
||||
const [probe, setProbe] = useState(endpoint.probe);
|
||||
const [testing, setTesting] = useState(false);
|
||||
|
||||
async function test() {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/endpoints/${endpoint.id}/test`, { method: "POST" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
|
||||
setProbe(json);
|
||||
router.refresh();
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const res = await fetch(`/api/endpoints/${endpoint.id}`, { method: "DELETE" });
|
||||
if (!res.ok) {
|
||||
const json = await res.json().catch(() => ({}));
|
||||
return toast.error(json.error?.message ?? `Could not delete (${res.status})`);
|
||||
}
|
||||
router.push("/endpoints");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">{endpoint.name}</h1>
|
||||
<p className="text-sm break-all text-muted-foreground">
|
||||
{endpoint.baseUrl}
|
||||
{endpoint.hasApiKey ? " · API key set" : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EndpointStatus probe={probe} />
|
||||
<Button variant="outline" onClick={test} disabled={testing}>
|
||||
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
|
||||
Test connection
|
||||
</Button>
|
||||
<Link href={`/endpoints/${endpoint.id}/edit`} className={buttonVariants({ variant: "outline" })}>
|
||||
<PencilIcon />
|
||||
Edit
|
||||
</Link>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {endpoint.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The endpoint and its stored API key are removed.{runCount > 0 ? ` Its ${runCount} run${runCount === 1 ? "" : "s"} stay, with what they recorded.` : ""}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
{probe && <ProbeResult probe={probe} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { RunMetaCard } from "@/components/run-meta";
|
||||
import { endpointRunMeta, endpointSystem } from "@/lib/benchmark-meta";
|
||||
import { kanameVersion } from "@/lib/benchmark-snapshot";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { getEndpoint, listEndpoints } from "@/lib/endpoints";
|
||||
import { BenchmarkList } from "../../benchmarks/benchmark-list";
|
||||
import { BenchmarkStart } from "./benchmark-start";
|
||||
import { EndpointHeader } from "./endpoint-header";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata({ params }: PageProps<"/endpoints/[id]">): Promise<Metadata> {
|
||||
const e = await getEndpoint((await params).id);
|
||||
return { title: e ? `${e.name} · Endpoint` : "Endpoint" };
|
||||
}
|
||||
|
||||
export default async function EndpointPage({ params }: PageProps<"/endpoints/[id]">) {
|
||||
const { id } = await params;
|
||||
const endpoint = await getEndpoint(id);
|
||||
if (!endpoint) notFound();
|
||||
const [runs, all] = await Promise.all([listBenchmarks({ endpointId: id }), listEndpoints()]);
|
||||
const model = endpoint.model ?? (endpoint.probe?.models.length === 1 ? endpoint.probe.models[0] : null);
|
||||
// What a run would record now (the worker asks the server again when it starts).
|
||||
const preview = endpointRunMeta({
|
||||
type: "endpoint",
|
||||
endpointName: endpoint.name,
|
||||
model: model ?? "(model)",
|
||||
engine: endpoint.engine ?? endpoint.probe?.engine ?? null,
|
||||
engineVersion: endpoint.probe?.engineVersion ?? null,
|
||||
contextSize: endpoint.probe?.contextSize ?? null,
|
||||
slots: endpoint.probe?.slots ?? null,
|
||||
hardware: endpoint.hardware,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<EndpointHeader endpoint={endpoint} runCount={runs.length} />
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<BenchmarkStart
|
||||
endpoint={{ id: endpoint.id, name: endpoint.name, model, models: endpoint.probe?.models ?? [] }}
|
||||
peers={all.filter((e) => e.id !== id).map((e) => ({ id: e.id, name: e.name, models: e.probe?.models ?? [], model: e.model }))}
|
||||
/>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(runs))} filter={{ endpoint: id }} />
|
||||
</div>
|
||||
<aside className="flex flex-col gap-4">
|
||||
<RunMetaCard meta={preview} system={endpointSystem(endpoint.hardware, kanameVersion())} />
|
||||
{endpoint.hardware.description && (
|
||||
<p className="rounded-xl bg-card px-4 py-3 text-xs whitespace-pre-wrap text-muted-foreground ring-1 ring-foreground/10">{endpoint.hardware.description}</p>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
"use client";
|
||||
|
||||
import { CheckCircle2Icon, Loader2Icon, PlugZapIcon, SaveIcon, XCircleIcon } 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 { NativeSelect } from "@/components/ui/native-select";
|
||||
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
|
||||
import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema";
|
||||
import type { EndpointView } from "@/lib/endpoints";
|
||||
|
||||
type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string };
|
||||
|
||||
const GROUPS: { title: string; hint: string; fields: Field[] }[] = [
|
||||
{
|
||||
title: "GPU",
|
||||
hint: "Leave empty for a CPU-only server.",
|
||||
fields: [
|
||||
{ key: "gpuName", label: "GPU", placeholder: "NVIDIA GeForce RTX 4090" },
|
||||
{ key: "gpuCount", label: "Count", placeholder: "1", kind: "int" },
|
||||
{ key: "vramGb", label: "VRAM per GPU (GB)", placeholder: "24", kind: "number" },
|
||||
{ key: "pcie", label: "PCIe link", placeholder: "Gen4 x16" },
|
||||
{ key: "gpuDriver", label: "Driver", placeholder: "nvidia 580.82" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Machine",
|
||||
hint: "Only facts like these are published, never host names or addresses.",
|
||||
fields: [
|
||||
{ key: "cpu", label: "CPU", placeholder: "AMD EPYC 7282" },
|
||||
{ key: "memoryGb", label: "RAM (GB)", placeholder: "128", kind: "number" },
|
||||
{ key: "os", label: "OS", placeholder: "Debian 13" },
|
||||
{ key: "virtualization", label: "Virtualization", placeholder: "Proxmox VM with GPU passthrough, or bare metal" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Server",
|
||||
hint: "What the server runs. Empty fields are taken from what it reports where it can.",
|
||||
fields: [
|
||||
{ key: "engineName", label: "Engine name", placeholder: "ik_llama.cpp (default: detected)" },
|
||||
{ key: "engineVersion", label: "Engine version", placeholder: "default: detected" },
|
||||
{ key: "image", label: "Container image", placeholder: "ghcr.io/ggml-org/llama.cpp:server-cuda" },
|
||||
{ key: "quant", label: "Quant", placeholder: "Q4_K_M (default: from the model name)" },
|
||||
{ key: "kvCache", label: "KV cache type", placeholder: "q8_0" },
|
||||
{ key: "contextSize", label: "Context (tokens)", placeholder: "default: reported", kind: "int" },
|
||||
{ key: "concurrency", label: "Parallel slots", placeholder: "4", kind: "int" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const toText = (v: unknown) => (v == null ? "" : String(v));
|
||||
|
||||
/** Create or edit an endpoint. The API key is never sent to the browser: on edit it can be kept, replaced or removed. */
|
||||
export function EndpointForm({ initial }: { initial?: EndpointView }) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [baseUrl, setBaseUrl] = useState(initial?.baseUrl ?? "");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [removeKey, setRemoveKey] = useState(false);
|
||||
const [model, setModel] = useState(initial?.model ?? "");
|
||||
const [engine, setEngine] = useState<string>(initial?.engine ?? "");
|
||||
const [hw, setHw] = useState<Record<string, string>>(() =>
|
||||
Object.fromEntries(Object.entries(initial?.hardware ?? {}).map(([k, v]) => [k, typeof v === "boolean" ? (v ? "on" : "off") : toText(v)])),
|
||||
);
|
||||
const [probe, setProbe] = useState<EndpointProbe | null>(initial?.probe ?? null);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const fields = GROUPS.flatMap((g) => g.fields);
|
||||
function body() {
|
||||
const hardware: Record<string, unknown> = {};
|
||||
for (const f of fields) {
|
||||
const v = (hw[f.key] ?? "").trim();
|
||||
if (!v) continue;
|
||||
hardware[f.key] = f.kind ? Number(v.replace(",", ".")) : v;
|
||||
}
|
||||
if (hw.p2p) hardware.p2p = hw.p2p;
|
||||
if (hw.rebar) hardware.rebar = hw.rebar === "on";
|
||||
if (hw.description?.trim()) hardware.description = hw.description.trim();
|
||||
return {
|
||||
name,
|
||||
baseUrl,
|
||||
// Left out: keep the stored key. "": remove it.
|
||||
...(apiKey.trim() ? { apiKey: apiKey.trim() } : removeKey || !initial ? { apiKey: "" } : {}),
|
||||
model: model.trim() || null,
|
||||
engine: engine || null,
|
||||
hardware,
|
||||
};
|
||||
}
|
||||
|
||||
async function test() {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await fetch(initial ? `/api/endpoints/${initial.id}/test` : "/api/endpoints/test", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body()),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
|
||||
setProbe(json);
|
||||
if (json.ok && !model && json.models.length === 1) setModel(json.models[0]);
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch(initial ? `/api/endpoints/${initial.id}` : "/api/endpoints", {
|
||||
method: initial ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body()),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
|
||||
router.push(`/endpoints/${json.id}`);
|
||||
router.refresh();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const set = (key: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setHw((cur) => ({ ...cur, [key]: e.target.value }));
|
||||
const models = probe?.ok ? probe.models : [];
|
||||
|
||||
return (
|
||||
<form onSubmit={save} className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Connection</CardTitle>
|
||||
<CardDescription>Any OpenAI-compatible server: llama.cpp, vLLM, SGLang, Ollama, … Kaname talks to it from its own server.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">Name</span>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="4090 llama.cpp" required />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">URL</span>
|
||||
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="http://192.168.1.20:8080" required />
|
||||
<span className="text-xs text-muted-foreground">The server's root; /v1 is added by Kaname.</span>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">API key</span>
|
||||
<Input
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder={initial?.hasApiKey ? "stored; type to replace" : "optional"}
|
||||
disabled={removeKey}
|
||||
/>
|
||||
{initial?.hasApiKey && (
|
||||
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Checkbox checked={removeKey} onCheckedChange={(v) => setRemoveKey(!!v)} />
|
||||
Remove the stored key
|
||||
</label>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">Stays on the server: never shown again, logged or put into a run.</span>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">Engine</span>
|
||||
<NativeSelect value={engine} onChange={(e) => setEngine(e.target.value)}>
|
||||
<option value="">Detect</option>
|
||||
{ENDPOINT_ENGINES.map((e) => (
|
||||
<option key={e} value={e}>
|
||||
{ENGINE_LABEL[e]}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">Model</span>
|
||||
{models.length > 1 ? (
|
||||
<NativeSelect value={model} onChange={(e) => setModel(e.target.value)}>
|
||||
<option value="">Choose…</option>
|
||||
{models.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
) : (
|
||||
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={models[0] ?? "the only one it serves"} />
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" variant="outline" onClick={test} disabled={testing || !baseUrl.trim()}>
|
||||
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
|
||||
Test connection
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
<SaveIcon />
|
||||
{initial ? "Save" : "Add endpoint"}
|
||||
</Button>
|
||||
</div>
|
||||
{probe && <ProbeResult probe={probe} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Hardware notes</CardTitle>
|
||||
<CardDescription>
|
||||
Kaname can't see the machine behind an endpoint. What you enter here goes into every run, its BetterBench notes and launch80 reports, so results stay
|
||||
comparable.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4 text-sm">
|
||||
{GROUPS.map((g) => (
|
||||
<fieldset key={g.title} className="flex flex-col gap-2">
|
||||
<legend className="mb-1 font-medium">{g.title}</legend>
|
||||
<p className="-mt-1 text-xs text-muted-foreground">{g.hint}</p>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{g.fields.map((f) => (
|
||||
<label key={f.key} className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">{f.label}</span>
|
||||
<Input value={hw[f.key] ?? ""} onChange={set(f.key)} placeholder={f.placeholder} inputMode={f.kind ? "decimal" : undefined} />
|
||||
</label>
|
||||
))}
|
||||
{g.title === "GPU" && (
|
||||
<>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">P2P between GPUs</span>
|
||||
<NativeSelect value={hw.p2p ?? ""} onChange={set("p2p")}>
|
||||
<option value="">unknown</option>
|
||||
<option value="on">on</option>
|
||||
<option value="off">off</option>
|
||||
<option value="partial">partial</option>
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">Resizable BAR</span>
|
||||
<NativeSelect value={hw.rebar ?? ""} onChange={set("rebar")}>
|
||||
<option value="">unknown</option>
|
||||
<option value="on">on</option>
|
||||
<option value="off">off</option>
|
||||
</NativeSelect>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
))}
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="font-medium">Notes</span>
|
||||
<textarea
|
||||
value={hw.description ?? ""}
|
||||
onChange={set("description")}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder="Launch flags, power limit, anything worth knowing. Published with the runs."
|
||||
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"
|
||||
/>
|
||||
</label>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** What "Test connection" found. */
|
||||
export function ProbeResult({ probe }: { probe: EndpointProbe }) {
|
||||
if (!probe.ok) {
|
||||
return (
|
||||
<div className="flex gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs">
|
||||
<XCircleIcon className="size-4 shrink-0 text-destructive" />
|
||||
<span>{probe.error}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs">
|
||||
<CheckCircle2Icon className="size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<span>
|
||||
Reachable{probe.latencyMs != null ? ` (${probe.latencyMs} ms)` : ""}
|
||||
{probe.engine ? ` · ${ENGINE_LABEL[probe.engine]}${probe.engineVersion ? ` ${probe.engineVersion}` : ""}` : " · engine not detected"}
|
||||
{probe.contextSize ? ` · ${probe.contextSize.toLocaleString("en-US")} tokens context` : ""}
|
||||
{probe.slots ? ` · ${probe.slots} slots` : ""}
|
||||
</span>
|
||||
<span className="break-all text-muted-foreground">
|
||||
{probe.models.length ? `Serves: ${probe.models.slice(0, 6).join(", ")}${probe.models.length > 6 ? ", …" : ""}` : "Lists no models."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import type { EndpointProbe } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Reachable / unreachable / untested, from the last connection test. */
|
||||
export function EndpointStatus({ probe }: { probe: EndpointProbe | null }) {
|
||||
const state = !probe ? "untested" : probe.ok ? "reachable" : "unreachable";
|
||||
return (
|
||||
<span className="flex flex-col gap-0.5" title={probe?.error ?? undefined}>
|
||||
<span className="flex items-center gap-1.5 text-sm">
|
||||
<span className={cn("size-2 rounded-full", state === "reachable" ? "bg-emerald-500" : state === "unreachable" ? "bg-destructive" : "bg-foreground/25")} />
|
||||
{state}
|
||||
</span>
|
||||
{probe && (
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
<LocalTime value={probe.at} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { EndpointForm } from "../endpoint-form";
|
||||
|
||||
export const metadata: Metadata = { title: "New endpoint" };
|
||||
|
||||
export default function NewEndpointPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">New endpoint</h1>
|
||||
<EndpointForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { PlusIcon, ServerIcon } from "lucide-react";
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { listEndpoints } from "@/lib/endpoints";
|
||||
import { EndpointStatus } from "./endpoint-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Endpoints" };
|
||||
|
||||
export default async function EndpointsPage() {
|
||||
const [endpoints, runs] = await Promise.all([listEndpoints(), listBenchmarks()]);
|
||||
// Newest completed speed run and quality score per endpoint.
|
||||
const latest = new Map<string, { decode: number | null; quality: number | null }>();
|
||||
for (const r of runs) {
|
||||
if (!r.endpointId || r.state !== "completed") continue;
|
||||
const cur = latest.get(r.endpointId) ?? { decode: null, quality: null };
|
||||
if (r.kind === "run" && cur.decode == null) cur.decode = headline(r.summary).decode;
|
||||
if (r.kind === "eval" && cur.quality == null) cur.quality = r.quality?.score ?? null;
|
||||
latest.set(r.endpointId, cur);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-end justify-between gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">Endpoints</h1>
|
||||
<p className="text-sm text-muted-foreground">OpenAI-compatible servers to benchmark. They run elsewhere; Kaname only sends them requests.</p>
|
||||
</div>
|
||||
<Link href="/endpoints/new" className={buttonVariants()}>
|
||||
<PlusIcon />
|
||||
Add endpoint
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{endpoints.length === 0 ? (
|
||||
<Card className="items-center gap-3 py-10 text-center">
|
||||
<ServerIcon className="size-8 text-muted-foreground" />
|
||||
<p className="max-w-md text-sm text-muted-foreground">
|
||||
No endpoints yet. Add the URL of a llama.cpp, vLLM, SGLang or Ollama server, describe its hardware, and benchmark it.
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="py-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Endpoint</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Model</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Hardware</TableHead>
|
||||
<TableHead className="text-right">Decode t/s</TableHead>
|
||||
<TableHead className="hidden text-right sm:table-cell">Quality</TableHead>
|
||||
<TableHead className="w-32">Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{endpoints.map((e) => {
|
||||
const l = latest.get(e.id);
|
||||
const engine = e.hardware.engineName || (e.engine ?? e.probe?.engine ? ENGINE_LABEL[(e.engine ?? e.probe?.engine)!] : null);
|
||||
return (
|
||||
<TableRow key={e.id}>
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link href={`/endpoints/${e.id}`} className="font-medium hover:underline">
|
||||
{e.name}
|
||||
</Link>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{e.baseUrl}
|
||||
{engine && ` · ${engine}${e.probe?.engineVersion ? ` ${e.probe.engineVersion}` : ""}`}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden max-w-64 truncate text-sm md:table-cell">{e.model ?? (e.probe?.models.length === 1 ? e.probe.models[0] : "–")}</TableCell>
|
||||
<TableCell className="hidden text-sm text-muted-foreground lg:table-cell">
|
||||
{e.hardware.gpuName ? `${e.hardware.gpuCount ?? 1}× ${e.hardware.gpuName}` : (e.hardware.cpu ?? "–")}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{l?.decode != null ? l.decode.toFixed(1) : "–"}</TableCell>
|
||||
<TableCell className="hidden text-right tabular-nums sm:table-cell">{l?.quality != null ? `${l.quality}%` : "–"}</TableCell>
|
||||
<TableCell>
|
||||
<EndpointStatus probe={e.probe} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import { formatDuration } from "@/lib/format";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { jobLabel } from "@/lib/job-labels";
|
||||
import type { JobSnapshot } from "@/lib/jobs";
|
||||
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
@@ -40,7 +41,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-xl font-semibold">
|
||||
{job.kind === "download" ? "Download" : job.kind} ·{" "}
|
||||
{jobLabel(job)} ·{" "}
|
||||
<Link href={`/${job.repoId}`} className="hover:underline">
|
||||
{job.repoId}
|
||||
</Link>
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
} 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",
|
||||
@@ -56,7 +56,12 @@ function toSearchable(r: LibraryRow): SearchableModel {
|
||||
pipelineTag: r.pipelineTag,
|
||||
license: r.license,
|
||||
status: r.status,
|
||||
hubStatus: r.hubState && r.hubState !== "available" ? HUB_STATE_LABEL[r.hubState].label : null,
|
||||
hubStatus:
|
||||
r.hubState && r.hubState !== "available"
|
||||
? HUB_STATE_LABEL[r.hubState].label
|
||||
: r.updateAvailable
|
||||
? "update available"
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -223,6 +228,11 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
<span className="flex flex-wrap gap-1">
|
||||
<ModelStatusBadge status={r.status} />
|
||||
<HubStateBadge state={r.hubState} />
|
||||
{r.updateAvailable && (r.hubState === "available" || !r.hubState) && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium whitespace-nowrap text-sky-700 dark:text-sky-300">
|
||||
update available
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getRecommendedRoles } from "@/lib/settings";
|
||||
import { getDownloadSpeedLimit, getRecommendedRoles, getScanStatus } from "@/lib/settings";
|
||||
import { RecommendedSettings } from "./recommended-settings";
|
||||
import { ScanSettings } from "./scan-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()} />
|
||||
<ScanSettings initial={await getScanStatus()} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2Icon, ScanSearchIcon } from "lucide-react";
|
||||
import { useEffect, useState, useSyncExternalStore } 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 { FREQUENCY_LABEL, SCAN_FREQUENCIES, type ScanFrequency } from "@/lib/folder-scan";
|
||||
import type { ScanStatus } from "@/lib/settings";
|
||||
|
||||
const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
||||
const browserTz = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
||||
const noSubscribe = () => () => {};
|
||||
|
||||
/** When the worker looks for importable folders in the models folder, plus "Scan now". */
|
||||
export function ScanSettings({ initial }: { initial: ScanStatus }) {
|
||||
const [status, setStatus] = useState(initial);
|
||||
const [every, setEvery] = useState<ScanFrequency>(initial.schedule.every);
|
||||
const [time, setTime] = useState(initial.schedule.time);
|
||||
const [weekday, setWeekday] = useState(initial.schedule.weekday);
|
||||
const [monthDay, setMonthDay] = useState(initial.schedule.monthDay);
|
||||
const [busy, setBusy] = useState(false);
|
||||
// The browser's zone; the server renders the stored one.
|
||||
const tz = useSyncExternalStore(noSubscribe, browserTz, () => initial.schedule.tz);
|
||||
|
||||
const s = status.schedule;
|
||||
const dirty = every !== s.every || time !== s.time || weekday !== s.weekday || monthDay !== s.monthDay || (every !== "2min" && every !== "manual" && tz !== s.tz);
|
||||
const timed = every === "daily" || every === "weekly" || every === "monthly";
|
||||
|
||||
// While a requested scan hasn't run yet, refresh until it has.
|
||||
useEffect(() => {
|
||||
if (!status.requested) return;
|
||||
const t = setInterval(async () => {
|
||||
const res = await fetch("/api/settings/downloads", { cache: "no-store" }).catch(() => null);
|
||||
if (res?.ok) setStatus((await res.json()).scan);
|
||||
}, 2_000);
|
||||
return () => clearInterval(t);
|
||||
}, [status.requested]);
|
||||
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/downloads", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ scanSchedule: { every, time, weekday, monthDay, tz } }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
|
||||
setStatus(body.scan);
|
||||
toast.success("Scan schedule saved");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanNow() {
|
||||
const res = await fetch("/api/local-folders/scan", { method: "POST" });
|
||||
if (!res.ok) return toast.error(`Could not start a scan (${res.status})`);
|
||||
setStatus((cur) => ({ ...cur, requested: true }));
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Models folder scan</CardTitle>
|
||||
<CardDescription>
|
||||
Kaname looks through the models folder for folders that aren't in the library yet, so you can import them. It only lists files and their sizes (no
|
||||
hashing) and skips the models you already have; on a NAS, a rarer schedule lets the disks sleep.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scan-every">Scan</Label>
|
||||
<NativeSelect id="scan-every" value={every} onChange={(e) => setEvery(e.target.value as ScanFrequency)} className="w-64">
|
||||
{SCAN_FREQUENCIES.map((f) => (
|
||||
<option key={f} value={f}>
|
||||
{FREQUENCY_LABEL[f]}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
{every === "weekly" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scan-weekday">On</Label>
|
||||
<NativeSelect id="scan-weekday" value={weekday} onChange={(e) => setWeekday(Number(e.target.value))} className="w-36">
|
||||
{WEEKDAYS.map((d, i) => (
|
||||
<option key={d} value={i}>
|
||||
{d}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
)}
|
||||
{every === "monthly" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scan-day">On day</Label>
|
||||
<NativeSelect id="scan-day" value={monthDay} onChange={(e) => setMonthDay(Number(e.target.value))} className="w-24">
|
||||
{Array.from({ length: 28 }, (_, i) => i + 1).map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{d}.
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
)}
|
||||
{timed && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scan-time">At</Label>
|
||||
<Input id="scan-time" type="time" value={time} onChange={(e) => setTime(e.target.value || "03:00")} className="w-32" />
|
||||
</div>
|
||||
)}
|
||||
{every === "hourly" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scan-minute">At minute</Label>
|
||||
<NativeSelect id="scan-minute" value={time.slice(3)} onChange={(e) => setTime(`${time.slice(0, 2)}:${e.target.value}`)} className="w-24">
|
||||
{Array.from({ length: 12 }, (_, i) => String(i * 5).padStart(2, "0")).map((m) => (
|
||||
<option key={m} value={m}>
|
||||
:{m}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
)}
|
||||
<Button onClick={save} disabled={busy || !dirty}>
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" onClick={scanNow} disabled={status.requested}>
|
||||
{status.requested ? <Loader2Icon className="animate-spin" /> : <ScanSearchIcon />}
|
||||
{status.requested ? "Scanning…" : "Scan now"}
|
||||
</Button>
|
||||
</div>
|
||||
{timed && <p className="text-xs text-muted-foreground">Times are in your time zone ({tz}).</p>}
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
|
||||
<dt className="text-muted-foreground">Last scan</dt>
|
||||
<dd>
|
||||
{status.lastScanAt ? (
|
||||
<>
|
||||
<LocalTime value={status.lastScanAt} /> · {status.lastScanFound ?? 0} folder{status.lastScanFound === 1 ? "" : "s"} to import
|
||||
</>
|
||||
) : (
|
||||
"not yet"
|
||||
)}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Next scan</dt>
|
||||
<dd>{status.nextScanAt ? <LocalTime value={status.nextScanAt} /> : "only when you click Scan now"}</dd>
|
||||
</dl>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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,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);
|
||||
}
|
||||
});
|
||||
@@ -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,30 @@
|
||||
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";
|
||||
import { modelName } from "@/lib/benchmark-view";
|
||||
|
||||
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-" : ""}${modelName(run.snapshot).split("/").pop()!.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
|
||||
return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } });
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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; `?endpoint=<id>` or `?model=<id>` narrows them. */
|
||||
export const GET = withAuth(async (req) => {
|
||||
const sp = new URL(req.url).searchParams;
|
||||
return NextResponse.json(await listBenchmarks({ endpointId: sp.get("endpoint") ?? undefined, modelId: sp.get("model") ?? undefined }));
|
||||
});
|
||||
|
||||
/** Queue a benchmark run against an endpoint. */
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { deleteEndpoint, EndpointError, getEndpoint, updateEndpoint } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fail = (err: unknown) => (err instanceof EndpointError ? apiError(err.status, err.code, err.message) : handleApiError(err));
|
||||
|
||||
export const GET = withAuth<RouteContext<"/api/endpoints/[id]">>(async (_req, { params }) => {
|
||||
const e = await getEndpoint((await params).id);
|
||||
return e ? NextResponse.json(e) : apiError(404, "not_found", "Endpoint not found.");
|
||||
});
|
||||
|
||||
/** Change an endpoint; leave `apiKey` out to keep the stored key, send "" to remove it. */
|
||||
export const PATCH = withAuth<RouteContext<"/api/endpoints/[id]">>(async (req, { params }) => {
|
||||
try {
|
||||
return NextResponse.json(await updateEndpoint((await params).id, await req.json()));
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
/** Delete an endpoint; its runs stay (with their snapshot). */
|
||||
export const DELETE = withAuth<RouteContext<"/api/endpoints/[id]">>(async (_req, { params }) => {
|
||||
try {
|
||||
await deleteEndpoint((await params).id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { EndpointError, testEndpoint } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Test a saved endpoint (stores the result), or, with a body, the form's unsaved values for it. */
|
||||
export const POST = withAuth<RouteContext<"/api/endpoints/[id]/test">>(async (req, { params }) => {
|
||||
try {
|
||||
const text = await req.text();
|
||||
return NextResponse.json(await testEndpoint((await params).id, text ? JSON.parse(text) : undefined));
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { createEndpoint, EndpointError, listEndpoints } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** All endpoints (never their API keys). */
|
||||
export const GET = withAuth(async () => NextResponse.json(await listEndpoints()));
|
||||
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await createEndpoint(await req.json()), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { EndpointError, testEndpoint } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Test a new endpoint's form values before saving. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await testEndpoint(null, await req.json()));
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { checkHubAvailability, getCheckedModel } from "@/lib/hub/availability";
|
||||
import { checkHub, getCheckedModel } from "@/lib/hub/availability";
|
||||
|
||||
/** Check right now whether the repo and pinned commit are still on the Hub. */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
const model = await getCheckedModel(id);
|
||||
if (!model) return apiError(404, "not_found", "Model not found.");
|
||||
return NextResponse.json(await checkHubAvailability(model));
|
||||
return NextResponse.json(await checkHub(model));
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError, queueDownload } from "@/lib/jobs";
|
||||
|
||||
/** Download again what's missing or broken (the worker deletes broken files first). */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/repair">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await queueDownload(id, "repair"), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -1,13 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { ModelError, removeModel } from "@/lib/models";
|
||||
import { deleteModel, ModelError } from "@/lib/models";
|
||||
|
||||
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (_req, { params }) => {
|
||||
/** Delete a model; `?files=1` also deletes its files from disk (queued for the worker). */
|
||||
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await removeModel(id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
const deleteFiles = new URL(req.url).searchParams.get("files") === "1";
|
||||
const { queued } = await deleteModel(id, { deleteFiles });
|
||||
return queued ? NextResponse.json({ queued }, { status: 202 }) : new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { applyUpdate, ModelError } from "@/lib/models";
|
||||
|
||||
/** Update to the newer commit found by the last Hub check (deliberate, never automatic). */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/update">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await applyUpdate(id), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError, queueVerify } from "@/lib/jobs";
|
||||
|
||||
/** Queue a verify (`?deep=1`: hash every file) of the model's selected files. */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/verify">>(async (req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const deep = new URL(req.url).searchParams.get("deep") === "1";
|
||||
return NextResponse.json(await queueVerify(id, deep), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -2,19 +2,30 @@ 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, getScanStatus, saveDownloadSpeedLimit, saveRecommendedRoles, saveScanSchedule, 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(), scan: await getScanStatus() };
|
||||
}
|
||||
|
||||
const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) });
|
||||
/** Download settings: which file kinds are picked along with model weights, the speed limit, and the models folder scan. */
|
||||
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(),
|
||||
scanSchedule: z.unknown().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);
|
||||
if (body.scanSchedule !== undefined) await saveScanSchedule(body.scanSchedule);
|
||||
return NextResponse.json(await current());
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
|
||||
@@ -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);
|
||||
@@ -127,4 +131,11 @@
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
/* Native controls (select popups, scrollbars, date pickers) follow the theme. */
|
||||
.dark {
|
||||
color-scheme: dark;
|
||||
}
|
||||
option {
|
||||
@apply bg-popover text-popover-foreground;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { LibraryIcon, SettingsIcon } from "lucide-react";
|
||||
import { GaugeIcon, LibraryIcon, ServerIcon, SettingsIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const LINKS = [
|
||||
{ href: "/", label: "Library", icon: LibraryIcon, active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/jobs/") },
|
||||
{
|
||||
href: "/",
|
||||
label: "Library",
|
||||
icon: LibraryIcon,
|
||||
active: (p: string) => !["/settings", "/endpoints", "/benchmarks"].some((x) => p.startsWith(x)),
|
||||
},
|
||||
{ href: "/endpoints", label: "Endpoints", icon: ServerIcon, active: (p: string) => p.startsWith("/endpoints") },
|
||||
{ href: "/benchmarks", label: "Benchmarks", icon: GaugeIcon, active: (p: string) => p.startsWith("/benchmarks") },
|
||||
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
|
||||
];
|
||||
|
||||
@@ -16,7 +23,7 @@ export function AppNav() {
|
||||
return (
|
||||
<nav className="flex items-center gap-1 text-sm">
|
||||
{LINKS.map((l) => {
|
||||
const active = l.active(pathname) || (l.href === "/" && pathname.startsWith("/jobs/"));
|
||||
const active = l.active(pathname);
|
||||
return (
|
||||
<Link
|
||||
key={l.href}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { LoaderCircleIcon } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const STYLE: Record<string, string> = {
|
||||
pending_approval: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
|
||||
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 === "pending_approval" ? "awaiting approval" : 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>
|
||||
);
|
||||
}
|
||||
@@ -17,3 +17,35 @@ export async function startDownload(modelId: string) {
|
||||
export async function cancelJob(jobId: string) {
|
||||
if (await post(`/api/jobs/${jobId}/cancel`)) toast.info("Cancelling…");
|
||||
}
|
||||
|
||||
export async function startVerify(modelId: string, deep: boolean) {
|
||||
if (await post(`/api/models/${modelId}/verify${deep ? "?deep=1" : ""}`)) toast.success(deep ? "Deep verify queued" : "Verify queued");
|
||||
}
|
||||
|
||||
export async function startRepair(modelId: string) {
|
||||
if (await post(`/api/models/${modelId}/repair`)) toast.success("Repair queued");
|
||||
}
|
||||
|
||||
export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
const ok = await post(`/api/models/${modelId}/update`);
|
||||
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;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 & 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** A native <select> styled like Input; the option list follows the theme via `color-scheme`. */
|
||||
function NativeSelect({ className, children, ...props }: React.ComponentProps<"select">) {
|
||||
return (
|
||||
<div className={cn("relative w-full", className)}>
|
||||
<select
|
||||
data-slot="native-select"
|
||||
className="h-8 w-full min-w-0 appearance-none rounded-lg border border-input bg-transparent py-1 pr-8 pl-2.5 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
<ChevronDownIcon className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { NativeSelect };
|
||||
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user