Compare commits
No files matched your search
+30
-15
@@ -1,49 +1,64 @@
|
||||
# Kaname settings. Copy to .env next to compose.yaml and fill in the "Required" part; everything
|
||||
# else has working defaults. Full reference: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Required
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# URL you open Kaname at in the browser. Your OIDC redirect URI is
|
||||
# <AUTH_URL>/api/auth/callback/pocket-id
|
||||
# The address you open Kaname at in the browser (no trailing slash). The OIDC redirect URI to
|
||||
# register with your provider is <AUTH_URL>/api/auth/callback/pocket-id
|
||||
AUTH_URL=http://localhost:3000
|
||||
# Random secret for session cookies: `openssl rand -base64 33`
|
||||
AUTH_SECRET=
|
||||
|
||||
# OIDC provider (e.g. Pocket ID): authorization code flow with PKCE
|
||||
OIDC_ISSUER=https://auth.example.com
|
||||
OIDC_CLIENT_ID=
|
||||
OIDC_CLIENT_SECRET=
|
||||
# Optional, comma-separated: only members of these groups (`groups` claim) can log in.
|
||||
OIDC_ALLOWED_GROUPS=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Recommended
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Hugging Face token: read-only is enough. Needed for gated/private repos, recommended anyway
|
||||
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
|
||||
HF_TOKEN=
|
||||
|
||||
# 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=
|
||||
# Optional, comma-separated: only members of these groups (`groups` claim) can log in.
|
||||
OIDC_ALLOWED_GROUPS=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Folders on the Docker host (deploy/compose.yaml); both must be owned by uid 1000
|
||||
# Folders, port and image (deploy/compose.yaml)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# SQLite database, shared by web and worker. Must be on local disk, not NFS.
|
||||
# SQLite database and benchmark results. Must be on local disk, not NFS.
|
||||
KANAME_DATA_DIR=./data
|
||||
# Downloaded models. Can be a NAS share mounted on the host, e.g. /mnt/nas/models.
|
||||
KANAME_MODELS_DIR=./models
|
||||
# Host port of the web UI
|
||||
WEB_PORT=3000
|
||||
# Image tag to run, e.g. 0.4.0 (default: latest)
|
||||
# The user Kaname runs as (and owns the files it writes). Set these to the owner of your models
|
||||
# folder, e.g. the uid/gid of a NAS share (`ls -ln /mnt/nas/models`). New, empty folders are set up
|
||||
# for this user automatically.
|
||||
PUID=1000
|
||||
PGID=1000
|
||||
# Image tag, e.g. 0.16.0 (default: latest). KANAME_IMAGE replaces the registry/name if you build or
|
||||
# mirror the image yourself.
|
||||
KANAME_VERSION=
|
||||
KANAME_IMAGE=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Optional tuning
|
||||
# Optional
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Random secret for session cookies. Empty: generated on first start and kept in the data folder.
|
||||
AUTH_SECRET=
|
||||
|
||||
# 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.
|
||||
L80_TOKEN=
|
||||
|
||||
MAX_CONCURRENT_DOWNLOADS=1
|
||||
# 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.
|
||||
# 0: use Xet (chunk-level dedup on updates). Files over 50 GB always use Xet.
|
||||
HF_HUB_DISABLE_XET=1
|
||||
+219
@@ -4,6 +4,225 @@ 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.20.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Local models have a model card again:** the folder's `README.md`. The worker reads it when it
|
||||
scans the models folder (the web app can't see that folder), so edits show up after the next
|
||||
scan. Relative images and links in it are left out.
|
||||
|
||||
## [0.19.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Import a folder that isn't on Hugging Face** (Add model → Found in the models folder → Import →
|
||||
**Add as local model**): Kaname adds every file in the folder as it is, named after the folder.
|
||||
Local models have no pinned commit, model card or model tree, and no Hub checks, updates or
|
||||
downloads. Verify still checks that each file is there with the right size; deep verify isn't
|
||||
offered because there are no Hub hashes to compare with.
|
||||
|
||||
## [0.18.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- **Your own background picture** (Settings → Appearance): upload an image and every page header
|
||||
draws it as the dot matrix instead of *The Creation of Adam*; click the preview to choose the part
|
||||
that stays in view. The browser turns it into dots, so only those are saved (not the image).
|
||||
**Use the built-in painting** switches back.
|
||||
|
||||
## [0.17.0] - 2026-11-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Several open tabs no longer stall Kaname.** Every tab with live progress kept one or two
|
||||
connections open, and over plain HTTP a browser allows six per server: the third tab loaded
|
||||
slowly and a fourth not at all. Live updates are now short requests, one poller per tab shared by
|
||||
everything on the page, paused while the tab is in the background. The server also no longer
|
||||
grows in memory while a tab stays open, and an idle page no longer redraws every 5 seconds.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Lighter library page**: folders found in the models folder no longer bring their whole file
|
||||
list (up to 5,000 entries each) into the page; **Import** loads it when you click it. Search and
|
||||
filter counts are computed once per change instead of on every progress update.
|
||||
- **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K
|
||||
search load only what they show (headline numbers, the quality score), not every run's full
|
||||
results; the list refreshed every 3 s during a run now sends a fraction of the data.
|
||||
- **Less JavaScript per page** (10–29 KB gzipped less on every page): the dot painting's data is
|
||||
loaded once and cached instead of being part of each page, the ⌘K search loads when you first
|
||||
reach for it, and the endpoint pages no longer include database code. The painting is drawn once
|
||||
per page view instead of twice, and at most once per frame while the window is resized.
|
||||
- **Less disk activity**: the models folder scan writes only folders that changed (it rewrote
|
||||
every found folder's file list each time, every 2 minutes by default), and download progress
|
||||
no longer re-checks files that are already complete, which matters on network shares. A
|
||||
benchmark's current step is written when it changes, not for every line BetterBench prints.
|
||||
- **Fewer and smaller Hugging Face requests**: adding a model right after looking it up reuses the
|
||||
file list it just fetched (a commit's files never change), the author's avatar loads alongside,
|
||||
and the regular Hub check asks only for the commit SHA instead of the full model info.
|
||||
- The **Model card** tab shows the page at once and the card when it arrives from the Hub.
|
||||
- Database indexes for the queries the live view and the worker repeat every few seconds (the
|
||||
migration runs by itself on start).
|
||||
- **The image is 427 MB instead of 1.04 GB.** The web server runs as Next.js standalone output
|
||||
(only the files it uses instead of all of `node_modules`), the worker is bundled, and neither the
|
||||
build cache nor the downloaded archives end up in the image; build-only packages (`shadcn`,
|
||||
`tw-animate-css`) are dev dependencies. The worker container used about 40 MB at idle instead of
|
||||
about 190 MB in our test. Building the image again after a code change reuses npm's and Next's
|
||||
caches (the Next build went from 30 to 12 seconds). Nothing changes in `compose.yaml` or `.env`.
|
||||
|
||||
## [0.16.0] - 2026-10-30
|
||||
|
||||
A new look, a search for everything (⌘K / Ctrl+K), removing single files, and an easier deployment
|
||||
on another server: no `chown` before the first start, no `AUTH_SECRET` to generate.
|
||||
|
||||
**Upgrading:** take the new `deploy/compose.yaml` (the sandbox now runs as `nobody` and starts after
|
||||
the worker; `KANAME_IMAGE` is new). Existing `.env` files keep working; nothing else to do.
|
||||
|
||||
### Added
|
||||
|
||||
- **New look**: every main page opens with Michelangelo's *The Creation of Adam* as a dot matrix,
|
||||
full width behind a floating menu and fading into the page; cards and tables are frosted glass on
|
||||
top of it. Drawn from a small brightness grid in the code (the photo isn't shipped), in the theme's
|
||||
colors for light and dark mode.
|
||||
- **Library header**: a greeting with live stats: downloads with speed and time left, free space
|
||||
on the models folder, library size, and updates or deletions on Hugging Face (each links to the
|
||||
matching filter). **Add model** moved up there.
|
||||
- **Search everything** with ⌘K / Ctrl+K (or Search in the menu): models, endpoints, benchmark
|
||||
runs, tags, settings pages and actions (add a model or endpoint, scan the models folder, theme).
|
||||
- The library table: search and filters as one toolbar, one heading style for all tables, and
|
||||
**pagination** (10–100 rows per page).
|
||||
- **Remove single files** from a model: the trash icon next to a downloaded file on the Files tab
|
||||
deletes it (all parts of a split file) from disk and takes it out of the selection; the rest of
|
||||
the model stays. A model's last file can't be removed this way (delete the model instead).
|
||||
- `PUID`/`PGID`: the user Kaname runs as. The containers start as root only to prepare the folders:
|
||||
the data folder is created and given to that user, the models folder only if it is empty (one
|
||||
with files in it is never changed). Then they drop to that user.
|
||||
- `AUTH_SECRET` is optional: without it, one is generated on first start and kept in the data folder.
|
||||
- `KANAME_IMAGE` for a self-built or mirrored image; the README explains where the image is (public,
|
||||
no login), its tags, and how to build it yourself.
|
||||
|
||||
### Changed
|
||||
|
||||
- The menu floats as two pills (navigation; search, worker status, account). The worker status is a
|
||||
green dot while it's online; the account button is just the avatar. The logo is gone.
|
||||
- Model pages: the Hugging Face link sits next to the name, Delete at the end of the tabs.
|
||||
- The sandbox container runs as `nobody` (65534) instead of the app user.
|
||||
- `.env.example` is grouped into required, recommended and optional settings.
|
||||
|
||||
## [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
|
||||
|
||||
+44
-32
@@ -1,5 +1,6 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# One image for both services; the first argument picks the role: `web` (default) or `worker`.
|
||||
# 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
|
||||
|
||||
@@ -8,49 +9,56 @@ FROM node AS build
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
# npm's download cache and Turbopack's build cache (.next/cache) are cache mounts: kept between
|
||||
# builds on the same machine, never part of an image layer.
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci
|
||||
COPY . .
|
||||
RUN npm run build \
|
||||
&& npm run build:worker \
|
||||
&& npm prune --omit=dev
|
||||
# Standalone output: the web server plus only the node_modules files it uses. The worker, migrate
|
||||
# and sandbox scripts are bundled (esbuild) and only need @libsql/client from those.
|
||||
RUN --mount=type=cache,target=/app/.next/cache \
|
||||
NEXT_OUTPUT=standalone npm run build \
|
||||
&& npm run build:worker
|
||||
|
||||
# --- runtime -----------------------------------------------------------------
|
||||
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
|
||||
# has CA certificates and libstdc++; apt only adds the PCI ID database (GPU names for benchmarks).
|
||||
FROM python:3.13-slim-trixie AS runtime
|
||||
COPY --from=node /usr/local/bin/node /usr/local/bin/node
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends pci.ids \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
|
||||
# re-verify that before bumping.
|
||||
ARG HF_HUB_VERSION=2.1.1
|
||||
# BetterBench (Apache-2.0), the benchmark run against deployments. Not on PyPI: the release
|
||||
# --- downloads ---------------------------------------------------------------
|
||||
# Pinned release archives, in their own stage: only what is installed from them reaches the image.
|
||||
FROM python:3.13-slim-trixie AS downloads
|
||||
# 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
|
||||
https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /downloads/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
|
||||
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /downloads/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
|
||||
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /downloads/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 \
|
||||
&& tar -xzf "/downloads/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
|
||||
&& chmod 0755 /opt/l80/L80
|
||||
|
||||
# --- runtime -----------------------------------------------------------------
|
||||
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
|
||||
# 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
|
||||
COPY --from=downloads /opt/l80/L80 /opt/l80/L80
|
||||
|
||||
# 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
|
||||
RUN --mount=type=bind,from=downloads,source=/downloads/betterbench.tar.gz,target=/tmp/betterbench.tar.gz \
|
||||
python -m venv /opt/hf \
|
||||
&& /opt/hf/bin/pip install --no-cache-dir "huggingface_hub[hf_xet]==${HF_HUB_VERSION}" \
|
||||
&& 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 \
|
||||
&& rm -rf /root/.cache \
|
||||
&& 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 \
|
||||
&& chmod 0777 /sandbox
|
||||
|
||||
ARG APP_VERSION=dev
|
||||
ENV PATH=/opt/hf/bin:$PATH \
|
||||
@@ -66,14 +74,18 @@ ENV PATH=/opt/hf/bin:$PATH \
|
||||
L80_BIN=/opt/l80/L80
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=build --chown=app:app /app/package.json /app/next.config.ts ./
|
||||
COPY --from=build --chown=app:app /app/node_modules ./node_modules
|
||||
COPY --from=build --chown=app:app /app/.next ./.next
|
||||
# server.js, package.json, the traced node_modules (also what dist/ needs: @libsql/client) and .next.
|
||||
COPY --from=build --chown=app:app /app/.next/standalone ./
|
||||
COPY --from=build --chown=app:app /app/.next/static ./.next/static
|
||||
COPY --from=build --chown=app:app /app/dist ./dist
|
||||
COPY --from=build --chown=app:app /app/drizzle ./drizzle
|
||||
COPY --chmod=755 docker-entrypoint.sh docker-healthcheck.sh /usr/local/bin/
|
||||
# Next.js writes its cache at runtime, as whatever PUID the container runs as.
|
||||
RUN mkdir -p .next/cache && chmod 0777 .next/cache
|
||||
|
||||
USER app
|
||||
# Starts as root: docker-entrypoint.sh prepares /data (and an empty models folder) for PUID:PGID
|
||||
# (default 1000:1000), then drops to that user. /sandbox is the exchange folder between the worker
|
||||
# (PUID) and the sandbox (nobody); a fresh named volume copies its 0777.
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=15s --timeout=5s --start-period=30s --retries=3 CMD ["docker-healthcheck.sh"]
|
||||
ENTRYPOINT ["docker-entrypoint.sh"]
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<p align="center">
|
||||
<img src="docs/banner.png" alt="Kaname: self-hosted model manager for Hugging Face" width="100%" />
|
||||
<img src="docs/banner-0.16.png" alt="Kaname: download models from Hugging Face and benchmark the servers that run them" 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,12 +14,16 @@ 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
|
||||
|
||||
You need Docker with Compose and an OIDC provider (e.g. [Pocket ID](https://pocket-id.org)).
|
||||
You need a Linux server with Docker and Compose, and an OIDC provider for the login (e.g.
|
||||
[Pocket ID](https://pocket-id.org), Authelia, Authentik, Keycloak).
|
||||
|
||||
**1. Get the compose file and the config template**
|
||||
|
||||
@@ -28,31 +34,61 @@ curl -fsSLo .env https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/m
|
||||
```
|
||||
|
||||
**2. Create an OIDC client** in your identity provider with the redirect URI
|
||||
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`.
|
||||
Request the `groups` scope if you want to restrict access by group.
|
||||
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`
|
||||
(the path says `pocket-id` whatever provider you use). Request the `groups` scope if you want to
|
||||
restrict access by group.
|
||||
|
||||
**3. Fill in `.env`.** At minimum: `AUTH_URL` (the address you open in the browser), `AUTH_SECRET`
|
||||
(`openssl rand -base64 33`), `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a
|
||||
read-only `HF_TOKEN`.
|
||||
**3. Fill in `.env`:** `AUTH_URL` (the address you open in the browser), `OIDC_ISSUER`,
|
||||
`OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else has
|
||||
defaults. Models go to `./models` and the database to `./data` next to the compose file; point
|
||||
`KANAME_MODELS_DIR` at another folder (e.g. a NAS share mounted on the host) if you like.
|
||||
|
||||
**4. Create the folders and start**
|
||||
**4. Start**
|
||||
|
||||
```bash
|
||||
mkdir -p data models && sudo chown 1000:1000 data models
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open your `AUTH_URL`, sign in, click **Add model**. That's it.
|
||||
|
||||
Kaname creates and takes over `./data` itself, and an empty models folder too. It runs as uid/gid
|
||||
1000 by default; if your models folder already holds files that belong to another user (common for
|
||||
NAS shares), set `PUID`/`PGID` in `.env` to that owner (`ls -ln /path/to/models`). Kaname never
|
||||
changes the ownership of a models folder that has files in it.
|
||||
|
||||
**Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g.
|
||||
`KANAME_VERSION=0.4.0` in `.env`. The running version is shown next to the app name.
|
||||
`KANAME_VERSION=0.16.0` in `.env`. The running version is shown next to the app name. Read the
|
||||
[changelog](CHANGELOG.md) before jumping minor versions: it says when the compose file changed.
|
||||
|
||||
### The image
|
||||
|
||||
`git.linxweiler.xyz/pascallinxweiler/kaname` is public: no account or `docker login` needed.
|
||||
|
||||
| Tag | What it is |
|
||||
| --- | --- |
|
||||
| `latest` | the newest release |
|
||||
| `0.16` | the newest 0.16.x release |
|
||||
| `0.16.0` | exactly that release |
|
||||
|
||||
It is built for x86-64 (`linux/amd64`). One image serves all three services (`web`, `worker`,
|
||||
`sandbox`); the compose file picks the role. To build it yourself (e.g. for ARM) from this
|
||||
repository:
|
||||
|
||||
```bash
|
||||
git clone https://git.linxweiler.xyz/pascallinxweiler/Kaname.git && cd Kaname
|
||||
docker build -t kaname:mine --build-arg APP_VERSION=$(git describe --tags) .
|
||||
```
|
||||
|
||||
and set `KANAME_IMAGE=kaname` and `KANAME_VERSION=mine` in `.env`.
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings live in `.env`. The four steps above cover the required ones; the **[configuration
|
||||
reference in the wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration)**
|
||||
lists every option with defaults and examples (folders, ports, download tuning, OIDC groups, which
|
||||
Hugging Face token to use).
|
||||
All settings live in `.env`; [`.env.example`](.env.example) explains each one. The
|
||||
**[configuration reference in the wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration)**
|
||||
lists every option with defaults and examples (folders, ports, user, download tuning, OIDC groups,
|
||||
which Hugging Face token to use). Settings that change while Kaname runs (download speed limit,
|
||||
which files are picked with a quant, file labels, tags, how often the models folder is scanned) are
|
||||
in the web UI under Settings.
|
||||
|
||||
Models end up in `<models folder>/<org>/<repo>/`, e.g. `models/unsloth/Qwen3-8B-GGUF/`.
|
||||
More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki).
|
||||
@@ -68,6 +104,8 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
are selected along with it; choose which kinds in Settings → Downloads. You can add tags right there.
|
||||
- **Search:** type anything: `unsloth qwen`, `q4_k_m`, `gemma`, `roleplay`. Every word has to match
|
||||
somewhere (repo, author, base model family, architecture, quant, tags).
|
||||
- **Search everything:** ⌘K / Ctrl+K (or **Search** in the menu) jumps to any model, endpoint,
|
||||
benchmark run, tag or settings page, and runs actions like Add model or switching the theme.
|
||||
- **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so
|
||||
you can bookmark a view.
|
||||
- **Tags:** add or remove your own tags on a model's page; click a tag in the list to filter by it.
|
||||
@@ -76,37 +114,53 @@ 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).
|
||||
Kaname looks for such folders every 2 minutes by default; in Settings → Downloads you can make
|
||||
that hourly, daily, weekly or monthly at a time you pick, or manual only (**Scan now**), e.g. so
|
||||
NAS disks can sleep.
|
||||
- **Download more / remove files:** on a model's Files tab, **Download more** adds files of the repo
|
||||
(another quant, the vision projector, …); the trash icon next to a downloaded file deletes it from
|
||||
disk and takes it out of the selection, the rest of the model stays.
|
||||
- **Verify / repair:** Verify checks every file's presence and size, Deep verify hashes them against
|
||||
the Hub; Repair downloads only what's missing or broken.
|
||||
- **Updates:** Kaname checks the Hub regularly and shows which of your files a newer commit changes;
|
||||
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
|
||||
model is flagged and your local copy is kept.
|
||||
- **Delete:** removes the model and, if you want, its files from disk.
|
||||
- **Runtimes:** register llama.cpp, vLLM or your own fork images and pull them from Settings → Runtimes
|
||||
(groundwork for testing model configs). See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
|
||||
- **Delete:** removes the model and, if you want, its files from disk (files that aren't part of
|
||||
the repo are kept).
|
||||
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
|
||||
- **API for agents:** create a token in Settings → API tokens and let a program or AI agent look up
|
||||
repos, list models and request downloads at `/api/v1`, and deploy and benchmark models to tune
|
||||
their launch options, within guardrails you set (approval, sizes and limits, one GPU job at a time,
|
||||
allowed runtimes and arguments, protected deployments). See [docs/api.md](docs/api.md) (also how to
|
||||
let `/api/v1/` past a forward-auth proxy) and the agent skills [docs/agent/SKILL.md](docs/agent/SKILL.md)
|
||||
and [docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md).
|
||||
- **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.
|
||||
- **web:** Next.js UI and API, OIDC login (Auth.js); live updates by polling once a second from
|
||||
the visible tab (paused in background tabs, so any number of tabs can stay open).
|
||||
- **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, small limits and an unprivileged user. It
|
||||
shares only an exchange folder with the worker and gets no settings or secrets. 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
|
||||
@@ -130,7 +184,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
|
||||
|
||||
+20
-17
@@ -20,31 +20,34 @@ services:
|
||||
DATABASE_URL: file:/data/app.db
|
||||
MODELS_DIR: /models
|
||||
HF_HOME: /data/hf-home
|
||||
DOCKER_HOST: tcp://docker-proxy:2375
|
||||
volumes: [data:/data, models:/models]
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes: [data:/data, models:/models, sandbox:/sandbox]
|
||||
|
||||
web:
|
||||
<<: *app
|
||||
ports: ["${WEB_PORT:-3000}:3000"]
|
||||
volumes: [data:/data]
|
||||
|
||||
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
|
||||
# containers, images, networks, info. Not reachable from outside the compose network.
|
||||
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
|
||||
docker-proxy:
|
||||
image: tecnativa/docker-socket-proxy:v0.5.0
|
||||
environment:
|
||||
CONTAINERS: 1
|
||||
IMAGES: 1
|
||||
INFO: 1
|
||||
NETWORKS: 1
|
||||
POST: 1
|
||||
ALLOW_START: 1
|
||||
ALLOW_STOP: 1
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
# Runs the quality eval's coding answers (Python written by the model under test) with no
|
||||
# network, a read-only root, no capabilities, small limits and an unprivileged user. It shares only
|
||||
# the exchange folder with the worker. Optional: without it the quality eval skips coding.
|
||||
sandbox:
|
||||
image: kaname:local
|
||||
command: sandbox
|
||||
user: "65534:65534"
|
||||
depends_on: [worker]
|
||||
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:
|
||||
+37
-29
@@ -1,41 +1,49 @@
|
||||
# Kaname: put this file and a filled-in .env (from .env.example) in one folder, then
|
||||
# mkdir -p data models && sudo chown 1000:1000 data models
|
||||
# docker compose up -d
|
||||
# The data and models folders are created next to this file unless .env points elsewhere.
|
||||
name: kaname
|
||||
|
||||
services:
|
||||
worker:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
command: worker
|
||||
env_file: .env
|
||||
environment:
|
||||
DOCKER_HOST: tcp://docker-proxy:2375
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
|
||||
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
|
||||
restart: unless-stopped
|
||||
x-kaname: &kaname
|
||||
# Public image, no login needed. Pin a version with KANAME_VERSION=0.15.2 in .env.
|
||||
image: ${KANAME_IMAGE:-git.linxweiler.xyz/pascallinxweiler/kaname}:${KANAME_VERSION:-latest}
|
||||
restart: unless-stopped
|
||||
|
||||
services:
|
||||
web:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
<<: *kaname
|
||||
env_file: .env
|
||||
ports: ["${WEB_PORT:-3000}:3000"]
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data
|
||||
restart: unless-stopped
|
||||
- ${KANAME_DATA_DIR:-./data}:/data # SQLite database and results, shared with the worker (local disk, not NFS)
|
||||
|
||||
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
|
||||
# containers, images, networks, info. Not reachable from outside the compose network.
|
||||
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
|
||||
docker-proxy:
|
||||
image: tecnativa/docker-socket-proxy:v0.5.0
|
||||
worker:
|
||||
<<: *kaname
|
||||
command: worker
|
||||
env_file: .env
|
||||
environment:
|
||||
CONTAINERS: 1
|
||||
IMAGES: 1
|
||||
INFO: 1
|
||||
NETWORKS: 1
|
||||
POST: 1
|
||||
ALLOW_START: 1
|
||||
ALLOW_STOP: 1
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
restart: unless-stopped
|
||||
- ${KANAME_DATA_DIR:-./data}:/data
|
||||
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a NAS share mounted on the host works)
|
||||
- sandbox:/sandbox # exchange folder with the code sandbox
|
||||
|
||||
# Runs the quality eval's coding answers (Python written by the model under test): no network, a
|
||||
# read-only root, no capabilities, small limits, an unprivileged user, and only the exchange
|
||||
# folder shared with the worker. No .env (no secrets). Optional: without it the eval skips coding.
|
||||
sandbox:
|
||||
<<: *kaname
|
||||
command: sandbox
|
||||
user: "65534:65534"
|
||||
depends_on: [worker]
|
||||
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]
|
||||
|
||||
volumes:
|
||||
sandbox:
|
||||
+46
-4
@@ -1,12 +1,38 @@
|
||||
#!/bin/sh
|
||||
# Usage: docker run <image> [web|worker|<any command>] (default: web)
|
||||
# Usage: docker run <image> [web|worker|sandbox|<any command>] (default: web)
|
||||
#
|
||||
# Started as root (the default), it prepares the folders, then drops to PUID:PGID (default
|
||||
# 1000:1000) and runs as that user. Started as a user already (`user:` in compose), it skips that.
|
||||
set -e
|
||||
|
||||
role="${1:-web}"
|
||||
models="${MODELS_DIR:-/models}"
|
||||
|
||||
if [ "$(id -u)" = 0 ] && [ "$role" != sandbox ]; then
|
||||
uid="${PUID:-1000}"
|
||||
gid="${PGID:-1000}"
|
||||
as_user() { setpriv --reuid="$uid" --regid="$gid" --clear-groups "$@"; }
|
||||
# /data is Kaname's own (database, results): take it over if a new or old mount belongs to someone else.
|
||||
if [ -d /data ] && [ "$(stat -c %u:%g /data)" != "$uid:$gid" ]; then
|
||||
echo "Taking over /data for $uid:$gid"
|
||||
chown -R "$uid:$gid" /data
|
||||
fi
|
||||
# The models folder may be a NAS share with other files: only a new, empty one is taken over.
|
||||
if [ "$role" = worker ] && [ -d "$models" ] && ! as_user sh -c 'touch "$1/.write-test" && rm -f "$1/.write-test"' _ "$models" 2>/dev/null; then
|
||||
if [ -z "$(ls -A "$models")" ]; then
|
||||
echo "Taking over the empty models folder for $uid:$gid"
|
||||
chown "$uid:$gid" "$models"
|
||||
fi
|
||||
fi
|
||||
# The exchange folder with the sandbox (which runs as nobody); volumes from before 0.15.2 are 0755.
|
||||
if [ "$role" = worker ] && [ -d "${SANDBOX_DIR:-/sandbox}" ]; then chmod 0777 "${SANDBOX_DIR:-/sandbox}"; fi
|
||||
export HOME=/home/app
|
||||
exec setpriv --reuid="$uid" --regid="$gid" --clear-groups "$0" "$@"
|
||||
fi
|
||||
|
||||
require_writable() {
|
||||
if ! touch "$1/.write-test" 2>/dev/null; then
|
||||
echo "ERROR: $1 is not writable by uid $(id -u). On the host: chown -R $(id -u):$(id -g) <folder mounted at $1>" >&2
|
||||
echo "ERROR: $1 is not writable by uid $(id -u). Give that user access on the host (e.g. chown -R $(id -u):$(id -g) <folder mounted at $1>), or set PUID/PGID in .env to the folder's owner." >&2
|
||||
exit 1
|
||||
fi
|
||||
rm -f "$1/.write-test"
|
||||
@@ -16,14 +42,30 @@ case "$role" in
|
||||
web|worker)
|
||||
echo "$role" > /tmp/kaname-role
|
||||
require_writable /data
|
||||
if [ "$role" = worker ]; then require_writable "${MODELS_DIR:-/models}"; fi
|
||||
if [ "$role" = worker ]; then require_writable "$models"; fi
|
||||
# Without AUTH_SECRET, one is generated on first start and kept in /data.
|
||||
if [ "$role" = web ] && [ -z "$AUTH_SECRET" ]; then
|
||||
[ -s /data/.auth-secret ] || (umask 077 && head -c 33 /dev/urandom | base64 > /data/.auth-secret)
|
||||
AUTH_SECRET="$(cat /data/.auth-secret)"
|
||||
export AUTH_SECRET
|
||||
fi
|
||||
# web and worker usually start together; the lock makes sure only one runs the migrations.
|
||||
flock /data/.migrate.lock node dist/migrate.mjs
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$role" in
|
||||
web) exec node_modules/.bin/next start ;;
|
||||
web) exec node server.js ;; # Next.js standalone server (see Dockerfile)
|
||||
worker) exec node dist/worker.mjs ;;
|
||||
sandbox)
|
||||
# It runs code written by the model under test: never as root (compose gives it `user:`).
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
echo "ERROR: the sandbox must not run as root; give the service a user, e.g. user: \"65534:65534\"." >&2
|
||||
exit 1
|
||||
fi
|
||||
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
|
||||
@@ -1,179 +0,0 @@
|
||||
---
|
||||
name: kaname-tuning
|
||||
description: Deploy local LLMs on the user's Kaname server and benchmark them to find good launch options (context, KV cache type, batch sizes, GPU layers, runtime) for the hardware. Use when the user asks to deploy, test, benchmark, tune or compare a model's settings, or to find the fastest setup for a model.
|
||||
required_environment_variables:
|
||||
- name: KANAME_URL
|
||||
prompt: Kaname base URL (no trailing slash)
|
||||
- name: KANAME_TOKEN
|
||||
prompt: Kaname API token (kn_…) with the deployments and benchmarks scopes
|
||||
---
|
||||
|
||||
# Kaname: deploy and tune models
|
||||
|
||||
Kaname runs models in containers (llama.cpp or vLLM) and measures them with BetterBench. With this
|
||||
skill you deploy a downloaded model, benchmark it, change **one** launch option at a time and report
|
||||
which setup is best. To find or download models, use the `kaname-models` skill (`SKILL.md`).
|
||||
|
||||
You may only change and benchmark deployments your own token created. You **cannot** touch the
|
||||
user's deployments (especially protected ones), change settings, runtimes or tokens, or delete
|
||||
models. Tell the user when something needs one of those.
|
||||
|
||||
Every call needs `KANAME_URL` and `KANAME_TOKEN` (never print the token or put it in a URL), and the
|
||||
`kaname` helper (a `curl` wrapper that adds the token and JSON headers; see `SKILL.md` → Setup). If
|
||||
`kaname` is missing, write out
|
||||
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …` instead.
|
||||
|
||||
Errors are `{"error": {"code", "message"}}`; the message says what to do.
|
||||
|
||||
## Rules
|
||||
|
||||
- **No polling loops.** Status calls take `?wait=S` (max 900): Kaname holds the request until the
|
||||
state settles. Make one call, with `-m` (curl's time limit) a bit above the wait.
|
||||
- **Approval:** by default every start, run and sweep waits for the user (`state:
|
||||
pending_approval`). Then **stop**: tell the user what you asked for and that it awaits their
|
||||
approval in Kaname. Don't retry, don't poll. Continue when the user says it's approved.
|
||||
- **Never work around a guardrail** (another token, splitting a sweep, renaming things). Report the
|
||||
error message and stop.
|
||||
- **One GPU job at a time:** one of your deployments running at once (unless the user raised the
|
||||
limit), one run or sweep at a time. Stop your deployment when you're done.
|
||||
- **Change one variable at a time**, so a difference has one cause.
|
||||
|
||||
## 1. Know your limits
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1"
|
||||
```
|
||||
|
||||
`deploymentGuardrails`: approval mode, how many of your deployments may run, run/sweep time limits,
|
||||
max sweep variants, caps, host ports. Your scopes must include `deployments:write` and
|
||||
`benchmarks:run`; if not, tell the user.
|
||||
|
||||
## 2. Pick a model and a runtime
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/models?status=ready&q=qwen3"
|
||||
kaname "$KANAME_URL/api/v1/models/<modelId>" # its files (pick a .gguf for llama.cpp)
|
||||
kaname "$KANAME_URL/api/v1/runtimes"
|
||||
```
|
||||
|
||||
Runtimes say what they serve (llama.cpp: a GGUF file, vLLM: a safetensors repo), whether you may use
|
||||
them (`"allowed": true`) and which extra argument flags you may pass (`allowedExtraArgs`). `gpus`
|
||||
lists the host's GPUs and their VRAM.
|
||||
|
||||
Previous results for this model, to start from what is known:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/benchmarks?limit=10"
|
||||
```
|
||||
|
||||
## 3. Deploy
|
||||
|
||||
Check first (nothing is created; you get the exact command and the memory/VRAM estimates):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments" -d '{
|
||||
"runtimeId": "<runtimeId>", "modelId": "<modelId>", "dryRun": true,
|
||||
"options": { "modelFile": "Qwen3-8B-Q4_K_M.gguf", "contextSize": 16384, "gpuLayers": "auto",
|
||||
"cacheTypeK": "q8_0", "cacheTypeV": "q8_0", "parallel": 1, "extraArgs": [] }
|
||||
}'
|
||||
```
|
||||
|
||||
If `estimates.vramMb` is above `estimates.gpuVramMb`, lower the context, quantize the KV cache or
|
||||
pick a smaller quant. Then the same body without `"dryRun"`:
|
||||
|
||||
- `state: pending_approval` → tell the user and stop (see Rules).
|
||||
- `state: starting` → wait until it is ready:
|
||||
|
||||
```bash
|
||||
kaname -m 660 "$KANAME_URL/api/v1/deployments/<id>?wait=600"
|
||||
```
|
||||
|
||||
`state: running` → go on. `state: failed` → read `error` (and `?log=50`), fix the options
|
||||
(`PATCH`, below) and start again; don't repeat the same failing options.
|
||||
|
||||
## 4. Benchmark
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{
|
||||
"deploymentId": "<id>", "quick": true, "label": "Q4_K_M ctx16k q8_0 KV",
|
||||
"description": "Baseline for tuning Qwen3-8B on this GPU"
|
||||
}'
|
||||
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
|
||||
```
|
||||
|
||||
- `quick: true` (5 passes) to screen options; `quick: false` (20 passes) to confirm the winner.
|
||||
- `phases` (`decode`, `prefill`, `concurrency`) narrows what is measured; leave it out for all.
|
||||
- The result's `headline` has `decodeTps` (generation speed), `prefillTps` (prompt processing at the
|
||||
deepest prompt), `ttftMs` (time to first token) and `peakParallelTps`; `setup` lists GPU, PCIe,
|
||||
engine version, model/quant/KV cache, context and concurrency; `resources` has VRAM, power and
|
||||
temperature. `?full=1` only when you need the per-category details.
|
||||
- If the wait times out, the run is still going: one more call with `?wait=900`, then report.
|
||||
|
||||
## 5. Change one variable and compare
|
||||
|
||||
Stop, change one option, start, wait, benchmark again:
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
|
||||
kaname -m 120 "$KANAME_URL/api/v1/deployments/<id>?wait=60"
|
||||
kaname -X PATCH "$KANAME_URL/api/v1/deployments/<id>" -d '{"options": {"cacheTypeK": "f16", "cacheTypeV": "f16"}}'
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/start"
|
||||
```
|
||||
|
||||
Or let Kaname do it: a **sweep** deploys each variant of one or two settings, benchmarks it and
|
||||
removes it again (stop your own deployment first; it counts as one run):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/sweeps" -d '{
|
||||
"baseDeploymentId": "<id>", "quick": true,
|
||||
"params": [{ "key": "kvCache", "values": ["f16", "q8_0", "q4_0"] }]
|
||||
}'
|
||||
kaname -m 960 "$KANAME_URL/api/v1/sweeps/<sweepId>?wait=900"
|
||||
```
|
||||
|
||||
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
|
||||
`flashAttn`, `cacheRamMb`, `gpuLayers` (llama.cpp); `dtype`, `maxNumSeqs`, `gpuMemoryUtilization`
|
||||
(vLLM); `cpus`. A sweep can take long: after a timed-out wait, report progress instead of waiting
|
||||
again and again.
|
||||
|
||||
Compare runs side by side:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/benchmarks/compare?ids=<run1>,<run2>,<run3>"
|
||||
```
|
||||
|
||||
Differences under ~2 % between separate runs are noise. For a small difference that matters, run
|
||||
an A/B (two deployments of the same model at once, if the user allows 2 agent deployments):
|
||||
`{"kind": "ab", "deploymentId": "<A>", "deploymentBId": "<B>"}`.
|
||||
|
||||
## 6. Report and clean up
|
||||
|
||||
Report a compact table, one row per setup, the varied option first:
|
||||
|
||||
| KV cache | Decode t/s | Prefill t/s | TTFT ms | VRAM peak | Notes |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| f16 | 58.1 | 1910 | 88 | 11.2 GB | baseline |
|
||||
| q8_0 | 57.6 | 1880 | 90 | 9.4 GB | −1 %, 1.8 GB less VRAM |
|
||||
|
||||
Name the winner and why (and what stayed the same: GPU, engine version, quant, context). Then stop
|
||||
your deployment (or delete it if the user doesn't need it):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
|
||||
```
|
||||
|
||||
## When something is refused
|
||||
|
||||
| `error.code` | What to do |
|
||||
| --- | --- |
|
||||
| `too_many_deployments` | Stop your other deployment first, or tell the user. |
|
||||
| `gpu_busy` | Another agent job is running or a deployment is loading: wait once with `?wait=`, then retry once; otherwise report and stop. |
|
||||
| `vram_protected` | It would crowd the user's protected deployment out of VRAM: smaller quant, context or quantized KV cache, or tell the user. |
|
||||
| `arg_not_allowed` | That flag isn't allowed; use the structured option if there is one (`contextSize`, `gpuLayers`, `cacheTypeK`, …) or drop it. |
|
||||
| `limit_exceeded` | Over the memory/CPU cap: smaller model or context. |
|
||||
| `port_not_allowed` | Leave out `hostPort`. |
|
||||
| `runtime_not_allowed`, `runtime_not_pulled` | Pick another runtime from `GET /api/v1/runtimes`, or tell the user. |
|
||||
| `protected`, `not_owner` | Not your deployment: deploy your own. |
|
||||
| `too_many_variants` | Vary fewer values. |
|
||||
| `busy` | Stop the deployment before changing it. |
|
||||
| `unauthorized`, `forbidden` | Token wrong, revoked or missing a scope: tell the user. |
|
||||
@@ -1,133 +0,0 @@
|
||||
---
|
||||
name: kaname-models
|
||||
description: Find, request and track downloads of local LLMs (Hugging Face models, GGUF quants) on the user's Kaname server. Use when the user asks to get, download, add or check a model, or asks which models are available locally or how much disk space is left.
|
||||
required_environment_variables:
|
||||
- name: KANAME_URL
|
||||
prompt: Kaname base URL (no trailing slash)
|
||||
- name: KANAME_TOKEN
|
||||
prompt: Kaname API token (kn_…)
|
||||
---
|
||||
|
||||
# Kaname: local model downloads
|
||||
|
||||
Kaname manages the user's local LLM library. You can look up Hugging Face repos, see what is
|
||||
already downloaded, request a download and follow it. You **cannot** delete anything, change
|
||||
settings, or start models with this skill: tell the user when they need one of those. To deploy and
|
||||
benchmark models (with a token that has the deployments and benchmarks scopes), see
|
||||
`SKILL-tuning.md`.
|
||||
|
||||
Every call needs two environment variables:
|
||||
|
||||
- `KANAME_URL`: e.g. `https://models.example.com` (no trailing slash)
|
||||
- `KANAME_TOKEN`: the API token (`kn_…`). Never print it or put it in a URL.
|
||||
|
||||
## Setup
|
||||
|
||||
The examples use `kaname`, a small wrapper around `curl` that adds the token and JSON headers. The
|
||||
user installs it once:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.local/bin && curl -fsSL https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/docs/agent/kaname -o ~/.local/bin/kaname && chmod +x ~/.local/bin/kaname
|
||||
```
|
||||
|
||||
If `kaname` is not found, write out the full command in each call instead:
|
||||
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …`
|
||||
(every command runs in a fresh shell, so don't define a shell function for it).
|
||||
|
||||
All responses are JSON. Errors are `{"error": {"code", "message"}}`; the message says what to do.
|
||||
|
||||
## 0. Know your limits
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1"
|
||||
```
|
||||
|
||||
Shows your token name, scopes and the guardrails. The defaults:
|
||||
|
||||
- **approvalMode `approve`**: your requests wait until the user approves them. That's normal.
|
||||
- **maxRequestSize** (60 GB): one request may download at most this much.
|
||||
- **minFreeSize** (100 GB): this much must stay free on disk after the download.
|
||||
- **maxOpenAgentJobs** (2): at most this many of your requests pending or running at once.
|
||||
- **allowedAuthors**: if not empty, only repos from these Hugging Face authors.
|
||||
|
||||
## 1. Is it already here?
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/models?q=qwen3%208b"
|
||||
kaname "$KANAME_URL/api/v1/models?author=unsloth&quant=Q4_K_M&status=ready"
|
||||
```
|
||||
|
||||
Filters: `q`, `author`, `family`, `quant`, `tag`, `status`, `requested_by` (comma-separate values).
|
||||
If the model is there with `status: ready`, you're done. Don't request it again.
|
||||
|
||||
## 2. Look up the repo
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"
|
||||
```
|
||||
|
||||
Note `sha` (the commit) and pick a quant from `quants` (each has a `size`). Choose one that fits the
|
||||
user's request and the limits: check `size` against `maxRequestSize`, and check space with:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/disk" # availableForRequests = what a request may still use
|
||||
```
|
||||
|
||||
If `gated` is not `false`, the download only works if the user's Hugging Face account has access.
|
||||
|
||||
## 3. Request the download
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/downloads" \
|
||||
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"<sha from lookup>","quant":"Q4_K_M"}'
|
||||
```
|
||||
|
||||
For repos without GGUF quants (safetensors), use `"include": ["*.safetensors", "*.json"]` instead
|
||||
of `quant`. Optional: `"tags": ["…"]`.
|
||||
|
||||
Answer:
|
||||
|
||||
- `201`, `state: pending_approval`: **waiting for the user.** Tell them what you requested and that
|
||||
it needs their approval in Kaname. **Do not retry or re-request.**
|
||||
- `201`, `state: queued`: it will start on its own.
|
||||
- `200`, `created: false`: you (or someone) already requested exactly this; you get the existing
|
||||
job. Don't request it again.
|
||||
|
||||
## 4. Follow it
|
||||
|
||||
```bash
|
||||
kaname -m 660 "$KANAME_URL/api/v1/jobs/<jobId>?wait=600"
|
||||
```
|
||||
|
||||
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. With `?wait=600`
|
||||
Kaname holds the request until the job is finished (or 600 s have passed; then `timedOut` is
|
||||
`true`), so one call replaces a polling loop. Keep `-m` (curl's time limit) a bit above the wait.
|
||||
Every call costs a full round of your context, so call rarely:
|
||||
|
||||
- **`pending_approval`:** do **not** poll. Tell the user what you requested and that it awaits
|
||||
their approval in Kaname, then stop. Check again only when the user says it's approved, or, if
|
||||
the user asks for it, schedule a single one-off check later with your cron/scheduling tool.
|
||||
- **`queued` / `downloading` / `verifying`:** one call with `?wait=600`. If it comes back with
|
||||
`timedOut: true` and the ETA is long, tell the user it is still downloading instead of waiting
|
||||
again and again. Never loop in short intervals.
|
||||
- **`completed`:** tell the user it's ready.
|
||||
- **`cancelled`:** the user rejected or cancelled it. Don't ask again unless the user says so.
|
||||
- **`failed`:** report `error.message` to the user. Don't loop on retries.
|
||||
|
||||
Add `?log=20` only when you need to explain a failure.
|
||||
|
||||
## When a request is refused
|
||||
|
||||
| `error.code` | What to do |
|
||||
| --- | --- |
|
||||
| `too_large` | Pick a smaller quant (or fewer files) that fits `maxRequestSize`. |
|
||||
| `disk_space` | Pick a smaller quant, or tell the user the disk is full. |
|
||||
| `too_many_jobs` | Don't wait in a loop: tell the user your earlier downloads are still pending or running, and stop. Request again later when the user asks. |
|
||||
| `author_not_allowed` | Find the model from an allowed author, or ask the user. |
|
||||
| `already_exists` | The repo is in the library at another commit; the user updates it in Kaname. |
|
||||
| `busy` | That model has a download in progress; tell the user and stop. |
|
||||
| `gated_no_access`, `gated_no_token` | The user must accept the model's terms on Hugging Face. |
|
||||
| `disk_unknown` | Kaname's worker is offline; tell the user and stop. |
|
||||
| `unauthorized`, `forbidden` | Your token is wrong, revoked or lacks a scope: tell the user. |
|
||||
|
||||
Never try to work around a guardrail (e.g. by splitting one big download into several requests).
|
||||
@@ -1,2 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"
|
||||
-398
@@ -1,398 +0,0 @@
|
||||
# Kaname API (`/api/v1`)
|
||||
|
||||
A small JSON API for programs and AI agents: look up Hugging Face repos, list the local library,
|
||||
request downloads, deploy models and benchmark them to tune launch options. Everything an agent can
|
||||
do here is bounded by [guardrails](#guardrails); it can't delete models or files, change settings,
|
||||
manage runtimes or tokens, or touch deployments it didn't create.
|
||||
|
||||
The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login. Only
|
||||
`/api/v1` accepts tokens, and it accepts *only* tokens (a browser session doesn't work there).
|
||||
|
||||
- [Authentication](#authentication)
|
||||
- [Errors](#errors)
|
||||
- [Endpoints](#endpoints): models and downloads, [deployments](#deployments), [benchmarks](#benchmarks)
|
||||
- [Waiting instead of polling](#waiting-instead-of-polling)
|
||||
- [Guardrails](#guardrails)
|
||||
- [Behind a forward-auth proxy (Traefik)](#behind-a-forward-auth-proxy-traefik)
|
||||
|
||||
## Authentication
|
||||
|
||||
Create a token in **Settings → API tokens**. It is shown once; Kaname stores only its SHA-256.
|
||||
Send it with every request:
|
||||
|
||||
```
|
||||
Authorization: Bearer kn_…
|
||||
```
|
||||
|
||||
| Scope | Allows |
|
||||
| --- | --- |
|
||||
| `models:read` | Hub lookup, list models, read jobs (and their log), disk space |
|
||||
| `downloads:create` | `POST /api/v1/downloads`, within the guardrails |
|
||||
| `deployments:read` | List runtimes and deployments, read a deployment's state and log |
|
||||
| `deployments:write` | Create deployments; edit, start, stop and delete **its own** ones, within the guardrails |
|
||||
| `benchmarks:read` | Read runs, sweeps and comparisons |
|
||||
| `benchmarks:run` | Start runs, A/B runs and sweeps on **its own** deployments; cancel its own |
|
||||
|
||||
Tokens created before 0.13 keep the scopes they had; grant new ones with **Scopes** next to the
|
||||
token in Settings → API tokens.
|
||||
|
||||
A missing, unknown or revoked token gets `401`; a token without the needed scope gets `403`. The
|
||||
settings page shows when each token was last used; **Revoke** stops it immediately.
|
||||
|
||||
Everything a token requests is marked with its name ("requested by hermes") on the model and job
|
||||
pages and in the library, where you can filter by it.
|
||||
|
||||
## Errors
|
||||
|
||||
Errors are JSON with a message meant to be read and acted on:
|
||||
|
||||
```json
|
||||
{ "error": { "code": "too_large", "message": "exceeds max size per request 60.0 GB: requested 74.2 GB. Pick a smaller quant or fewer files." } }
|
||||
```
|
||||
|
||||
| Status | Codes |
|
||||
| --- | --- |
|
||||
| 400 | `invalid_request` (also unknown fields), `invalid_json`, `empty_selection` (quant or globs match nothing), `invalid_repo_id`, `invalid` |
|
||||
| 401 / 403 | `unauthorized`, `forbidden` (scope), `author_not_allowed`, `gated_no_token`, `gated_no_access`, `runtime_not_allowed`, `arg_not_allowed`, `port_not_allowed`, `protected`, `not_owner` |
|
||||
| 404 | `not_found`, `repo_not_found`, `revision_not_found` |
|
||||
| 409 | `already_exists` (repo is in the library at another commit), `busy` (a model with an open job; a deployment that must be stopped first), `runtime_not_pulled`, `vram_protected`, `invalid` (e.g. benchmarking a stopped deployment) |
|
||||
| 422 | `too_large`, `limit_exceeded`, `too_many_variants` |
|
||||
| 429 | `too_many_jobs`, `too_many_deployments`, `gpu_busy`, `rate_limited` (Hugging Face) |
|
||||
| 503 / 507 | `disk_unknown` (worker offline), `disk_space` |
|
||||
|
||||
Sizes appear as bytes plus a readable `"… GB"` field (decimal GB, like the Hub).
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `GET /api/v1`
|
||||
|
||||
Any valid token. Who you are, your scopes, the current guardrails and the endpoint list.
|
||||
|
||||
```bash
|
||||
curl -s -H "Authorization: Bearer $KANAME_TOKEN" "$KANAME_URL/api/v1"
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"token": { "name": "hermes", "scopes": ["models:read", "downloads:create"] },
|
||||
"guardrails": { "approvalMode": "approve", "maxRequestBytes": 60000000000, "maxRequestSize": "60.0 GB",
|
||||
"minFreeBytes": 100000000000, "minFreeSize": "100.0 GB", "maxOpenAgentJobs": 2, "allowedAuthors": [] },
|
||||
"endpoints": ["…"]
|
||||
}
|
||||
```
|
||||
|
||||
### `GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]`
|
||||
|
||||
`models:read`. Resolves the revision to a commit SHA and lists quants and files, the same data as
|
||||
the Add model dialog. `repo` may also be a Hub URL. Up to 200 files are listed unless `files=all`.
|
||||
|
||||
```json
|
||||
{
|
||||
"repoId": "unsloth/Qwen3-8B-GGUF", "revision": "main", "sha": "9e6855bc…", "gated": false,
|
||||
"lastModified": "2026-05-01T10:00:00.000Z",
|
||||
"inLibrary": null,
|
||||
"quants": [{ "quant": "Q4_K_M", "files": 1, "bytes": 5027783488, "size": "5.0 GB" }, "…"],
|
||||
"fileCount": 31, "totalBytes": 104000000000,
|
||||
"files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "bytes": 5027783488 }, "…"],
|
||||
"filesTruncated": false
|
||||
}
|
||||
```
|
||||
|
||||
`inLibrary` is `{ modelId, pinnedSha, status }` when the repo is already in Kaname.
|
||||
|
||||
### `GET /api/v1/models`
|
||||
|
||||
`models:read`. The library, filtered like the library page:
|
||||
|
||||
| Parameter | Meaning |
|
||||
| --- | --- |
|
||||
| `q` | Search text; every word must match (repo, author, family, quant, tags, …) |
|
||||
| `author`, `family`, `quant`, `tag` | Facets; repeat or comma-separate values (OR within a facet, AND across) |
|
||||
| `status` | `pending`, `downloading`, `ready`, `incomplete`, `failed`, `deleting`, `pending_approval`, `update_available`, `repo_missing`, `commit_missing` |
|
||||
| `requested_by` | Token name |
|
||||
|
||||
```json
|
||||
{ "count": 1, "models": [{ "id": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "status": "ready", "pendingApproval": false,
|
||||
"pinnedSha": "9e68…", "quants": ["Q4_K_M"], "tags": ["agent"], "selectedFiles": 1, "selectedBytes": 5027783488,
|
||||
"onDiskBytes": 5027783488, "onDisk": "5.0 GB", "updateAvailable": false, "hubState": "available",
|
||||
"requestedBy": "hermes", "createdAt": "…", "downloadedAt": "…" }] }
|
||||
```
|
||||
|
||||
### `GET /api/v1/models/{id}`
|
||||
|
||||
`models:read`. One model with its selected files (path, bytes, state) and latest job.
|
||||
|
||||
### `POST /api/v1/downloads`
|
||||
|
||||
`downloads:create`. Request a download of a repo **at a pinned commit**: take `sha` from the lookup.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `repoId` | `"org/name"` |
|
||||
| `sha` | Full 40-character commit SHA |
|
||||
| `quant` | e.g. `"Q4_K_M"`: that quant's weight files (all split parts) plus the companion files ticked in Settings → Downloads (chat template, mmproj, …), as in the Add model dialog |
|
||||
| `include` | Instead of `quant`: glob patterns, e.g. `["*.safetensors", "*.json"]` |
|
||||
| `tags` | Optional user tags for the model |
|
||||
| `revision` | Optional branch to track for update checks (default `main`) |
|
||||
|
||||
```bash
|
||||
curl -s -X POST -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"9e6855bc…","quant":"Q4_K_M"}' \
|
||||
"$KANAME_URL/api/v1/downloads"
|
||||
```
|
||||
|
||||
```json
|
||||
{ "created": true, "modelId": "01M…", "jobId": "01M…", "state": "pending_approval",
|
||||
"requestedBytes": 5027783488, "requestedSize": "5.0 GB", "files": ["Qwen3-8B-Q4_K_M.gguf"],
|
||||
"message": "Requested; waiting for the user to approve it in Kaname. Do not retry or poll; tell the user and stop." }
|
||||
```
|
||||
|
||||
- **201**: a new job, `state` `pending_approval` (approval mode `approve`) or `queued` (`auto`).
|
||||
- **200** with `"created": false`: the same repo, commit and files were requested before; you get the
|
||||
existing model and its latest job. Nothing is queued twice.
|
||||
- If the repo is already in the library at the same commit, the request adds the files that are
|
||||
missing from its selection (only the added bytes count against the guardrails). At another commit
|
||||
it is refused: updating a model is done in the UI.
|
||||
|
||||
It uses the same code path as the Add model dialog (the file list is fetched again from the Hub at
|
||||
that commit; the client's list isn't trusted).
|
||||
|
||||
### `GET /api/v1/jobs/{id}[?wait=S][&log=N]`
|
||||
|
||||
`models:read`. Compact job state:
|
||||
|
||||
```json
|
||||
{ "id": "01M…", "modelId": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "kind": "download", "purpose": "initial",
|
||||
"state": "downloading", "cancelRequested": false, "requestedBy": "hermes",
|
||||
"progress": { "doneBytes": 3000000000, "totalBytes": 5027783488, "percent": 59.7, "done": "3.0 GB", "total": "5.0 GB",
|
||||
"speedBytesPerSecond": 52000000, "etaSeconds": 39 },
|
||||
"error": null,
|
||||
"files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "state": "downloading", "doneBytes": 3000000000, "totalBytes": 5027783488 }],
|
||||
"createdAt": "…", "startedAt": "…", "finishedAt": null,
|
||||
"next": "Downloading; check again in a minute." }
|
||||
```
|
||||
|
||||
States: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `failed`, `cancelled`
|
||||
(also when the user rejected the request), `interrupted`. The `hf` log is only included with
|
||||
`?log=N` (the last N lines, at most 200). `?wait=S` returns once the job is finished (or right away
|
||||
while it waits for approval); see [Waiting instead of polling](#waiting-instead-of-polling).
|
||||
|
||||
### `GET /api/v1/disk`
|
||||
|
||||
`models:read`. Space on the models folder, as reported by the worker every few seconds:
|
||||
|
||||
```json
|
||||
{ "workerOnline": true, "freeBytes": 945600000000, "totalBytes": 2000000000000, "usedBytes": 1054400000000,
|
||||
"reservedBytes": 105454144, "minFreeBytes": 100000000000, "availableForRequestsBytes": 845494545856,
|
||||
"free": "945.6 GB", "total": "2000.0 GB", "availableForRequests": "845.5 GB" }
|
||||
```
|
||||
|
||||
`reservedBytes` is what open downloads still have to fetch; `availableForRequests` is what a request
|
||||
may use before hitting the minimum-free guardrail.
|
||||
|
||||
### Deployments
|
||||
|
||||
A deployment is a model served by a runtime container. Agents use the same validation, estimates and
|
||||
`docker run` command as the UI; they can only edit, start, stop, delete and benchmark deployments their
|
||||
own token created, and never [protected](#protected-deployments) ones.
|
||||
|
||||
#### `GET /api/v1/runtimes`
|
||||
|
||||
`deployments:read`. Runtimes with a pulled image: engine (`llama.cpp` or `vllm`), accelerator
|
||||
(`cpu`, `nvidia`, `dri` for Intel/AMD), what they serve, whether agents may use them (`allowed`) and
|
||||
the extra argument flags agents may pass (`allowedExtraArgs`); plus the host's GPUs.
|
||||
|
||||
#### `GET /api/v1/deployments[?mine=1]`, `GET /api/v1/deployments/{id}[?wait=S][&log=N]`
|
||||
|
||||
`deployments:read`. State (`stopped`, `pending_approval`, `starting`, `running`, `stopping`,
|
||||
`failed`), `mine`, `protected`, runtime, model, options, limits, the endpoint inside the Docker
|
||||
network, what the server reported once ready (version, slots, context), live CPU/RAM, error and a
|
||||
`next` hint. `?wait=S` returns once it is running, stopped or failed (or right away while the start
|
||||
waits for approval). `?log=N` adds the last N log lines (max 200).
|
||||
|
||||
#### `POST /api/v1/deployments`
|
||||
|
||||
`deployments:write`.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `runtimeId`, `modelId` | From `GET /api/v1/runtimes` and `GET /api/v1/models` |
|
||||
| `options` | The deployment form's launch options: `modelFile` (llama.cpp: the `.gguf`; vLLM: `""`), `contextSize`, `parallel`, `cacheTypeK`/`cacheTypeV`, `flashAttn`, `gpuLayers`, `batchSize`/`ubatchSize`, `maxNumSeqs`, `gpuMemoryUtilization`, … and `extraArgs` (only [allowed flags](#deployments-and-benchmarks)). Unknown fields are refused. |
|
||||
| `cpus`, `memoryMb` | Optional limits within the caps; without `memoryMb` the estimate is used |
|
||||
| `hostPort` | Optional, only inside the configured range (none by default) |
|
||||
| `name` | Optional |
|
||||
| `start` | Default `true`; with approval mode `approve` the start waits for the user |
|
||||
| `dryRun` | `true`: only validate; returns the command and estimates, creates nothing |
|
||||
|
||||
```json
|
||||
{ "created": true, "id": "01M…", "state": "pending_approval",
|
||||
"command": "docker run -v <models>:/models:ro ghcr.io/ggml-org/llama.cpp:server-intel -m /models/… -c 16384 -ctk q8_0 …",
|
||||
"estimates": { "memoryMb": 9800, "vramMb": 7900, "gpuVramMb": 32768 }, "limits": { "memoryMb": 9800, "cpus": null },
|
||||
"message": "Created; the start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop." }
|
||||
```
|
||||
|
||||
#### `PATCH /api/v1/deployments/{id}`, `POST …/start`, `POST …/stop`, `DELETE …`
|
||||
|
||||
`deployments:write`, own deployments only. `PATCH` takes `options` (merged into the current ones),
|
||||
`cpus`, `memoryMb`, `hostPort`, `name`, and only while the deployment is stopped; it returns the new
|
||||
command and estimates. `start` goes through the same guardrails as creating one (and approval);
|
||||
`stop` and `DELETE` never need approval.
|
||||
|
||||
### Benchmarks
|
||||
|
||||
#### `POST /api/v1/benchmarks`
|
||||
|
||||
`benchmarks:run`. A [BetterBench](https://github.com/GGZ14/BetterBench) run against the token's own
|
||||
**running** deployment.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `kind` | `run` (default) or `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) |
|
||||
| `deploymentId`, `deploymentBId` | Own, running deployments |
|
||||
| `quick` | `true`: 5 passes, a smoke check; default `false`: 20 passes, comparable |
|
||||
| `passes`, `phases` | Optional: passes per category; phases `decode`, `prefill`, `concurrency` (default all) |
|
||||
| `label`, `description` | Optional; the description goes into the report and the launch80 preview |
|
||||
|
||||
Answers `201` with `state` `pending_approval` (default) or `queued`, and the run's time limit.
|
||||
|
||||
#### `GET /api/v1/benchmarks/{id}[?wait=S][&full=1]`, `GET /api/v1/benchmarks[?deployment=&requested_by=&limit=]`
|
||||
|
||||
`benchmarks:read`. Compact result:
|
||||
|
||||
```json
|
||||
{ "id": "01M…", "kind": "run", "state": "completed", "label": "q8_0 KV", "mine": true,
|
||||
"headline": { "decodeTps": 61.3, "prefillTps": 1840, "prefillDepth": 16000, "ttftMs": 92, "peakParallelTps": 155.2, "peakParallelLevel": 8 },
|
||||
"setup": { "gpus": "1× Intel Arc Pro B65 (32 GiB)", "pcie": "Gen5 x8 of Gen5 x16", "p2p": "n/a", "rebar": "on",
|
||||
"engine": "llama.cpp b11541-f2918cabb", "image": "ghcr.io/ggml-org/llama.cpp:server-intel", "digest": "sha256:…",
|
||||
"model": "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache", "ctx": "16,384", "concurrency": "4" },
|
||||
"resources": { "cpuAvgCores": 1.1, "ramPeakBytes": 2100000000,
|
||||
"gpus": [{ "name": "Intel Arc Pro B65", "vramPeakMb": 9100, "vramTotalMb": 32768, "utilAvg": 88.5, "powerAvgW": 151.2, "tempPeakC": 71 }] },
|
||||
"error": null, "next": "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…" }
|
||||
```
|
||||
|
||||
`?full=1` adds BetterBench's complete summary (per category, per prompt depth, per concurrency
|
||||
level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence interval).
|
||||
`POST /api/v1/benchmarks/{id}/cancel` cancels an own run.
|
||||
|
||||
#### `GET /api/v1/benchmarks/compare?ids=a,b,…`
|
||||
|
||||
`benchmarks:read`. 2–16 runs: headline numbers side by side, the setup values that differ per run
|
||||
(`differs`) and the ones they share (`same`).
|
||||
|
||||
#### `POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}[?wait=S]`, `POST /api/v1/sweeps/{id}/cancel`
|
||||
|
||||
`benchmarks:run` / `benchmarks:read`. One or two settings varied from an own base deployment, e.g.
|
||||
`{"baseDeploymentId": "…", "params": [{"key": "kvCache", "values": ["f16", "q8_0"]}], "quick": true}`.
|
||||
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
|
||||
`flashAttn`, `cacheRamMb`, `gpuLayers`, `dtype`, `maxNumSeqs`, `kvCacheGb`, `gpuMemoryUtilization`,
|
||||
`cpus` (per engine, as in the UI). Each variant is deployed, benchmarked and removed again. The
|
||||
answer lists every variant with its headline numbers and setup.
|
||||
|
||||
## Waiting instead of polling
|
||||
|
||||
Every status call costs an agent a round of its context. The status endpoints (`/jobs/{id}`,
|
||||
`/deployments/{id}`, `/benchmarks/{id}`, `/sweeps/{id}`) take `?wait=S` (seconds, at most 900): the
|
||||
request is held until the state is settled (finished, running, failed, cancelled) or the time is up,
|
||||
then answers with the current state plus `waitedSeconds` and `timedOut`. Something that waits for the
|
||||
user's approval answers right away: there is nothing to wait for. Use one waiting call instead of a
|
||||
polling loop, with a wait shorter than your HTTP client's timeout (and any proxy's).
|
||||
|
||||
## Guardrails
|
||||
|
||||
### Downloads
|
||||
|
||||
Settings → API tokens → **Guardrails for API downloads**. They apply to every token together;
|
||||
downloads started in the UI aren't affected.
|
||||
|
||||
| Setting | Default | Rejection |
|
||||
| --- | --- | --- |
|
||||
| Approval | **Ask me**: requests wait as *pending approval* until you approve or reject them on the model or job page | (not an error; `state: pending_approval`) |
|
||||
| Max size per request | 60 GB | `422 too_large` |
|
||||
| Keep free on the models folder | 100 GB, after the download and after what other open downloads still need | `507 disk_space` (`503 disk_unknown` if the worker is offline) |
|
||||
| Agent jobs at once | 2 (pending approval, queued or running) | `429 too_many_jobs` |
|
||||
| Allowed authors | empty = any; e.g. `unsloth, ggml-org, Qwen` (case-insensitive) | `403 author_not_allowed` |
|
||||
|
||||
Rejecting a request cancels its job. A model that only that request added leaves the library again;
|
||||
for a request that added files to an existing model, the previous selection is restored.
|
||||
|
||||
### Deployments and benchmarks
|
||||
|
||||
Settings → API tokens → **Guardrails for API deployments and benchmarks**, for every token together:
|
||||
|
||||
| Setting | Default | Rejection |
|
||||
| --- | --- | --- |
|
||||
| Approval | **Ask me**: starts, runs and sweeps wait as *pending approval* on the deployment, run or sweep page. Creating or editing a stopped deployment, stopping and deleting own ones need none. | (not an error) |
|
||||
| Agent deployments at once | 1 (running, starting or waiting to start); 2 for A/B runs | `429 too_many_deployments` |
|
||||
| One GPU job at a time | No agent start while an agent run or sweep is pending or running, or another agent deployment is still loading; one agent run or sweep at a time; no sweep while an agent deployment runs (the sweep deploys its variants itself) | `429 gpu_busy` |
|
||||
| Max minutes per run / sweep | 30 / 180, then the worker stops it | (`failed` with the reason) |
|
||||
| Max variants per sweep | 8 | `422 too_many_variants` |
|
||||
| Runtimes | Any with a pulled image, or an allowlist | `403 runtime_not_allowed`, `409 runtime_not_pulled` |
|
||||
| Extra arguments | Tuning flags only, per engine (editable list); values can't be paths or URLs | `403 arg_not_allowed`, naming the argument |
|
||||
| Host ports | None (Kaname reaches deployments over the Docker network), or a range | `403 port_not_allowed` |
|
||||
| Memory / CPU caps | The host's size, or what you set; agent deployments always get a memory limit (the estimate if they don't give one) | `422 limit_exceeded` |
|
||||
| Own deployments only | Agents change and benchmark only what their token created | `403 not_owner` |
|
||||
|
||||
Docker options (devices, volumes, privileges, capabilities, network) are never arguments: they belong
|
||||
to the runtime, which tokens can't change.
|
||||
|
||||
### Protected deployments
|
||||
|
||||
The **Protect** button on a deployment's page: agents can't edit, start, stop, delete or benchmark
|
||||
it, and can't start a deployment on the same GPUs if the estimated VRAM of everything running there
|
||||
plus the new one (and 1 GiB to spare) exceeds the GPUs' VRAM (`409 vram_protected`). When the need
|
||||
can't be estimated (only some layers on the GPU), such a start is refused too.
|
||||
|
||||
### Activity
|
||||
|
||||
Settings → API tokens → **Activity** next to each token lists what it did: every request that
|
||||
creates or changes something, waits for approval, or was refused (with the error code).
|
||||
|
||||
## Behind a forward-auth proxy (Traefik)
|
||||
|
||||
If Kaname sits behind forward auth (e.g. Traefik with Tinyauth or Pocket ID), the proxy would answer
|
||||
API calls with a login redirect. Let `/api/v1/` through without forward auth; Kaname checks the
|
||||
bearer token itself there. Everything else keeps forward auth.
|
||||
|
||||
Two routers for the same host, the API one with a higher priority and no auth middleware:
|
||||
|
||||
```yaml
|
||||
# docker compose labels on the kaname "web" service
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.services.kaname.loadbalancer.server.port=3000
|
||||
|
||||
# UI and internal API: forward auth as before
|
||||
- traefik.http.routers.kaname.rule=Host(`models.example.com`)
|
||||
- traefik.http.routers.kaname.entrypoints=websecure
|
||||
- traefik.http.routers.kaname.tls=true
|
||||
- traefik.http.routers.kaname.middlewares=tinyauth
|
||||
- traefik.http.routers.kaname.service=kaname
|
||||
|
||||
# Token API: no forward auth (bearer tokens are checked by Kaname)
|
||||
- traefik.http.routers.kaname-api.rule=Host(`models.example.com`) && PathPrefix(`/api/v1/`)
|
||||
- traefik.http.routers.kaname-api.entrypoints=websecure
|
||||
- traefik.http.routers.kaname-api.tls=true
|
||||
- traefik.http.routers.kaname-api.priority=100
|
||||
- traefik.http.routers.kaname-api.service=kaname
|
||||
```
|
||||
|
||||
The same in a file provider:
|
||||
|
||||
```yaml
|
||||
http:
|
||||
routers:
|
||||
kaname-api:
|
||||
rule: Host(`models.example.com`) && PathPrefix(`/api/v1/`)
|
||||
entryPoints: [websecure]
|
||||
tls: {}
|
||||
priority: 100
|
||||
service: kaname
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- Use `PathPrefix(`/api/v1/`)` with the trailing slash, so nothing else that starts with `/api/v1`
|
||||
slips past forward auth. Kaname's own login gate also excludes exactly `/api/v1` and `/api/v1/…`.
|
||||
- Don't exempt `/api` as a whole: the internal routes rely on the login session.
|
||||
- Agents on the same network can also call Kaname directly (`http://<host>:3000/api/v1/…`) without
|
||||
going through the proxy.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 705 KiB |
@@ -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;
|
||||
@@ -0,0 +1,2 @@
|
||||
CREATE INDEX `benchmark_runs_state_idx` ON `benchmark_runs` (`state`,`created_at`);--> statement-breakpoint
|
||||
CREATE INDEX `jobs_finished_idx` ON `jobs` (`finished_at`);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `models` ADD `source` text DEFAULT 'hub' NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `local_folders` ADD `readme` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `local_readme` text;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -141,6 +141,55 @@
|
||||
"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
|
||||
},
|
||||
{
|
||||
"idx": 24,
|
||||
"version": "6",
|
||||
"when": 1793567055573,
|
||||
"tag": "0024_polling_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 25,
|
||||
"version": "6",
|
||||
"when": 1794093022425,
|
||||
"tag": "0025_local_models",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 26,
|
||||
"version": "6",
|
||||
"when": 1794093954553,
|
||||
"tag": "0026_local_readme",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,6 +15,27 @@ const eslintConfig = defineConfig([
|
||||
// Bundled worker output
|
||||
"dist/**",
|
||||
]),
|
||||
// A value import from the schema in a client component puts drizzle-orm and every table
|
||||
// definition into the browser bundle. Enums are in @/lib/db/enums; types are fine. Pages, layouts
|
||||
// and route handlers run on the server only.
|
||||
{
|
||||
files: ["src/components/**/*.{ts,tsx}", "src/hooks/**/*.{ts,tsx}", "src/app/**/*.{ts,tsx}"],
|
||||
ignores: ["src/app/**/page.tsx", "src/app/**/layout.tsx", "src/app/**/route.ts"],
|
||||
rules: {
|
||||
"@typescript-eslint/no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
paths: [
|
||||
{
|
||||
name: "@/lib/db/schema",
|
||||
allowTypeImports: true,
|
||||
message: "In client code this bundles drizzle-orm and every table. Import enums from @/lib/db/enums.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -3,6 +3,14 @@ import type { NextConfig } from "next";
|
||||
const nextConfig: NextConfig = {
|
||||
// Native SQLite driver: load from node_modules at runtime instead of bundling.
|
||||
serverExternalPackages: ["@libsql/client", "libsql"],
|
||||
// The Docker image runs the standalone server: only the files the server needs instead of all of
|
||||
// node_modules (see Dockerfile). Local `next build` / `next start` stay as they are.
|
||||
output: process.env.NEXT_OUTPUT === "standalone" ? "standalone" : undefined,
|
||||
// Nothing uses next/image (model cards show the Hub's images as they are). With the optimizer off
|
||||
// (/_next/image answers 404), sharp and its native libvips (28 MB) stay out of the standalone
|
||||
// output; "next-server" is the key Next applies to its own server's trace.
|
||||
images: { unoptimized: true },
|
||||
outputFileTracingExcludes: { "next-server": ["**/node_modules/sharp/**/*", "**/node_modules/@img/**/*"] },
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+389
-5
File diff suppressed because it is too large.
Load diff
+4
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.13.0",
|
||||
"version": "0.20.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
@@ -14,7 +14,7 @@
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
|
||||
"test": "tsx --conditions=react-server --test \"src/**/*.test.ts\"",
|
||||
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs"
|
||||
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --external:@libsql/client --external:libsql --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --external:@libsql/client --external:libsql --outfile=dist/migrate.mjs && esbuild src/sandbox/index.ts --bundle --platform=node --target=node24 --format=esm --external:@libsql/client --external:libsql --outfile=dist/sandbox.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
@@ -33,9 +33,7 @@
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"server-only": "^0.0.1",
|
||||
"shadcn": "^4.21.1",
|
||||
"sonner": "^2.0.8",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"ulid": "^3.0.2",
|
||||
"zod": "^4.6.5"
|
||||
},
|
||||
@@ -51,8 +49,10 @@
|
||||
"esbuild": "^0.25.12",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.3.8",
|
||||
"shadcn": "^4.21.1",
|
||||
"tailwindcss": "^4",
|
||||
"tsx": "^4.23.15",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Read-only diagnostics for Intel GPU support (Arc / Arc Pro B-series) on a Kaname host.
|
||||
# Shows which telemetry sources this kernel and driver offer, so Kaname uses ones that exist.
|
||||
# Changes nothing. Run it on the Docker host (or VM) that has the GPU:
|
||||
#
|
||||
# bash scripts/intel-probe.sh # as your user: what an unprivileged container can see
|
||||
# sudo bash scripts/intel-probe.sh # adds lspci's link/ReBAR capability details
|
||||
#
|
||||
# Paste the output back. It contains no hostname, IP addresses or user names.
|
||||
|
||||
set -u
|
||||
section() { printf '\n=== %s ===\n' "$1"; }
|
||||
show() { [ -e "$1" ] && printf '%s: %s\n' "$1" "$(tr '\n' ' ' < "$1" 2>/dev/null || echo '(not readable)')"; }
|
||||
|
||||
section "System"
|
||||
echo "kernel: $(uname -r)"
|
||||
grep -E '^(PRETTY_NAME|VERSION_ID)=' /etc/os-release 2>/dev/null
|
||||
command -v systemd-detect-virt >/dev/null && echo "virt: $(systemd-detect-virt 2>/dev/null)"
|
||||
show /sys/class/dmi/id/sys_vendor
|
||||
show /sys/class/dmi/id/product_name
|
||||
echo "running as uid $(id -u)"
|
||||
|
||||
section "Intel display devices"
|
||||
gpus=()
|
||||
for d in /sys/bus/pci/devices/*; do
|
||||
[ "$(cat "$d/vendor" 2>/dev/null)" = "0x8086" ] || continue
|
||||
case "$(cat "$d/class" 2>/dev/null)" in 0x03*) gpus+=("$(basename "$d")") ;; esac
|
||||
done
|
||||
[ ${#gpus[@]} -eq 0 ] && echo "no Intel GPU found on the PCI bus"
|
||||
|
||||
for a in "${gpus[@]}"; do
|
||||
d=$(readlink -f "/sys/bus/pci/devices/$a")
|
||||
section "GPU $a"
|
||||
echo "sysfs path: $d"
|
||||
show "$d/device"
|
||||
show "$d/subsystem_device"
|
||||
echo "driver: $(basename "$(readlink "$d/driver" 2>/dev/null)" 2>/dev/null)"
|
||||
command -v lspci >/dev/null && lspci -nn -s "$a"
|
||||
echo "-- link per level (GPU up to the root port):"
|
||||
p=$d
|
||||
while [[ $(basename "$p") =~ ^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$ ]]; do
|
||||
printf '%s vendor=%s cur=%s x%s max=%s x%s\n' "$(basename "$p")" "$(cat "$p/vendor" 2>/dev/null)" \
|
||||
"$(cat "$p/current_link_speed" 2>/dev/null)" "$(cat "$p/current_link_width" 2>/dev/null)" \
|
||||
"$(cat "$p/max_link_speed" 2>/dev/null)" "$(cat "$p/max_link_width" 2>/dev/null)"
|
||||
p=$(dirname "$p")
|
||||
done
|
||||
echo "-- BARs (start end flags):"
|
||||
head -6 "$d/resource" 2>/dev/null
|
||||
echo "-- VRAM / memory files:"
|
||||
find "$d" -maxdepth 3 \( -iname '*vram*' -o -iname '*lmem*' -o -iname '*mem_info*' \) 2>/dev/null | while read -r f; do
|
||||
[ -f "$f" ] && show "$f"
|
||||
done
|
||||
ls "$d/tile0" 2>/dev/null | head -30
|
||||
echo "-- hwmon:"
|
||||
for h in "$d"/hwmon/hwmon*; do
|
||||
[ -d "$h" ] || continue
|
||||
show "$h/name"
|
||||
for f in "$h"/*_input "$h"/*_label "$h"/*_crit "$h"/power*_max; do [ -f "$f" ] && show "$f"; done
|
||||
done
|
||||
if [ "$(id -u)" = 0 ] && command -v lspci >/dev/null; then
|
||||
echo "-- lspci capabilities:"
|
||||
lspci -vvv -s "$a" | grep -E 'LnkCap:|LnkSta:|Resizable BAR|BAR [0-9]: current size|Region'
|
||||
fi
|
||||
done
|
||||
|
||||
section "/dev/dri"
|
||||
ls -ln /dev/dri 2>/dev/null
|
||||
for n in /dev/dri/renderD*; do [ -e "$n" ] && echo "$n gid=$(stat -c %g "$n") group=$(stat -c %G "$n")"; done
|
||||
getent group render video | cut -d: -f1,3
|
||||
|
||||
section "DRM fdinfo (per-process VRAM / engine time)"
|
||||
found=0
|
||||
for f in /proc/[0-9]*/fdinfo/*; do
|
||||
grep -q '^drm-driver:' "$f" 2>/dev/null || continue
|
||||
found=1
|
||||
echo "readable example: $f"
|
||||
grep -E '^drm-(driver|client-id|engine-|cycles-|total-cycles-|memory-|total-|resident-)' "$f" | head -25
|
||||
break
|
||||
done
|
||||
[ $found = 0 ] && echo "no readable DRM fdinfo (no GPU process running, or not permitted for this user)"
|
||||
|
||||
section "Tools"
|
||||
for t in xpu-smi intel_gpu_top clinfo sycl-ls vulkaninfo docker; do
|
||||
printf '%s: %s\n' "$t" "$(command -v "$t" || echo missing)"
|
||||
done
|
||||
command -v docker >/dev/null && docker version --format 'docker server {{.Server.Version}}' 2>/dev/null
|
||||
@@ -59,7 +59,7 @@ export function DeleteModelButton({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
className="border-foreground/20 bg-background/90 font-medium text-red-600 shadow-xs backdrop-blur-sm hover:bg-destructive/15 hover:text-red-600 dark:border-foreground/20 dark:bg-background/90 dark:text-red-400 dark:hover:bg-destructive/25 dark:hover:text-red-300"
|
||||
/>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { ApprovalBar } from "@/components/approval-bar";
|
||||
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
|
||||
import { JobProgress, JobStateBadge } from "@/components/job-progress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -24,19 +22,20 @@ export function DownloadCard({
|
||||
modelId,
|
||||
status,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
status: ModelStatus;
|
||||
/** The repo or pinned commit is gone from the Hub; no new downloads. */
|
||||
hubMissing: boolean;
|
||||
/** A local model (no Hub repo): nothing to download or repair, no hashes to deep-verify against. */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const { snapshot } = useLive({ model: modelId });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const jobs = snapshot?.jobs ?? [];
|
||||
const latest = jobs[0];
|
||||
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
|
||||
const pending = latest?.state === "pending_approval" ? latest : undefined;
|
||||
const router = useRouter();
|
||||
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
|
||||
// The newest verify, unless a download ran after it (its result would be stale).
|
||||
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
|
||||
@@ -62,16 +61,16 @@ export function DownloadCard({
|
||||
: latest?.state === "failed" && latest.kind === "download"
|
||||
? "Retry"
|
||||
: "Download missing";
|
||||
const canDownload = !open && !pending && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !pending && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !pending && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
const canDownload = !open && !local && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && (!neverRan || local) && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !local && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
|
||||
let hint = "Downloads the selected files at the pinned commit.";
|
||||
if (pending) hint = "Requested through the API; waits for your approval.";
|
||||
else if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
let hint = local ? "A local folder: Kaname keeps its files as they are." : "Downloads the selected files at the pinned commit.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
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 (local && (verifyProblems > 0 || status === "incomplete")) hint = "Some files are missing or changed. A local model can't be repaired from the Hub.";
|
||||
else if (status === "ready") hint = "All selected files are present.";
|
||||
|
||||
const showProgress =
|
||||
@@ -82,15 +81,13 @@ export function DownloadCard({
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
|
||||
<DownloadIcon className="size-4 text-muted-foreground" />
|
||||
{open ? jobLabel(open) : "Download"}
|
||||
{open ? jobLabel(open) : local ? "Files" : "Download"}
|
||||
</h3>
|
||||
{latest && <JobStateBadge job={latest} />}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
|
||||
{pending && <ApprovalBar job={pending} onRemoved={() => router.push("/")} />}
|
||||
|
||||
{showProgress && !pending && <JobProgress job={latest} compact />}
|
||||
{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">
|
||||
@@ -152,15 +149,17 @@ export function DownloadCard({
|
||||
<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>
|
||||
{!local && (
|
||||
<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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -121,7 +121,7 @@ export function FilesHeader({
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
|
||||
· {formatBytes(totalBytes)} · {sha ? `commit ${shortSha(sha)}` : "local folder"}
|
||||
</span>
|
||||
</span>
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -17,6 +17,7 @@ import { formatBytes } from "@/lib/format";
|
||||
import { type FileGroup, groupSplitFiles } from "@/lib/file-groups";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FilesHeader } from "./download-more";
|
||||
import { RemoveFileButton } from "./remove-file-button";
|
||||
|
||||
type FileRow = { id: string; path: string; size: number; lfsSha256: string | null; state: ModelFileState };
|
||||
|
||||
@@ -67,20 +68,20 @@ function entryState(e: Entry): { state: ModelFileState; label: string } {
|
||||
|
||||
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
|
||||
|
||||
function Row({ entry, href, muted, showState }: { entry: Entry; href: string; muted?: boolean; showState: boolean }) {
|
||||
function Row({ entry, href, muted, showState, action }: { entry: Entry; href?: string; muted?: boolean; showState: boolean; action?: React.ReactNode }) {
|
||||
const { state: stateKey, label } = entryState(entry);
|
||||
const state = STATE[stateKey];
|
||||
const split = entry.totalParts > 1;
|
||||
return (
|
||||
<li>
|
||||
<li className="flex items-center pr-3">
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
target={href ? "_blank" : undefined}
|
||||
rel={href ? "noreferrer" : undefined}
|
||||
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
|
||||
className={cn(
|
||||
// Fixed status column so sizes line up between selected and unselected rows.
|
||||
"grid grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_7.5rem]",
|
||||
"grid min-w-0 flex-1 grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 py-2.5 pr-2 pl-5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_7.5rem]",
|
||||
muted && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
@@ -109,6 +110,7 @@ function Row({ entry, href, muted, showState }: { entry: Entry; href: string; mu
|
||||
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(entry.size)}</span>
|
||||
)}
|
||||
</a>
|
||||
<span className="flex w-7 shrink-0 justify-end">{action}</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -123,6 +125,7 @@ export function FilesTab({
|
||||
freeBytes,
|
||||
busy,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
repoId: string;
|
||||
@@ -132,10 +135,13 @@ export function FilesTab({
|
||||
freeBytes: number | null;
|
||||
busy: boolean;
|
||||
hubMissing: boolean;
|
||||
/** A local model (no Hub repo): files don't link anywhere. */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const hub = `https://huggingface.co/${repoId}`;
|
||||
// Split files link to their folder (all parts), single files to the file itself.
|
||||
const href = (e: Entry) => {
|
||||
if (local) return undefined;
|
||||
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
|
||||
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
|
||||
};
|
||||
@@ -163,7 +169,22 @@ export function FilesTab({
|
||||
|
||||
<ul className="divide-y">
|
||||
{selectedEntries.map((e) => (
|
||||
<Row key={e.path} entry={e} href={href(e)} showState />
|
||||
<Row
|
||||
key={e.path}
|
||||
entry={e}
|
||||
href={href(e)}
|
||||
showState
|
||||
action={
|
||||
<RemoveFileButton
|
||||
modelId={modelId}
|
||||
name={e.path.split("/").pop()!}
|
||||
paths={e.parts.map((p) => p.path)}
|
||||
size={e.size}
|
||||
disabled={busy || selectedEntries.length < 2}
|
||||
reason={busy ? "Wait until the current job has finished." : "The model's only file: delete the model instead."}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import "server-only";
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
|
||||
import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { shortSha } from "@/lib/format";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
|
||||
// Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts,
|
||||
// styles or event handlers, only the tags/attributes GitHub-style READMEs normally use.
|
||||
@@ -17,9 +22,84 @@ const schema = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
|
||||
const base = `https://huggingface.co/${repoId}`;
|
||||
/**
|
||||
* The Model card tab: the README at the pinned commit, fetched from the Hub (cached per commit).
|
||||
* Rendered inside a Suspense boundary, so the rest of the page doesn't wait for the Hub.
|
||||
*/
|
||||
export async function ModelCardSection({ repoId, sha }: { repoId: string; sha: string }) {
|
||||
const hub = `https://huggingface.co/${repoId}`;
|
||||
const card = await fetchModelCard(repoId, sha).catch(() => undefined);
|
||||
if (!card) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
|
||||
<a href={hub} target="_blank" rel="noreferrer" className="underline">
|
||||
Open on Hugging Face
|
||||
</a>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<ModelCard markdown={card} repoId={repoId} sha={sha} />
|
||||
<div className="mt-6 flex justify-end">
|
||||
<a
|
||||
href={`${hub}/blob/${sha}/README.md`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
README.md @ {shortSha(sha)}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Model card tab of a local model: the folder's README.md, as the worker last read it. Relative
|
||||
* images and links are dropped: the web app can't serve files from the models folder.
|
||||
*/
|
||||
export function LocalModelCardSection({ markdown, localPath }: { markdown: string | null; localPath: string }) {
|
||||
if (!markdown) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This folder has no README.md. Add one to <code className="font-mono">{localPath}</code> and it shows up here after the
|
||||
next scan of the models folder.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<ModelCard markdown={markdown} />
|
||||
<p className="mt-6 text-right text-xs text-muted-foreground">
|
||||
README.md in <code className="font-mono">{localPath}</code>, as of the last scan
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelCardSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3" aria-busy="true" aria-label="Loading the model card">
|
||||
<Skeleton className="h-7 w-2/5" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-11/12" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
<Skeleton className="mt-3 h-5 w-1/4" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a repo's README like the Hub: relative links/images point at the pinned commit. Without a
|
||||
* repo (a local model's README) they are dropped.
|
||||
*/
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId?: string; sha?: string }) {
|
||||
const base = repoId ? `https://huggingface.co/${repoId}` : null;
|
||||
return (
|
||||
<article className="prose prose-sm max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-img:inline-block prose-img:my-1 prose-pre:bg-muted prose-pre:text-foreground prose-table:text-xs">
|
||||
<ReactMarkdown
|
||||
@@ -29,6 +109,7 @@ export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId:
|
||||
const safe = defaultUrlTransform(url);
|
||||
if (!safe || safe.startsWith("#") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(safe)) return safe;
|
||||
// Relative path inside the repo: images from /resolve, links to /blob, both at the pinned SHA.
|
||||
if (!base) return null;
|
||||
const path = safe.replace(/^\.?\//, "");
|
||||
return key === "src" ? `${base}/resolve/${sha}/${path}` : `${base}/blob/${sha}/${path}`;
|
||||
}}
|
||||
|
||||
@@ -2,15 +2,13 @@ import {
|
||||
ArrowDownIcon,
|
||||
BoxIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FileTextIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
LanguagesIcon,
|
||||
ListChecksIcon,
|
||||
MessagesSquareIcon,
|
||||
PlusIcon,
|
||||
RocketIcon,
|
||||
GaugeIcon,
|
||||
ScaleIcon,
|
||||
SparklesIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -18,17 +16,17 @@ import {
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
import { DeploymentStateBadge } from "@/components/deployment-state";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { HubStateBadge } from "@/components/hub-state-badge";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { ModelStatusBadge } from "@/components/model-status-badge";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { targetName } from "@/lib/benchmark-view";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
import { getModelByRepo, relatedModels } from "@/lib/library";
|
||||
@@ -40,7 +38,7 @@ import { DownloadCard } from "./download-card";
|
||||
import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCard } from "./model-card";
|
||||
import { LocalModelCardSection, ModelCardSection, ModelCardSkeleton } from "./model-card";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
@@ -95,6 +93,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const { model, files } = data;
|
||||
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
|
||||
|
||||
// A local model has no Hub repo: no commit, Hub checks or model tree; its README is the model card.
|
||||
const local = model.source === "local";
|
||||
const tab: TabId = TABS.some((t) => t.id === sp.tab) ? (sp.tab as TabId) : "files";
|
||||
const [author, name] = model.repoId.split("/");
|
||||
const hub = `https://huggingface.co/${model.repoId}`;
|
||||
@@ -102,17 +102,14 @@ 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, recentJobs, byModel, deployable] = await Promise.all([
|
||||
// The model card (a Hub request) isn't awaited here: it streams in behind its Suspense boundary.
|
||||
const [tags, related, 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),
|
||||
deploymentsByModel(),
|
||||
listDeployableModels(),
|
||||
listBenchmarks({ modelId: model.id }, { limit: 5 }), // the sidebar shows 5 and links to all
|
||||
]);
|
||||
const modelDeployments = byModel.get(model.id) ?? [];
|
||||
const canDeploy = deployable.some((m) => m.id === model.id);
|
||||
const update =
|
||||
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
|
||||
? model.updateDiff
|
||||
@@ -133,45 +130,48 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const tabHref = (id: TabId) => (id === "files" ? `/${model.repoId}` : `/${model.repoId}?tab=${id}`);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Header card, styled after the Hugging Face model page */}
|
||||
<Panel className="flex flex-col gap-4 p-5">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
|
||||
<PageHero
|
||||
painting={{ view: 0.5, focus: [0.48, 0.42], anchor: [0.72, 0.35] }}
|
||||
title={
|
||||
<span className="flex flex-wrap items-center gap-x-2 gap-y-2">
|
||||
<Avatar url={model.authorAvatarUrl} name={author} />
|
||||
<Link href={`/?author=${encodeURIComponent(author)}`} className="text-muted-foreground hover:text-foreground hover:underline">
|
||||
<Link href={`/?author=${encodeURIComponent(author)}`} className="font-normal text-muted-foreground hover:text-foreground hover:underline">
|
||||
{author}
|
||||
</Link>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<h1 className="text-xl font-semibold break-all">{name}</h1>
|
||||
<CopyButton value={model.repoId} label="Copy repo ID" />
|
||||
<span className="font-normal text-muted-foreground">/</span>
|
||||
<span className="break-all">{name}</span>
|
||||
<CopyButton value={model.repoId} label={local ? "Copy name" : "Copy repo ID"} />
|
||||
{!local && (
|
||||
<a
|
||||
href={hub}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title="Open on Hugging Face"
|
||||
aria-label="Open on Hugging Face"
|
||||
className="inline-flex size-7 items-center justify-center rounded-md text-base font-normal hover:bg-muted"
|
||||
>
|
||||
🤗
|
||||
</a>
|
||||
)}
|
||||
<ModelStatusBadge status={model.status} />
|
||||
{local && (
|
||||
<span
|
||||
title="A folder in the models folder without a Hugging Face repo"
|
||||
className="inline-flex h-5 items-center rounded-4xl border border-foreground/15 bg-background/80 px-2 text-xs font-medium text-muted-foreground"
|
||||
>
|
||||
local
|
||||
</span>
|
||||
)}
|
||||
<HubStateBadge state={model.hubState} />
|
||||
<RequestedByBadge name={model.requestedBy} />
|
||||
{update && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
|
||||
update available
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{canDeploy && (
|
||||
<Link
|
||||
href={`/deployments/new?model=${model.id}`}
|
||||
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
|
||||
>
|
||||
<RocketIcon />
|
||||
Deploy
|
||||
</Link>
|
||||
)}
|
||||
<DeleteModelButton
|
||||
id={model.id}
|
||||
repoId={model.repoId}
|
||||
localPath={model.localPath}
|
||||
mayHaveFiles={model.status !== "pending" || recentJobs.length > 0}
|
||||
/>
|
||||
<ExternalButton href={hub}>🤗 Hugging Face</ExternalButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</span>
|
||||
}
|
||||
extra={
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{model.pipelineTag && (
|
||||
<Pill icon={MessagesSquareIcon} accent>
|
||||
@@ -194,11 +194,12 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Your tags</span>
|
||||
<span className="text-xs font-medium text-foreground/85">Your tags</span>
|
||||
<TagEditor modelId={model.id} tags={tags} />
|
||||
</div>
|
||||
|
||||
</Panel>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
|
||||
{hubMissing && (
|
||||
<div className="flex flex-wrap items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
|
||||
@@ -253,32 +254,22 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<DeleteModelButton
|
||||
id={model.id}
|
||||
repoId={model.repoId}
|
||||
localPath={model.localPath}
|
||||
mayHaveFiles={model.status !== "pending" || recentJobs.length > 0}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{tab === "card" && (
|
||||
<div className="p-5 sm:p-6">
|
||||
{card ? (
|
||||
<>
|
||||
<ModelCard markdown={card} repoId={model.repoId} sha={model.pinnedSha} />
|
||||
<div className="mt-6 flex justify-end">
|
||||
<a
|
||||
href={`${hub}/blob/${model.pinnedSha}/README.md`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
README.md @ {shortSha(model.pinnedSha)}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
{local ? (
|
||||
<LocalModelCardSection markdown={model.localReadme} localPath={model.localPath} />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
|
||||
<a href={hub} target="_blank" rel="noreferrer" className="underline">
|
||||
Open on Hugging Face
|
||||
</a>
|
||||
</p>
|
||||
<Suspense fallback={<ModelCardSkeleton />}>
|
||||
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -292,6 +283,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
|
||||
busy={model.status === "downloading"}
|
||||
hubMissing={hubMissing}
|
||||
local={local}
|
||||
/>
|
||||
)}
|
||||
{tab === "jobs" && (
|
||||
@@ -303,31 +295,29 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
<aside className="flex flex-col gap-4">
|
||||
<SideCard>
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} local={local} />
|
||||
</SideCard>
|
||||
|
||||
{(modelDeployments.length > 0 || canDeploy) && (
|
||||
<SideCard title="Deployments" icon={RocketIcon}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{modelDeployments.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
|
||||
) : (
|
||||
modelDeployments.map((d) => (
|
||||
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
|
||||
{runs.length > 0 && (
|
||||
<SideCard title="Benchmarks" icon={GaugeIcon}>
|
||||
<div className="flex flex-col gap-1">
|
||||
{runs.slice(0, 5).map((r) => {
|
||||
const h = r.headline;
|
||||
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">{d.name}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
|
||||
<span className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? (r.qualityScore != null ? `quality ${r.qualityScore}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
|
||||
</span>
|
||||
</span>
|
||||
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
</Link>
|
||||
))
|
||||
)}
|
||||
{canDeploy && (
|
||||
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
|
||||
<PlusIcon className="size-3.5" />
|
||||
New deployment
|
||||
</Link>
|
||||
)}
|
||||
);
|
||||
})}
|
||||
<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>
|
||||
)}
|
||||
@@ -338,6 +328,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd>{quants.length > 0 ? quants.join(", ") : `${selected.length} file${selected.length === 1 ? "" : "s"}`}</dd>
|
||||
<dt className="text-muted-foreground">Size</dt>
|
||||
<dd className="tabular-nums">{formatBytes(selectedBytes)}</dd>
|
||||
{local ? (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Source</dt>
|
||||
<dd>Local folder, no Hugging Face repo</dd>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Commit</dt>
|
||||
<dd className="flex items-center gap-1">
|
||||
<a href={`${hub}/commit/${model.pinnedSha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline" title={model.pinnedSha}>
|
||||
@@ -350,6 +347,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd>
|
||||
<LocalTime value={model.downloadedAt} />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Path</dt>
|
||||
<dd className="flex min-w-0 items-center gap-1">
|
||||
<span className="truncate font-mono text-xs" title={`$MODELS_DIR/${model.localPath}`}>
|
||||
@@ -369,6 +368,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd className="flex flex-col font-mono text-xs">{model.excludePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
|
||||
</>
|
||||
)}
|
||||
{!local && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">On the Hub</dt>
|
||||
<dd className="flex flex-col items-start gap-0.5">
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
|
||||
@@ -390,6 +391,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
|
||||
<HubCheckButton modelId={model.id} />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Added</dt>
|
||||
<dd>
|
||||
<LocalTime value={model.createdAt} />
|
||||
@@ -397,6 +400,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</dl>
|
||||
</SideCard>
|
||||
|
||||
{!local && (
|
||||
<SideCard title="Model tree" icon={SparklesIcon}>
|
||||
<ModelTree
|
||||
repoId={model.repoId}
|
||||
@@ -416,9 +420,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
</SideCard>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -448,9 +453,10 @@ function Pill({
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs",
|
||||
accent && "border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300",
|
||||
muted && "text-muted-foreground",
|
||||
// Own background: these sit on the painting in the page banner.
|
||||
"inline-flex items-center gap-1 rounded-full border border-foreground/15 bg-background/80 px-2.5 py-0.5 text-xs font-medium text-foreground backdrop-blur-sm",
|
||||
accent && "border-indigo-500/40 text-indigo-700 dark:text-indigo-300",
|
||||
muted && "font-normal text-foreground/80",
|
||||
)}
|
||||
>
|
||||
{Icon && <Icon className="size-3.5" />}
|
||||
@@ -459,18 +465,9 @@ function Pill({
|
||||
);
|
||||
}
|
||||
|
||||
function ExternalButton({ href, children }: { href: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<a href={href} target="_blank" rel="noreferrer" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}>
|
||||
{children}
|
||||
<ExternalLinkIcon className="opacity-60" />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
/** Card surface shared by header, content and sidebar. */
|
||||
function Panel({ className, children }: { className?: string; children: React.ReactNode }) {
|
||||
return <div className={cn("rounded-xl bg-card text-card-foreground ring-1 ring-foreground/10", className)}>{children}</div>;
|
||||
return <div className={cn("rounded-xl bg-card/55 text-card-foreground ring-1 ring-foreground/10 backdrop-blur-md", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
function SideCard({
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"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 { formatBytes } from "@/lib/format";
|
||||
|
||||
/** Remove one selected file (all parts of a split file) from the model and from disk. */
|
||||
export function RemoveFileButton({ modelId, name, paths, size, disabled, reason }: { modelId: string; name: string; paths: string[]; size: number; disabled: boolean; reason?: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`/api/models/${modelId}/files`, { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ remove: paths }) });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not remove (${res.status})`);
|
||||
toast.success(`Removing ${name}`);
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
disabled={disabled || busy}
|
||||
title={disabled ? reason : `Remove ${name}`}
|
||||
aria-label={`Remove ${name}`}
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Trash2Icon />
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove {name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{paths.length > 1 ? `All ${paths.length} parts (${formatBytes(size)})` : `The file (${formatBytes(size)})`} will be deleted from the models folder and taken out of
|
||||
this model's selection. The rest of the model stays. You can download it again later with Download more.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove}>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -175,6 +175,21 @@ export function AddModelForm({
|
||||
});
|
||||
}
|
||||
|
||||
/** Import without a Hub repo: every file in the folder, kept as it is. */
|
||||
async function addAsLocal() {
|
||||
if (!importFolder) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const { id } = await postJson<{ id: string }>("/api/models", { source: "local", localPath: importFolder.path });
|
||||
toast.success(`${importFolder.path} added as a local model`);
|
||||
onAdded(id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function addToLibrary() {
|
||||
if (!result) return;
|
||||
setSubmitting(true);
|
||||
@@ -241,6 +256,18 @@ export function AddModelForm({
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{importFolder && (
|
||||
<div className="mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t pt-4">
|
||||
<p className="min-w-0 flex-1 text-sm text-muted-foreground">
|
||||
<span className="font-medium text-foreground">Not on Hugging Face?</span> Add the folder as a local model: all{" "}
|
||||
{importFolder.fileCount} file{importFolder.fileCount === 1 ? "" : "s"} as they are, without Hub checks, updates or
|
||||
downloads.
|
||||
</p>
|
||||
<Button type="button" variant="outline" onClick={addAsLocal} disabled={submitting || loading}>
|
||||
{submitting ? "Adding…" : "Add as local model"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -10,24 +10,43 @@ import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AddModelForm, type ImportFolder } from "./add-model-form";
|
||||
|
||||
type Folder = ImportFolder & { totalBytes: number };
|
||||
/** A folder found by the scan, without its file list (fetched when you click Import). */
|
||||
type Folder = { path: string; commit: string | null; fileCount: number; totalBytes: number };
|
||||
|
||||
/** The "Add model" / "Close" toggle (shown in the library hero). */
|
||||
export function AddModelToggle({ open, onToggle }: { open: boolean; onToggle: () => void }) {
|
||||
return (
|
||||
<Button variant={open ? "outline" : "default"} onClick={onToggle}>
|
||||
{open ? "Close" : "Add model"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Library header with an "Add model" toggle that opens the lookup/selection form inline, and the
|
||||
* folders in the models folder that aren't in the library yet, each with "Import".
|
||||
* The lookup/selection form, opened inline by the "Add model" toggle, and the folders in the models
|
||||
* folder that aren't in the library yet, each with "Import".
|
||||
*/
|
||||
export function AddModelPanel({
|
||||
freeBytes,
|
||||
defaultOpen,
|
||||
folders,
|
||||
open,
|
||||
setOpen,
|
||||
}: {
|
||||
freeBytes: number | null;
|
||||
defaultOpen: boolean;
|
||||
folders: Folder[];
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
const [importing, setImporting] = useState<Folder | null>(null);
|
||||
const [importing, setImporting] = useState<ImportFolder | null>(null);
|
||||
// The folder whose file list is being fetched for Import.
|
||||
const [fetching, setFetching] = useState<string | null>(null);
|
||||
// Closed from outside (the toggle in the hero): forget the folder being imported.
|
||||
const [wasOpen, setWasOpen] = useState(open);
|
||||
if (open !== wasOpen) {
|
||||
setWasOpen(open);
|
||||
if (!open) setImporting(null);
|
||||
}
|
||||
const [scanning, setScanning] = useState(false);
|
||||
|
||||
function close() {
|
||||
@@ -35,6 +54,22 @@ export function AddModelPanel({
|
||||
setImporting(null);
|
||||
}
|
||||
|
||||
async function startImport(folder: Folder) {
|
||||
setFetching(folder.path);
|
||||
try {
|
||||
const res = await fetch(`/api/local-folders?path=${encodeURIComponent(folder.path)}`, { cache: "no-store" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast.error(body.error?.message ?? `Could not load the folder (${res.status})`);
|
||||
return;
|
||||
}
|
||||
setImporting(body as ImportFolder);
|
||||
setOpen(true);
|
||||
} finally {
|
||||
setFetching(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function rescan() {
|
||||
setScanning(true);
|
||||
try {
|
||||
@@ -53,12 +88,6 @@ export function AddModelPanel({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold">Library</h1>
|
||||
<Button variant={open ? "outline" : "default"} onClick={() => (open ? close() : setOpen(true))}>
|
||||
{open ? "Close" : "Add model"}
|
||||
</Button>
|
||||
</div>
|
||||
{open && (
|
||||
<AddModelForm
|
||||
key={importing?.path ?? "new"}
|
||||
@@ -79,7 +108,8 @@ export function AddModelPanel({
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{folders.length} folder{folders.length === 1 ? " isn't" : "s aren't"} in the library yet. Import matches
|
||||
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again.
|
||||
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again,
|
||||
or adds {folders.length === 1 ? "it" : "them"} as a local model if there is no Hub repo.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
|
||||
@@ -99,15 +129,8 @@ export function AddModelPanel({
|
||||
{f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)}
|
||||
{f.commit && <> · hf commit {shortSha(f.commit)}</>}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setImporting(f);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Import
|
||||
<Button size="sm" variant="outline" disabled={fetching != null} onClick={() => void startImport(f)}>
|
||||
{fetching === f.path ? "Loading…" : "Import"}
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { TriangleAlertIcon } from "lucide-react";
|
||||
import { BenchmarkResources } from "@/components/benchmark-resources";
|
||||
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib/ab-report";
|
||||
import { CONFIG_ROWS } from "@/lib/benchmark-view";
|
||||
import { 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";
|
||||
import type { RunRow } from "../benchmark-list";
|
||||
|
||||
const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
|
||||
|
||||
@@ -57,7 +56,7 @@ function Side({ label, name, value, unit }: { label: string; name: string; value
|
||||
);
|
||||
}
|
||||
|
||||
export function AbReport({ run }: { run: ListRow }) {
|
||||
export function AbReport({ run }: { run: RunRow }) {
|
||||
const ab = run.ab;
|
||||
const a = run.snapshot;
|
||||
const b = run.snapshotB;
|
||||
@@ -70,13 +69,13 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
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">
|
||||
<article className="flex flex-col gap-8 rounded-2xl bg-card/55 px-5 py-6 ring-1 ring-foreground/10 backdrop-blur-md sm:px-8 sm:py-8">
|
||||
<header className="flex flex-col gap-3">
|
||||
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
|
||||
BetterBench {ab.betterbenchVersion} · paired A/B · {ab.pairs} pairs
|
||||
</span>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${a.deploymentName} vs ${b.deploymentName}`}</h2>
|
||||
<p className="max-w-3xl text-sm leading-relaxed">{abSummaryText(ab, a.deploymentName, b.deploymentName)}</p>
|
||||
<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)]">
|
||||
@@ -99,8 +98,8 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
</section>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-4">
|
||||
<Side label="A · decode, mean" name={a.deploymentName} value={d.mean_a} unit="t/s" />
|
||||
<Side label="B · decode, mean" name={b.deploymentName} value={d.mean_b} unit="t/s" />
|
||||
<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>
|
||||
@@ -136,8 +135,8 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
<thead>
|
||||
<tr className="border-b text-left text-muted-foreground">
|
||||
<th className="px-3 py-2 font-medium" />
|
||||
<th className="px-3 py-2 font-medium">A · {a.deploymentName}</th>
|
||||
<th className="px-3 py-2 font-medium">B · {b.deploymentName}</th>
|
||||
<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>
|
||||
@@ -161,13 +160,6 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
{same.length > 0 && <p className="text-xs text-muted-foreground">Same on both: {same.map((x) => `${x.row.label.toLowerCase()} ${x.va}`).join(" · ")}.</p>}
|
||||
</section>
|
||||
|
||||
{run.resources && (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h3 className="text-base font-semibold">Resources</h3>
|
||||
<BenchmarkResources stats={run.resources} names={{ a: a.deploymentName, b: b.deploymentName }} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="flex flex-col gap-2">
|
||||
<h3 className="text-base font-semibold">Method</h3>
|
||||
<div className="flex max-w-3xl flex-col gap-2 text-sm text-muted-foreground">
|
||||
|
||||
@@ -31,13 +31,25 @@ import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
|
||||
import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
import { AgentApprovalBar } from "@/components/approval-bar";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import {
|
||||
CONFIG_ROWS,
|
||||
describeSettings,
|
||||
engineName,
|
||||
isEndpointSnapshot,
|
||||
modelName,
|
||||
targetName,
|
||||
} from "@/lib/benchmark-view";
|
||||
import type { RunRow } from "../benchmark-list";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { RunMetaCard } from "@/components/run-meta";
|
||||
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
|
||||
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";
|
||||
|
||||
@@ -56,13 +68,13 @@ function duration(a: string | null, b: string | null, now: number) {
|
||||
: `${Math.round(s)} s`;
|
||||
}
|
||||
|
||||
export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
export function BenchmarkDetail({ initial }: { initial: RunRow }) {
|
||||
const router = useRouter();
|
||||
const [r, setR] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [label, setLabel] = useState(initial.label ?? "");
|
||||
const [description, setDescription] = useState(initial.description ?? "");
|
||||
const active = r.state === "pending_approval" || r.state === "queued" || r.state === "running";
|
||||
const active = r.state === "queued" || r.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
@@ -77,13 +89,15 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
}, [active, r.id]);
|
||||
|
||||
async function again() {
|
||||
if (!r.deploymentId) return;
|
||||
if (!r.endpointId) return;
|
||||
const res = await fetch("/api/benchmarks", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
deploymentId: r.deploymentId,
|
||||
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
|
||||
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,
|
||||
@@ -98,183 +112,158 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
}
|
||||
|
||||
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"
|
||||
? `${s.deploymentName} vs ${r.snapshotB?.deploymentName}`
|
||||
: s.deploymentName)}
|
||||
</h1>
|
||||
{r.kind === "ab" && (
|
||||
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">
|
||||
A/B
|
||||
</span>
|
||||
)}
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
<RequestedByBadge name={r.requestedBy} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{r.deploymentId ? (
|
||||
<Link
|
||||
href={`/deployments/${r.deploymentId}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
{s.deploymentName}
|
||||
</Link>
|
||||
) : (
|
||||
`${s.deploymentName} (deleted)`
|
||||
)}{" "}
|
||||
·{" "}
|
||||
{r.modelId ? (
|
||||
<Link href={`/${s.repoId}`} className="hover:underline">
|
||||
{s.repoId}
|
||||
</Link>
|
||||
) : (
|
||||
s.repoId
|
||||
)}{" "}
|
||||
· {s.runtimeName}
|
||||
{r.kind === "ab" && r.snapshotB && (
|
||||
<>
|
||||
{" "}
|
||||
· B:{" "}
|
||||
{r.deploymentBId ? (
|
||||
<Link
|
||||
href={`/deployments/${r.deploymentBId}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
{r.snapshotB.deploymentName}
|
||||
</Link>
|
||||
) : (
|
||||
r.snapshotB.deploymentName
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{r.sweepId && (
|
||||
<>
|
||||
{" "}
|
||||
·{" "}
|
||||
<Link
|
||||
href={`/benchmarks/sweeps/${r.sweepId}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
part of a sweep
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
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>
|
||||
<PageHero
|
||||
painting={{ view: 0.6, focus: [0.25, 0.6], anchor: [0.65, 0.4] }}
|
||||
title={
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
{r.label ??
|
||||
(r.kind === "ab" && sB
|
||||
? `${targetName(s)} vs ${targetName(sB)}`
|
||||
: targetName(s))}
|
||||
{r.kind === "ab" && (
|
||||
<span className="rounded-md border px-1.5 text-xs font-normal text-muted-foreground">
|
||||
A/B
|
||||
</span>
|
||||
)}
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
</span>
|
||||
}
|
||||
description={
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<p>
|
||||
{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)})
|
||||
</>
|
||||
)}
|
||||
{r.state === "completed" && (
|
||||
<a
|
||||
href={`/api/benchmarks/${r.id}/results`}
|
||||
className={buttonVariants({ variant: "outline" })}
|
||||
>
|
||||
<DownloadIcon />
|
||||
{r.kind === "ab" ? "ab.json" : "results.json"}
|
||||
</a>
|
||||
)}
|
||||
{active ? (
|
||||
</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>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
{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"
|
||||
disabled={!!r.cancelRequestedAt}
|
||||
onClick={async () =>
|
||||
(await cancelBenchmark(r.id)) && router.refresh()
|
||||
}
|
||||
onClick={again}
|
||||
title="Queue a new run with the same settings against the same endpoint"
|
||||
>
|
||||
<SquareIcon />
|
||||
Cancel
|
||||
<RotateCcwIcon />
|
||||
Run again
|
||||
</Button>
|
||||
) : (
|
||||
r.deploymentId &&
|
||||
!r.sweepId && (
|
||||
)
|
||||
)}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={again}
|
||||
title="Queue a new run with the same settings (the deployment must be running)"
|
||||
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();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<RotateCcwIcon />
|
||||
Run again
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={r.state === "running"}
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete this benchmark?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Its numbers, log, results.json and HTML report are removed.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
if (await deleteBenchmark(r.id)) {
|
||||
router.push("/benchmarks");
|
||||
router.refresh();
|
||||
}
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{r.state === "pending_approval" && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={r.requestedBy}
|
||||
what={`run ${r.kind === "ab" ? "an A/B" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
|
||||
base={`/api/benchmarks/${r.id}`}
|
||||
/>
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{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" />
|
||||
@@ -294,7 +283,13 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
|
||||
{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"
|
||||
@@ -306,7 +301,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
{r.kind === "run" && r.state === "completed" && r.summary && (
|
||||
<PublishCard
|
||||
runId={r.id}
|
||||
defaultTitle={r.label ?? `${s.repoId} ${weightsLabel(s)}`}
|
||||
defaultTitle={
|
||||
r.label ?? `${modelName(s).split("/").pop()} ${weightsLabel(s)}`
|
||||
}
|
||||
defaultSummary={reportSummary(r)}
|
||||
/>
|
||||
)}
|
||||
@@ -350,15 +347,16 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
}
|
||||
/>
|
||||
<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.
|
||||
Passed to BetterBench (when set before the run starts) and to
|
||||
the launch80 preview, together with the system summary.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
|
||||
{r.kind === "run" && (
|
||||
{r.kind !== "ab" && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Settings measured</CardTitle>
|
||||
<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">
|
||||
@@ -372,15 +370,22 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
Command
|
||||
<CopyButton value={s.command} label="Copy command" />
|
||||
{!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>
|
||||
<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
|
||||
@@ -392,6 +397,6 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,12 @@
|
||||
|
||||
import { TriangleAlertIcon } from "lucide-react";
|
||||
import { BarChart } from "@/components/bar-chart";
|
||||
import { BenchmarkResources } from "@/components/benchmark-resources";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled, weightsLabel } from "@/lib/benchmark-report";
|
||||
import { configChips } from "@/lib/benchmark-view";
|
||||
import { 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";
|
||||
import type { RunRow } from "../benchmark-list";
|
||||
|
||||
function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) {
|
||||
return (
|
||||
@@ -55,7 +54,7 @@ const date = (iso: string | null | undefined) =>
|
||||
: "";
|
||||
|
||||
/** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */
|
||||
export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
export function BenchmarkReport({ run }: { run: RunRow }) {
|
||||
const sum = run.summary;
|
||||
if (!sum) return null;
|
||||
const s = run.snapshot;
|
||||
@@ -73,13 +72,13 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
].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">
|
||||
<article className="flex flex-col gap-8 rounded-2xl bg-card/55 px-5 py-6 ring-1 ring-foreground/10 backdrop-blur-md sm:px-8 sm:py-8">
|
||||
<header className="flex flex-col gap-3">
|
||||
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
|
||||
BetterBench {sum.betterbenchVersion} · {date(sum.timestamp ?? run.startedAt)}
|
||||
</span>
|
||||
<div className="flex flex-col gap-1">
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${s.repoId} ${weightsLabel(s) !== "safetensors" ? weightsLabel(s) : ""}`.trim()}</h2>
|
||||
<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">
|
||||
@@ -88,7 +87,7 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
{x}
|
||||
</span>
|
||||
))}
|
||||
<span className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">{s.runtimeName}</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}
|
||||
@@ -200,12 +199,6 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{run.resources && (
|
||||
<Section title="Resources" intro="What the server used while BetterBench measured it.">
|
||||
<BenchmarkResources stats={run.resources} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title="Full numbers">
|
||||
{sum.single.length > 0 && (
|
||||
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
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 ?? run.snapshot.deploymentName} · Benchmark` : "Benchmark" };
|
||||
return { title: run ? `${run.label ?? targetName(run.snapshot)} · Benchmark` : "Benchmark" };
|
||||
}
|
||||
|
||||
export default async function BenchmarkPage({ params }: PageProps<"/benchmarks/[id]">) {
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { GaugeIcon, GitCompareIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
@@ -18,20 +17,23 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { BenchmarkRow } from "@/lib/benchmarks";
|
||||
import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkListRow, BenchmarkRow } from "@/lib/benchmarks";
|
||||
import { configChips, describeSettings, engineName, modelName, targetName } from "@/lib/benchmark-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ListRow = Omit<
|
||||
BenchmarkRow,
|
||||
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
|
||||
> & {
|
||||
/** A row as it arrives in the browser (dates as ISO strings). */
|
||||
type Serialized<T> = Omit<T, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
|
||||
createdAt: string;
|
||||
startedAt: string | null;
|
||||
finishedAt: string | null;
|
||||
cancelRequestedAt: string | null;
|
||||
};
|
||||
|
||||
/** A run in a list: headline numbers only. */
|
||||
export type ListRow = Serialized<BenchmarkListRow>;
|
||||
/** A run with everything (detail page). */
|
||||
export type RunRow = Serialized<BenchmarkRow>;
|
||||
|
||||
const MAX_COMPARE = 16;
|
||||
const fmt = (v: number | null | undefined, digits = 1) =>
|
||||
v == null ? "–" : v.toFixed(digits);
|
||||
@@ -40,41 +42,40 @@ const fmt = (v: number | null | undefined, digits = 1) =>
|
||||
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[]>([]);
|
||||
// "" = everything, "-" = started in Kaname, else a token name.
|
||||
// "" = every endpoint, else an endpoint's name.
|
||||
const [by, setBy] = useState("");
|
||||
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
|
||||
const tokens = [
|
||||
...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
|
||||
].sort();
|
||||
const shown = rows.filter(
|
||||
(r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
|
||||
);
|
||||
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", { cache: "no-store" }).catch(
|
||||
() => null,
|
||||
);
|
||||
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]);
|
||||
}, [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 a running{" "}
|
||||
<Link href="/deployments" className="underline">
|
||||
deployment
|
||||
No benchmarks yet. Open an{" "}
|
||||
<Link href="/endpoints" className="underline">
|
||||
endpoint
|
||||
</Link>{" "}
|
||||
and start one there.
|
||||
</p>
|
||||
@@ -94,7 +95,7 @@ export function BenchmarkList({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{!compact && (comparable.length > 1 || tokens.length > 0) && (
|
||||
{!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
|
||||
@@ -102,18 +103,17 @@ export function BenchmarkList({
|
||||
: `${selected.length} selected (up to ${MAX_COMPARE}).`}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
{tokens.length > 0 && (
|
||||
{targets.length > 1 && (
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
aria-label="Requested by"
|
||||
aria-label="Endpoint"
|
||||
>
|
||||
<option value="">Requested by anyone</option>
|
||||
<option value="-">Started in Kaname</option>
|
||||
{tokens.map((t) => (
|
||||
<option value="">All endpoints</option>
|
||||
{targets.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t} (API)
|
||||
{t}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
@@ -168,7 +168,7 @@ export function BenchmarkList({
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{shown.map((r) => {
|
||||
const h = headline(r.summary);
|
||||
const h = r.headline;
|
||||
const s = r.snapshot;
|
||||
return (
|
||||
<TableRow
|
||||
@@ -181,7 +181,7 @@ export function BenchmarkList({
|
||||
checked={selected.includes(r.id)}
|
||||
disabled={r.state !== "completed"}
|
||||
onCheckedChange={() => toggle(r.id)}
|
||||
aria-label={`Select ${r.label ?? s.deploymentName} for comparison`}
|
||||
aria-label={`Select ${r.label ?? targetName(s)} for comparison`}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
@@ -190,21 +190,17 @@ export function BenchmarkList({
|
||||
href={`/benchmarks/${r.id}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{r.label ?? s.deploymentName}
|
||||
{r.label ?? targetName(s)}
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{r.label && `${s.deploymentName} · `}
|
||||
{s.repoId} · <LocalTime value={r.createdAt} />
|
||||
<RequestedByBadge
|
||||
name={r.requestedBy}
|
||||
className="h-4 text-[10px]"
|
||||
/>
|
||||
{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">
|
||||
{s.runtimeName}
|
||||
{engineName(s)}
|
||||
</span>
|
||||
{configChips(s).map((c) => (
|
||||
<span
|
||||
@@ -220,7 +216,11 @@ export function BenchmarkList({
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">
|
||||
{fmt(h.decode)}
|
||||
{r.kind === "eval" ? (
|
||||
<span title="Quality eval score">{r.qualityScore != null ? `${r.qualityScore}% quality` : "–"}</span>
|
||||
) : (
|
||||
fmt(h.decode)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { getBenchmarks } from "@/lib/benchmarks";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import { 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) => number | null };
|
||||
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;
|
||||
@@ -87,6 +89,24 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
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.
|
||||
@@ -98,15 +118,17 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
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>
|
||||
<PageHero
|
||||
title="Compare benchmarks"
|
||||
painting={{ view: 0.6, focus: [0.25, 0.6], anchor: [0.65, 0.4] }}
|
||||
description={
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<p>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-destructive">These runs used different prompt sets (corpus versions), so their numbers aren't comparable.</p>}
|
||||
{anyQuick && <p className="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>
|
||||
@@ -116,7 +138,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
{runs.map((r, i) => (
|
||||
<TableHead key={r.id} className="align-top whitespace-normal">
|
||||
<Link href={`/benchmarks/${r.id}`} className="font-medium text-foreground hover:underline">
|
||||
{r.label ?? r.snapshot.deploymentName}
|
||||
{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>}
|
||||
@@ -174,7 +196,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -187,7 +209,7 @@ function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{rows.map((m) => {
|
||||
const vals = sums.map((s) => m.get(s));
|
||||
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 (
|
||||
|
||||
@@ -1,21 +1,47 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { getModel } from "@/lib/library";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { BenchmarkList } from "./benchmark-list";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Benchmarks" };
|
||||
|
||||
export default async function BenchmarksPage() {
|
||||
const rows = await listBenchmarks();
|
||||
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">
|
||||
BetterBench runs against your deployments. Start one from a running deployment; select runs to compare their settings and numbers.
|
||||
</p>
|
||||
</div>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} />
|
||||
</div>
|
||||
<PageHero
|
||||
title="Benchmarks"
|
||||
painting={{ view: 0.6, focus: [0.25, 0.6], anchor: [0.65, 0.4] }}
|
||||
description={
|
||||
<>
|
||||
{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.
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} filter={{ model: model?.model.id }} />
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getSweep } from "@/lib/sweeps";
|
||||
import { SweepDetail } from "./sweep-detail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Sweep · Benchmarks" };
|
||||
|
||||
export default async function SweepPage({ params }: PageProps<"/benchmarks/sweeps/[id]">) {
|
||||
const data = await getSweep((await params).id);
|
||||
if (!data) notFound();
|
||||
return <SweepDetail initial={JSON.parse(JSON.stringify(data))} />;
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { GitCompareIcon, Grid3x3Icon, SquareIcon, Trash2Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { BarChart } from "@/components/bar-chart";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { AgentApprovalBar } from "@/components/approval-bar";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Sweep = typeof benchmarkSweeps.$inferSelect;
|
||||
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null; meta: RunMeta | null };
|
||||
export type SweepData = { sweep: Sweep; runs: Run[] };
|
||||
|
||||
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
|
||||
pending: "Waiting",
|
||||
deploying: "Deploying",
|
||||
benchmarking: "Benchmarking",
|
||||
done: "Done",
|
||||
failed: "Failed",
|
||||
skipped: "Skipped",
|
||||
};
|
||||
|
||||
type Row = {
|
||||
v: SweepVariant;
|
||||
run: Run | null;
|
||||
decode: number | null;
|
||||
ttft: number | null;
|
||||
prefill: number | null;
|
||||
peak: number | null;
|
||||
cpu: number | null;
|
||||
ram: number | null;
|
||||
vram: number | null;
|
||||
power: number | null;
|
||||
temp: number | null;
|
||||
};
|
||||
|
||||
function rowsOf(data: SweepData): Row[] {
|
||||
return data.sweep.variants.map((v) => {
|
||||
const run = data.runs.find((r) => r.id === v.runId) ?? null;
|
||||
const h = headline(run?.summary ?? null);
|
||||
const c = run?.resources?.containers.find((x) => x.side === "a");
|
||||
const g = run?.resources?.gpus ?? [];
|
||||
return {
|
||||
v,
|
||||
run,
|
||||
decode: h.decode,
|
||||
ttft: h.ttftMs,
|
||||
prefill: h.prefill?.tps ?? null,
|
||||
peak: h.peak?.tps ?? null,
|
||||
cpu: c?.cpuAvg ?? null,
|
||||
ram: c?.memPeakBytes ?? null,
|
||||
vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
|
||||
power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
|
||||
temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded setup (GPU, PCIe, engine version, quant, KV cache, context, concurrency): values shared by
|
||||
* every variant go above the table, the ones that differ become columns.
|
||||
*/
|
||||
function setupOf(rows: Row[]) {
|
||||
const per = rows.map((r) => (r.run?.meta ? metaRows(r.run.meta).filter((x) => x.key !== "image" && x.key !== "digest") : null));
|
||||
const keys = [...new Map(per.flatMap((x) => x ?? []).map((x) => [x.key, x.label])).entries()];
|
||||
const recorded = per.filter((x) => x != null);
|
||||
const value = (i: number, key: string) => per[i]?.find((x) => x.key === key)?.value ?? null;
|
||||
const differs = keys.filter(([key]) => new Set(recorded.map((x) => x.find((y) => y.key === key)?.value ?? "")).size > 1);
|
||||
const shared = keys.filter((k) => !differs.includes(k)).map(([key, label]) => ({ label, value: recorded[0]?.find((y) => y.key === key)?.value ?? null }));
|
||||
return { shared: recorded.length ? shared : [], columns: differs.map(([key, label]) => ({ key, label })), value };
|
||||
}
|
||||
|
||||
/** Best value per column (higher or lower is better), to set it in bold. */
|
||||
function best(rows: Row[], key: keyof Row, higher: boolean): number | null {
|
||||
const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number");
|
||||
if (vals.length < 2) return null;
|
||||
return higher ? Math.max(...vals) : Math.min(...vals);
|
||||
}
|
||||
|
||||
export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
const router = useRouter();
|
||||
const [data, setData] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const { sweep } = data;
|
||||
const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const t = setInterval(async () => {
|
||||
const res = await fetch(`/api/sweeps/${sweep.id}`, { cache: "no-store" }).catch(() => null);
|
||||
if (res?.ok) setData(await res.json());
|
||||
}, 3_000);
|
||||
return () => clearInterval(t);
|
||||
}, [sweep.id, active]);
|
||||
|
||||
async function act(path: string, method: string, done: () => void) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(path, { method });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Failed (${res.status})`);
|
||||
done();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const rows = rowsOf(data);
|
||||
const setup = setupOf(rows);
|
||||
const finished = rows.filter((r) => r.decode != null);
|
||||
const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed"));
|
||||
const bestOf = {
|
||||
decode: best(rows, "decode", true),
|
||||
ttft: best(rows, "ttft", false),
|
||||
prefill: best(rows, "prefill", true),
|
||||
peak: best(rows, "peak", true),
|
||||
cpu: best(rows, "cpu", false),
|
||||
ram: best(rows, "ram", false),
|
||||
vram: best(rows, "vram", false),
|
||||
power: best(rows, "power", false),
|
||||
temp: best(rows, "temp", false),
|
||||
};
|
||||
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
|
||||
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
|
||||
);
|
||||
const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="flex items-center gap-2 text-xl font-semibold">
|
||||
<Grid3x3Icon className="size-5 text-muted-foreground" />
|
||||
{sweep.label ?? `Sweep of ${sweep.base.name}`}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "}
|
||||
{sweep.baseDeploymentId ? (
|
||||
<Link href={`/deployments/${sweep.baseDeploymentId}`} className="underline">
|
||||
{sweep.base.name}
|
||||
</Link>
|
||||
) : (
|
||||
sweep.base.name
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RequestedByBadge name={sweep.requestedBy} />
|
||||
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
|
||||
{runIds.length >= 2 && (
|
||||
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
|
||||
<GitCompareIcon />
|
||||
Compare in detail
|
||||
</Link>
|
||||
)}
|
||||
{active ? (
|
||||
<Button variant="outline" size="sm" disabled={busy || !!sweep.cancelRequestedAt} onClick={() => act(`/api/sweeps/${sweep.id}/cancel`, "POST", () => router.refresh())}>
|
||||
<SquareIcon />
|
||||
Cancel
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outline" size="sm" disabled={busy} onClick={() => act(`/api/sweeps/${sweep.id}`, "DELETE", () => router.push("/benchmarks"))}>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{active && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
|
||||
</p>
|
||||
)}
|
||||
{sweep.state === "pending_approval" && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={sweep.requestedBy}
|
||||
what={`run a sweep of ${rows.length} variants from ${sweep.base.name} (${sweep.params.map((p) => `${p.key}: ${p.values.join(", ")}`).join("; ")}${sweep.timeLimitS ? `, at most ${Math.round(sweep.timeLimitS / 60)} min` : ""}); each variant is deployed, benchmarked and removed`}
|
||||
base={`/api/sweeps/${sweep.id}`}
|
||||
/>
|
||||
)}
|
||||
{sweep.error && <p className="text-sm text-destructive">{sweep.error}</p>}
|
||||
|
||||
{finished.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Generation speed by variant</CardTitle>
|
||||
<CardDescription>Single-stream decode, tokens per second (BetterBench combined score). Higher is better.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BarChart
|
||||
axisLabel="Decode t/s"
|
||||
rows={finished.map((r) => ({
|
||||
label: r.v.label,
|
||||
value: r.decode,
|
||||
valueLabel: r.decode!.toFixed(1),
|
||||
details: [r.ttft != null ? `TTFT ${r.ttft.toFixed(0)} ms` : "", r.ram != null ? `Peak RAM ${formatBytes(r.ram)}` : ""].filter(Boolean),
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Variants</CardTitle>
|
||||
<CardDescription>Best value per column in bold. Resource figures are averages/peaks over the run.</CardDescription>
|
||||
{setup.shared.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{setup.shared
|
||||
.filter((x) => x.value)
|
||||
.map((x) => `${x.label}: ${x.value}`)
|
||||
.join(" · ")}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="overflow-x-auto px-0">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-xs text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
<th className="px-3 py-2 text-left font-medium">Variant</th>
|
||||
<th className="px-3 py-2 text-left font-medium">State</th>
|
||||
{setup.columns.map((c) => (
|
||||
<th key={c.key} className="px-3 py-2 text-left font-medium">
|
||||
{c.label}
|
||||
</th>
|
||||
))}
|
||||
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
|
||||
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
|
||||
<th className="px-3 py-2 text-right font-medium">CPU cores</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak RAM</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak VRAM</th>
|
||||
<th className="px-3 py-2 text-right font-medium">GPU power</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak temp</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr key={r.v.index} className="border-b last:border-0">
|
||||
<td className="px-3 py-2 font-mono text-xs">
|
||||
{r.v.runId ? (
|
||||
<Link href={`/benchmarks/${r.v.runId}`} className="underline-offset-2 hover:underline">
|
||||
{r.v.label}
|
||||
</Link>
|
||||
) : (
|
||||
r.v.label
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-xs text-muted-foreground" title={r.v.error ?? r.run?.error ?? undefined}>
|
||||
{VARIANT_STATE[r.v.state]}
|
||||
{r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""}
|
||||
{(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""}
|
||||
</td>
|
||||
{setup.columns.map((c) => (
|
||||
<td key={c.key} className="px-3 py-2 font-mono text-xs">
|
||||
{setup.value(i, c.key) ?? "–"}
|
||||
</td>
|
||||
))}
|
||||
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
|
||||
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
|
||||
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
|
||||
{cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
|
||||
{cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))}
|
||||
{cell(r.ram, bestOf.ram, (x) => formatBytes(x))}
|
||||
{cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)}
|
||||
{cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)}
|
||||
{cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listDeployableModels, listDeployments } from "@/lib/deployments";
|
||||
import { SweepForm, type SweepBase } from "./sweep-form";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "New sweep" };
|
||||
|
||||
export default async function NewSweepPage({ searchParams }: PageProps<"/benchmarks/sweeps/new">) {
|
||||
const { deployment } = await searchParams;
|
||||
const [deployments, models] = await Promise.all([listDeployments(), listDeployableModels()]);
|
||||
const bases: SweepBase[] = deployments
|
||||
.filter((d) => !d.sweepId)
|
||||
.map((d) => ({
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
engine: d.engine,
|
||||
accelerator: d.accelerator,
|
||||
repoId: d.repoId,
|
||||
options: d.options,
|
||||
cpus: d.cpus,
|
||||
memoryMb: d.memoryMb,
|
||||
ggufFiles: models.find((m) => m.id === d.modelId)?.candidates.gguf.map((g) => g.path) ?? [],
|
||||
}));
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">New sweep</h1>
|
||||
<p className="max-w-3xl text-sm text-muted-foreground">
|
||||
Vary one or two settings of a deployment. Kaname deploys each variant in turn, benchmarks it with BetterBench, removes it again and compares all of them,
|
||||
including the resources each one used.
|
||||
</p>
|
||||
</div>
|
||||
<SweepForm bases={bases} initialBaseId={typeof deployment === "string" ? deployment : undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Grid3x3Icon, PlusIcon, XIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import type { BenchmarkPhase, DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { expandSweep, MAX_SWEEP_VARIANTS, splitValues, SweepError, sweepKeysFor } from "@/lib/sweep";
|
||||
|
||||
export type SweepBase = {
|
||||
id: string;
|
||||
name: string;
|
||||
engine: RuntimeEngine;
|
||||
accelerator: RuntimeAccelerator;
|
||||
repoId: string;
|
||||
options: DeploymentOptions;
|
||||
cpus: number | null;
|
||||
memoryMb: number | null;
|
||||
ggufFiles: string[];
|
||||
};
|
||||
|
||||
const PHASES: { id: BenchmarkPhase; label: string }[] = [
|
||||
{ id: "decode", label: "Generation" },
|
||||
{ id: "prefill", label: "Prompt processing" },
|
||||
{ id: "concurrency", label: "Parallel requests" },
|
||||
];
|
||||
|
||||
/** The base's current value of a sweep key, shown as a hint. */
|
||||
function currentValue(base: SweepBase, key: string): string {
|
||||
const o = base.options;
|
||||
const v: Record<string, unknown> = {
|
||||
contextSize: o.contextSize,
|
||||
modelFile: o.modelFile,
|
||||
kvCache: o.cacheTypeK ?? "f16",
|
||||
threads: o.threads ?? "auto",
|
||||
parallel: o.parallel ?? "auto",
|
||||
batchSize: o.batchSize ?? "default",
|
||||
ubatchSize: o.ubatchSize ?? "default",
|
||||
flashAttn: o.flashAttn ?? "auto",
|
||||
cacheRamMb: o.cacheRamMb ?? "8192 (default)",
|
||||
gpuLayers: o.gpuLayers ?? "auto",
|
||||
dtype: o.dtype ?? "runtime default",
|
||||
maxNumSeqs: o.maxNumSeqs ?? "default",
|
||||
kvCacheGb: o.kvCacheGb ?? "runtime default",
|
||||
gpuMemoryUtilization: o.gpuMemoryUtilization ?? "0.9",
|
||||
cpus: base.cpus ?? "no limit",
|
||||
};
|
||||
return String(v[key] ?? "");
|
||||
}
|
||||
|
||||
type Param = { key: string; text: string; files: string[] };
|
||||
|
||||
export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initialBaseId?: string }) {
|
||||
const router = useRouter();
|
||||
const [baseId, setBaseId] = useState(initialBaseId && bases.some((b) => b.id === initialBaseId) ? initialBaseId : (bases[0]?.id ?? ""));
|
||||
const base = bases.find((b) => b.id === baseId) ?? null;
|
||||
const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
|
||||
const [params, setParams] = useState<Param[]>([{ key: "contextSize", text: "", files: [] }]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [mode, setMode] = useState("quick");
|
||||
const [passes, setPasses] = useState("10");
|
||||
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const values = (p: Param) => (p.key === "modelFile" ? p.files : splitValues(p.text));
|
||||
let preview: { variants: ReturnType<typeof expandSweep> | null; error: string | null } = { variants: null, error: null };
|
||||
if (base) {
|
||||
try {
|
||||
preview = { variants: expandSweep(params.map((p) => ({ key: p.key, values: values(p) })), base.engine, base.accelerator, { modelFiles: base.ggufFiles }), error: null };
|
||||
} catch (err) {
|
||||
preview = { variants: null, error: err instanceof SweepError ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
const setParam = (i: number, patch: Partial<Param>) => setParams((ps) => ps.map((p, j) => (j === i ? { ...p, ...patch } : p)));
|
||||
|
||||
async function submit() {
|
||||
if (!base || !preview.variants) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/sweeps", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
baseDeploymentId: base.id,
|
||||
label: label.trim() || null,
|
||||
params: params.map((p) => ({ key: p.key, values: values(p) })),
|
||||
quick: mode === "quick",
|
||||
passes: mode === "custom" ? Number(passes) || 10 : null,
|
||||
phases: phases.length === PHASES.length ? [] : phases,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
|
||||
router.push(`/benchmarks/sweeps/${json.id}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (bases.length === 0) return <p className="text-sm text-muted-foreground">Create a deployment first; a sweep varies its settings.</p>;
|
||||
|
||||
return (
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Base deployment</CardTitle>
|
||||
<CardDescription>Every variant starts from its settings. It doesn't need to be running.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<NativeSelect value={baseId} onChange={(e) => setBaseId(e.target.value)} aria-label="Base deployment">
|
||||
{bases.map((b) => (
|
||||
<option key={b.id} value={b.id}>
|
||||
{b.name} · {b.repoId}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>What to vary</CardTitle>
|
||||
<CardDescription>One or two settings; every combination becomes a variant (up to {MAX_SWEEP_VARIANTS}).</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{base &&
|
||||
params.map((p, i) => {
|
||||
const def = keys.find((k) => k.key === p.key);
|
||||
return (
|
||||
<div key={i} className="flex flex-col gap-2 rounded-lg border px-3 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<NativeSelect value={p.key} onChange={(e) => setParam(i, { key: e.target.value, text: "", files: [] })} aria-label={`Setting ${i + 1}`}>
|
||||
{keys
|
||||
.filter((k) => k.key === p.key || !params.some((q) => q.key === k.key))
|
||||
.map((k) => (
|
||||
<option key={k.key} value={k.key}>
|
||||
{k.label}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
{params.length > 1 && (
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Remove setting" onClick={() => setParams((ps) => ps.filter((_, j) => j !== i))}>
|
||||
<XIcon />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{p.key === "modelFile" ? (
|
||||
<div className="flex flex-col gap-1">
|
||||
{base.ggufFiles.map((f) => (
|
||||
<label key={f} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox checked={p.files.includes(f)} onCheckedChange={(v) => setParam(i, { files: v ? [...p.files, f] : p.files.filter((x) => x !== f) })} />
|
||||
<span className="font-mono text-xs">{quantGroup(f) ?? f}</span>
|
||||
</label>
|
||||
))}
|
||||
{base.ggufFiles.length < 2 && <p className="text-xs text-muted-foreground">Only one GGUF file is downloaded; download more quants to compare them.</p>}
|
||||
</div>
|
||||
) : (
|
||||
<Input value={p.text} onChange={(e) => setParam(i, { text: e.target.value })} placeholder={def?.hint} aria-label="Values" className="font-mono text-sm" />
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">Base value: {currentValue(base, p.key)}</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{params.length < 2 && base && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="self-start"
|
||||
onClick={() => setParams((ps) => [...ps, { key: keys.find((k) => !ps.some((q) => q.key === k.key))?.key ?? "threads", text: "", files: [] }])}
|
||||
>
|
||||
<PlusIcon />
|
||||
Vary a second setting
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Benchmark per variant</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
|
||||
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
|
||||
<option value="quick">Quick: 5 passes (smoke test)</option>
|
||||
<option value="full">Full: 20 passes (comparable)</option>
|
||||
<option value="custom">Custom number of passes</option>
|
||||
</NativeSelect>
|
||||
{mode === "custom" && <Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes" />}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{PHASES.map((p) => (
|
||||
<label key={p.id} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} />
|
||||
{p.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="sw-label">Label</Label>
|
||||
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="lg:sticky lg:top-4">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<Grid3x3Icon className="size-4 text-muted-foreground" />
|
||||
{preview.variants ? `${preview.variants.length} variants` : "Variants"}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
{preview.error ? (
|
||||
<p className="text-xs text-muted-foreground">{preview.error}</p>
|
||||
) : (
|
||||
<ol className="flex flex-col gap-1">
|
||||
{preview.variants?.map((v) => (
|
||||
<li key={v.index} className="flex gap-2 text-xs">
|
||||
<span className="w-5 text-right text-muted-foreground tabular-nums">{v.index + 1}</span>
|
||||
<span className="font-mono">{v.label}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Variants run one after another, each in its own temporary deployment{base?.memoryMb ? " (memory limit: the base's, raised where a variant needs more)" : ""}.
|
||||
{mode !== "quick" && " Full runs on a CPU can take hours per variant."}
|
||||
</p>
|
||||
<Button onClick={submit} disabled={!preview.variants || busy || phases.length === 0}>
|
||||
<Grid3x3Icon />
|
||||
Start sweep
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { abHeadline } from "@/lib/ab-report";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkPhase } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ListRow } from "../../benchmarks/benchmark-list";
|
||||
|
||||
const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
|
||||
{ id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
|
||||
{ id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
|
||||
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
|
||||
];
|
||||
|
||||
type Mode = "run" | "ab" | "sweep";
|
||||
type Peer = { id: string; name: string; state: string; modelId: string };
|
||||
|
||||
/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
|
||||
export function BenchmarkCard({ deploymentId, modelId, running, initial }: { deploymentId: string; modelId: string; running: boolean; initial: ListRow[] }) {
|
||||
const router = useRouter();
|
||||
const [tab, setTab] = useState<Mode>("run");
|
||||
const [mode, setMode] = useState("quick");
|
||||
const [passes, setPasses] = useState("10");
|
||||
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [runs, setRuns] = useState(initial);
|
||||
const [peers, setPeers] = useState<Peer[] | null>(null);
|
||||
const [peerId, setPeerId] = useState("");
|
||||
const [mde, setMde] = useState("1");
|
||||
const [maxPairs, setMaxPairs] = useState("200");
|
||||
|
||||
const active = runs.some((r) => r.state === "queued" || r.state === "running");
|
||||
useEffect(() => {
|
||||
const t = setInterval(
|
||||
async () => {
|
||||
const res = await fetch(`/api/benchmarks?deployment=${deploymentId}`, { cache: "no-store" }).catch(() => null);
|
||||
if (res?.ok) setRuns(await res.json());
|
||||
},
|
||||
active ? 3_000 : 15_000,
|
||||
);
|
||||
return () => clearInterval(t);
|
||||
}, [deploymentId, active]);
|
||||
|
||||
// Other deployments of the same model (A/B partners).
|
||||
useEffect(() => {
|
||||
if (tab !== "ab") return;
|
||||
let stop = false;
|
||||
void fetch("/api/deployments", { cache: "no-store" })
|
||||
.then((r) => (r.ok ? r.json() : []))
|
||||
.then((rows: Peer[]) => {
|
||||
if (stop) return;
|
||||
const list = rows.filter((p) => p.modelId === modelId && p.id !== deploymentId);
|
||||
setPeers(list);
|
||||
setPeerId((cur) => cur || list.find((p) => p.state === "running")?.id || "");
|
||||
});
|
||||
return () => {
|
||||
stop = true;
|
||||
};
|
||||
}, [tab, modelId, deploymentId]);
|
||||
|
||||
async function start(body: Record<string, unknown>) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, description: description.trim() || null, ...body }) });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
|
||||
router.push(`/benchmarks/${json.id}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const peer = peers?.find((p) => p.id === peerId);
|
||||
const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
|
||||
{ id: "run", label: "Run", icon: GaugeIcon },
|
||||
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
|
||||
{ id: "sweep", label: "Sweep", icon: Grid3x3Icon },
|
||||
];
|
||||
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<GaugeIcon className="size-4 text-muted-foreground" />
|
||||
Benchmark
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
<div className="inline-flex self-start rounded-lg bg-muted p-1" role="tablist">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === t.id}
|
||||
onClick={() => setTab(t.id)}
|
||||
className={cn("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs", tab === t.id ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground")}
|
||||
>
|
||||
<t.icon className="size-3.5" />
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === "run" && (
|
||||
<>
|
||||
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
|
||||
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
|
||||
<option value="quick">Quick: 5 passes (smoke test)</option>
|
||||
<option value="full">Full: 20 passes (comparable)</option>
|
||||
<option value="custom">Custom number of passes</option>
|
||||
</NativeSelect>
|
||||
{mode === "custom" && (
|
||||
<Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{PHASES.map((p) => (
|
||||
<label key={p.id} className="flex cursor-pointer items-start gap-2">
|
||||
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} className="mt-0.5" />
|
||||
<span className="flex flex-col">
|
||||
<span>{p.label}</span>
|
||||
<span className="text-xs text-muted-foreground">{p.hint}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
|
||||
<Button
|
||||
onClick={() =>
|
||||
start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
|
||||
}
|
||||
disabled={!running || busy || phases.length === 0}
|
||||
>
|
||||
<GaugeIcon />
|
||||
Run benchmark
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "ab" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Paired A/B: the same prompts go to this deployment (A) and another one of the same model (B), alternating, until the difference is known to ±the target. Both
|
||||
must be running and fit in memory together.
|
||||
</p>
|
||||
{peers === null ? (
|
||||
<p className="text-xs text-muted-foreground">Loading…</p>
|
||||
) : peers.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
No other deployment of this model. Create one with the setting you want to compare (e.g. a different KV cache type), or run a sweep.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<NativeSelect value={peerId} onChange={(e) => setPeerId(e.target.value)} aria-label="Deployment B">
|
||||
<option value="">Choose B…</option>
|
||||
{peers.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name} {p.state !== "running" ? `(${p.state})` : ""}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
{peer && peer.state !== "running" && (
|
||||
<p className="text-xs text-amber-700 dark:text-amber-300">
|
||||
{peer.name} isn't running.{" "}
|
||||
<Link href={`/deployments/${peer.id}`} className="underline">
|
||||
Start it
|
||||
</Link>{" "}
|
||||
first.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="flex flex-col gap-1 text-xs">
|
||||
<span className="text-muted-foreground">Target precision (±%)</span>
|
||||
<Input value={mde} onChange={(e) => setMde(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-xs">
|
||||
<span className="text-muted-foreground">Max pairs</span>
|
||||
<Input value={maxPairs} onChange={(e) => setMaxPairs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
|
||||
</label>
|
||||
</div>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
|
||||
<Button
|
||||
onClick={() => start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
|
||||
disabled={!running || busy || !peer || peer.state !== "running"}
|
||||
>
|
||||
<GitCompareArrowsIcon />
|
||||
Start A/B
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{!running && <p className="text-xs text-muted-foreground">Start this deployment (A) first.</p>}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "sweep" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Vary one or two settings (context size, KV cache type, threads, quant, GPU layers, …). Kaname deploys each variant in turn, benchmarks it, removes it again, and
|
||||
compares all of them. This deployment doesn't need to run.
|
||||
</p>
|
||||
<Link href={`/benchmarks/sweeps/new?deployment=${deploymentId}`} className={buttonVariants()}>
|
||||
<Grid3x3Icon />
|
||||
Set up a sweep
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
|
||||
{runs.length > 0 && (
|
||||
<div className="flex flex-col gap-1 border-t pt-3">
|
||||
{runs.slice(0, 5).map((r) => {
|
||||
const h = headline(r.summary);
|
||||
return (
|
||||
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
|
||||
<span className="min-w-0 truncate">
|
||||
{r.kind === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</span>}
|
||||
{r.label ?? new Date(r.createdAt).toLocaleString()}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
|
||||
{r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`}
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
<Link href="/benchmarks" className="self-start px-1.5 text-xs text-muted-foreground hover:text-foreground">
|
||||
All benchmarks →
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, ShieldCheckIcon, ShieldIcon, SquareIcon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { AgentApprovalBar } from "@/components/approval-bar";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
import { DeploymentStateBadge } from "@/components/deployment-state";
|
||||
import { LiveLog } from "@/components/live-log";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
|
||||
import { ENGINE_PORT } from "@/lib/deploy-command";
|
||||
import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
|
||||
import type { DeploymentRow } from "@/lib/deployments";
|
||||
import { formatBytes, percent } from "@/lib/format";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
|
||||
import type { ListRow } from "../../benchmarks/benchmark-list";
|
||||
import { BenchmarkCard } from "./benchmark-card";
|
||||
|
||||
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
|
||||
startedAt: string | null;
|
||||
readyAt: string | null;
|
||||
stoppedAt: string | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<span className="text-lg font-semibold tabular-nums">{value}</span>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment; benchmarks: ListRow[] }) {
|
||||
const router = useRouter();
|
||||
const [d, setD] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
|
||||
|
||||
useEffect(() => {
|
||||
const t = setInterval(async () => {
|
||||
setNow(Date.now());
|
||||
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
|
||||
if (res?.status === 404) router.push("/deployments");
|
||||
else if (res?.ok) setD(await res.json());
|
||||
}, 2_000);
|
||||
return () => clearInterval(t);
|
||||
}, [d.id, router]);
|
||||
|
||||
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
|
||||
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
|
||||
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
|
||||
const port = ENGINE_PORT[d.engine];
|
||||
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
|
||||
const hostname = useHostname();
|
||||
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
|
||||
const webUi = webUiUrl(d, hostname);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardContent className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="text-xl font-semibold">{d.name}</h1>
|
||||
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
|
||||
<RequestedByBadge name={d.requestedBy} />
|
||||
{d.protected && (
|
||||
<span className="inline-flex items-center gap-1 rounded-4xl border border-emerald-500/30 bg-emerald-500/10 px-2 text-xs text-emerald-700 dark:text-emerald-300">
|
||||
<ShieldCheckIcon className="size-3" />
|
||||
protected
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<Link href={`/${d.repoId}`} className="hover:underline">
|
||||
{d.repoId}
|
||||
</Link>
|
||||
{file && ` · ${file}`}
|
||||
{d.options.mmproj && " · vision"}
|
||||
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
|
||||
</p>
|
||||
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{webUi && (
|
||||
<a
|
||||
href={webUi}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={cn(buttonVariants({ variant: "outline" }), d.state !== "running" && "pointer-events-none opacity-50")}
|
||||
aria-disabled={d.state !== "running"}
|
||||
>
|
||||
<ExternalLinkIcon />
|
||||
Web UI
|
||||
</a>
|
||||
)}
|
||||
{active ? (
|
||||
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
|
||||
<SquareIcon />
|
||||
Stop
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => startDeployment(d.id)}>
|
||||
<PlayIcon />
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
title={d.protected ? "Agents can't touch it now; click to allow them again" : "Agents (API tokens) can't edit, stop, delete or benchmark a protected deployment, nor crowd it out of VRAM"}
|
||||
onClick={async () => {
|
||||
const res = await fetch(`/api/deployments/${d.id}/protect`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ protected: !d.protected }) });
|
||||
if (!res.ok) return void toast.error(`Could not change it (${res.status})`);
|
||||
setD({ ...d, protected: !d.protected });
|
||||
toast.success(d.protected ? "No longer protected from agents" : "Protected from agents");
|
||||
}}
|
||||
>
|
||||
{d.protected ? <ShieldCheckIcon /> : <ShieldIcon />}
|
||||
{d.protected ? "Protected" : "Protect"}
|
||||
</Button>
|
||||
<Link
|
||||
href={`/deployments/${d.id}/edit`}
|
||||
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
|
||||
aria-disabled={active}
|
||||
title={active ? "Stop it first" : undefined}
|
||||
>
|
||||
<PencilIcon />
|
||||
Edit
|
||||
</Link>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
if (await deleteDeployment(d.id)) router.push("/deployments");
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{d.startRequestedAt && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={d.requestedBy}
|
||||
what={`start this deployment (${d.runtimeName}${file ? `, ${file}` : ""}, context ${d.options.contextSize}${d.memoryMb ? `, ${formatBytes(d.memoryMb * 2 ** 20)} RAM limit` : ""})`}
|
||||
base={`/api/deployments/${d.id}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{d.state === "failed" && d.error && (
|
||||
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<Card>
|
||||
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
|
||||
<Stat
|
||||
label="CPU"
|
||||
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
|
||||
>
|
||||
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
|
||||
</Stat>
|
||||
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
|
||||
{d.stats && d.state === "running" && d.memoryMb ? (
|
||||
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
|
||||
)}
|
||||
</Stat>
|
||||
<Stat
|
||||
label={d.state === "starting" ? "Loading" : "Load time"}
|
||||
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
|
||||
>
|
||||
<span className="text-xs text-muted-foreground">until /health answered</span>
|
||||
</Stat>
|
||||
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
|
||||
</span>
|
||||
</Stat>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<LiveLog url={`/api/deployments/${d.id}/logs`} />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<Chat id={d.id} running={d.state === "running"} />
|
||||
<BenchmarkCard deploymentId={d.id} modelId={d.modelId} running={d.state === "running"} initial={benchmarks} />
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Endpoint</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2 text-xs">
|
||||
{internal ? (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<code className="font-mono break-all">{internal}</code>
|
||||
<CopyButton value={internal} label="Copy URL" />
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Not started yet.</span>
|
||||
)}
|
||||
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
|
||||
{published && (
|
||||
<div className="flex items-center justify-between gap-2 border-t pt-2">
|
||||
<code className="font-mono break-all">{published}</code>
|
||||
<CopyButton value={published} label="Copy URL" />
|
||||
</div>
|
||||
)}
|
||||
<span className="text-muted-foreground">
|
||||
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
|
||||
{d.options.requireApiKey && (
|
||||
<>
|
||||
{" "}
|
||||
Requires one of the{" "}
|
||||
<Link href="/settings/api-keys" className="underline">
|
||||
API keys
|
||||
</Link>{" "}
|
||||
as <code className="font-mono">Authorization: Bearer</code>.
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
|
||||
<dt className="text-muted-foreground">Container</dt>
|
||||
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
|
||||
<dt className="text-muted-foreground">Runs on</dt>
|
||||
<dd>
|
||||
{ACCELERATOR_LABEL[d.accelerator]}
|
||||
{d.accelerator === "nvidia" && ` · ${d.options.gpus?.length ? `${d.options.gpus.length} selected GPU${d.options.gpus.length === 1 ? "" : "s"}` : "all GPUs"}`}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Started</dt>
|
||||
<dd>
|
||||
<LocalTime value={d.startedAt} />
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Stopped</dt>
|
||||
<dd>
|
||||
<LocalTime value={d.stoppedAt} />
|
||||
</dd>
|
||||
{d.command && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Arguments</dt>
|
||||
<dd className="flex items-start gap-1">
|
||||
<code className="font-mono break-all">{d.command.join(" ")}</code>
|
||||
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Live container log (polls new lines every 1.5 s). */
|
||||
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
|
||||
function Chat({ id, running }: { id: string; running: boolean }) {
|
||||
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
|
||||
const [answer, setAnswer] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function send() {
|
||||
setBusy(true);
|
||||
setAnswer("");
|
||||
setError(null);
|
||||
setStats(null);
|
||||
const t0 = performance.now();
|
||||
let first: number | null = null;
|
||||
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
|
||||
let chunks = 0;
|
||||
try {
|
||||
const res = await fetch(`/api/deployments/${id}/chat`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
|
||||
});
|
||||
if (!res.ok || !res.body) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
|
||||
}
|
||||
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buf = "";
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buf += value;
|
||||
let nl: number;
|
||||
while ((nl = buf.indexOf("\n")) >= 0) {
|
||||
const line = buf.slice(0, nl).trim();
|
||||
buf = buf.slice(nl + 1);
|
||||
if (!line.startsWith("data:")) continue;
|
||||
const data = line.slice(5).trim();
|
||||
if (data === "[DONE]") continue;
|
||||
const j = JSON.parse(data);
|
||||
if (j.usage) usage = j.usage;
|
||||
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
|
||||
if (delta) {
|
||||
first ??= performance.now();
|
||||
chunks++;
|
||||
setAnswer((a) => a + delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
const total = (performance.now() - t0) / 1000;
|
||||
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Try it</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
<textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
rows={3}
|
||||
disabled={!running}
|
||||
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
|
||||
/>
|
||||
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
|
||||
<SendIcon />
|
||||
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
|
||||
</Button>
|
||||
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
|
||||
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-3 gap-2 text-center text-xs">
|
||||
<div>
|
||||
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
|
||||
<div className="text-muted-foreground">first token</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-semibold tabular-nums">
|
||||
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
|
||||
</div>
|
||||
<div className="text-muted-foreground">generation</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
|
||||
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getDeployment } from "@/lib/deployments";
|
||||
import { DeploymentForm } from "../../deployment-form";
|
||||
import { formData } from "../../form-data";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Edit deployment" };
|
||||
|
||||
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
|
||||
const { id } = await params;
|
||||
const [d, data] = await Promise.all([getDeployment(id), formData()]);
|
||||
if (!d) notFound();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
|
||||
{d.state !== "stopped" && d.state !== "failed" && (
|
||||
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
|
||||
)}
|
||||
<DeploymentForm
|
||||
{...data}
|
||||
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { getDeployment } from "@/lib/deployments";
|
||||
import { DeploymentDetail } from "./deployment-detail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
|
||||
const d = await getDeployment((await params).id);
|
||||
return { title: d ? d.name : "Deployment" };
|
||||
}
|
||||
|
||||
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
|
||||
const { id } = await params;
|
||||
const [d, runs] = await Promise.all([getDeployment(id), listBenchmarks({ deploymentId: id })]);
|
||||
if (!d) notFound();
|
||||
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} benchmarks={JSON.parse(JSON.stringify(runs))} />;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { toast } from "sonner";
|
||||
|
||||
async function call(url: string, method: string): Promise<boolean> {
|
||||
const res = await fetch(url, { method });
|
||||
if (res.ok) return true;
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return false;
|
||||
}
|
||||
|
||||
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
|
||||
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
|
||||
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,210 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ExternalLinkIcon,
|
||||
PlayIcon,
|
||||
RocketIcon,
|
||||
SquareIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { DeploymentStateBadge } from "@/components/deployment-state";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
|
||||
import type { DeploymentRow } from "@/lib/deployments";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { startDeployment, stopDeployment } from "./actions";
|
||||
|
||||
type Row = Omit<
|
||||
DeploymentRow,
|
||||
"startedAt" | "readyAt" | "stoppedAt" | "createdAt"
|
||||
> & {
|
||||
startedAt: string | null;
|
||||
readyAt: string | null;
|
||||
stoppedAt: string | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const isActive = (r: Row) =>
|
||||
r.desiredState === "running" ||
|
||||
r.state === "starting" ||
|
||||
r.state === "running" ||
|
||||
r.state === "stopping";
|
||||
|
||||
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
|
||||
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
|
||||
const [rows, setRows] = useState(initial);
|
||||
// "" = everything, "-" = created in the UI, else a token name.
|
||||
const [by, setBy] = useState("");
|
||||
const tokens = [
|
||||
...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
|
||||
].sort();
|
||||
const shown = rows.filter(
|
||||
(r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
|
||||
);
|
||||
const hostname = useHostname();
|
||||
const busy = rows.some(
|
||||
(r) =>
|
||||
r.state === "starting" ||
|
||||
r.state === "stopping" ||
|
||||
(r.desiredState === "running") !== (r.state === "running"),
|
||||
);
|
||||
|
||||
async function reload() {
|
||||
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(
|
||||
() => null,
|
||||
);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}
|
||||
useEffect(() => {
|
||||
const t = setInterval(reload, busy ? 2_000 : 5_000);
|
||||
return () => clearInterval(t);
|
||||
}, [busy]);
|
||||
|
||||
if (rows.length === 0) {
|
||||
return (
|
||||
<Card className="items-center gap-3 py-10 text-center">
|
||||
<RocketIcon className="size-8 text-muted-foreground" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No deployments yet. Pick a runtime and a downloaded model to start
|
||||
one.
|
||||
</p>
|
||||
<Link href="/deployments/new" className="text-sm underline">
|
||||
New deployment
|
||||
</Link>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{tokens.length > 0 && (
|
||||
<label className="flex items-center gap-2 self-end text-xs text-muted-foreground">
|
||||
Requested by
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-7 text-xs"
|
||||
aria-label="Requested by"
|
||||
>
|
||||
<option value="">Anyone</option>
|
||||
<option value="-">Created in Kaname</option>
|
||||
{tokens.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t} (API)
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
)}
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{shown.map((r) => {
|
||||
const file = r.options.modelFile
|
||||
? (quantGroup(r.options.modelFile) ?? r.options.modelFile)
|
||||
: null;
|
||||
const loadSecs =
|
||||
r.readyAt && r.startedAt
|
||||
? (new Date(r.readyAt).getTime() -
|
||||
new Date(r.startedAt).getTime()) /
|
||||
1000
|
||||
: null;
|
||||
return (
|
||||
<Card key={r.id} className="gap-3 px-4 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<Link
|
||||
href={`/deployments/${r.id}`}
|
||||
className="truncate font-medium hover:underline"
|
||||
>
|
||||
{r.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.repoId}
|
||||
{file && ` · ${file}`}
|
||||
{r.options.mmproj && " · vision"}
|
||||
{r.options.draftFile && " · MTP/draft"}
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{r.runtimeName}
|
||||
<RequestedByBadge
|
||||
name={r.requestedBy}
|
||||
className="h-4 text-[10px]"
|
||||
/>
|
||||
{r.protected && (
|
||||
<span className="text-emerald-700 dark:text-emerald-300">
|
||||
protected
|
||||
</span>
|
||||
)}
|
||||
{r.startRequestedAt && (
|
||||
<span className="text-amber-700 dark:text-amber-300">
|
||||
start awaits approval
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<DeploymentStateBadge
|
||||
state={r.state}
|
||||
desiredState={r.desiredState}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{r.state === "running" && r.stats
|
||||
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
|
||||
: r.state === "failed"
|
||||
? (r.error?.split("\n")[0] ?? "failed")
|
||||
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
|
||||
{r.state === "running" &&
|
||||
loadSecs != null &&
|
||||
` · loaded in ${loadSecs.toFixed(1)} s`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{r.state === "running" && webUiUrl(r, hostname) && (
|
||||
<a
|
||||
href={webUiUrl(r, hostname)!}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={buttonVariants({
|
||||
size: "xs",
|
||||
variant: "outline",
|
||||
})}
|
||||
>
|
||||
<ExternalLinkIcon />
|
||||
Web UI
|
||||
</a>
|
||||
)}
|
||||
{isActive(r) ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={async () =>
|
||||
(await stopDeployment(r.id)) && reload()
|
||||
}
|
||||
>
|
||||
<SquareIcon />
|
||||
Stop
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="xs"
|
||||
onClick={async () =>
|
||||
(await startDeployment(r.id)) && reload()
|
||||
}
|
||||
>
|
||||
<PlayIcon />
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import "server-only";
|
||||
import { listApiKeys } from "@/lib/api-keys";
|
||||
import { listDeployableModels } from "@/lib/deployments";
|
||||
import { applyOverrides } from "@/lib/hardware";
|
||||
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
|
||||
import { getHardwareOverrides } from "@/lib/settings";
|
||||
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
|
||||
|
||||
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
|
||||
export async function formData(): Promise<{
|
||||
runtimes: FormRuntime[];
|
||||
models: FormModel[];
|
||||
host: FormHost;
|
||||
apiKeyCount: number;
|
||||
}> {
|
||||
const [runtimes, models, docker, keys, overrides] = await Promise.all([
|
||||
listRuntimes(),
|
||||
listDeployableModels(),
|
||||
getDockerInfo(),
|
||||
listApiKeys(),
|
||||
getHardwareOverrides(),
|
||||
]);
|
||||
return {
|
||||
runtimes: runtimes.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
engine: r.engine,
|
||||
image: r.image,
|
||||
imageState: r.imageState,
|
||||
env: r.env,
|
||||
extraArgs: r.extraArgs,
|
||||
accelerator: r.accelerator,
|
||||
})),
|
||||
models,
|
||||
host: docker
|
||||
? {
|
||||
cpus: docker.cpus,
|
||||
memoryBytes: docker.memoryBytes,
|
||||
cpuFeatures: docker.cpuFeatures,
|
||||
nvidia: !!docker.nvidia,
|
||||
gpus: docker.gpus ?? [],
|
||||
hardwareGpus: applyOverrides(docker.hardware, overrides)?.gpus ?? [],
|
||||
}
|
||||
: null,
|
||||
apiKeyCount: keys.length,
|
||||
};
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { deployPreset } from "@/lib/deployments";
|
||||
import { DeploymentForm } from "../deployment-form";
|
||||
import { formData } from "../form-data";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "New deployment" };
|
||||
|
||||
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
|
||||
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
|
||||
const { model } = await searchParams;
|
||||
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">New deployment</h1>
|
||||
<DeploymentForm {...data} initial={preset ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { listDeployments } from "@/lib/deployments";
|
||||
import { getDockerInfo } from "@/lib/runtimes";
|
||||
import { DeploymentList } from "./deployment-list";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Deployments" };
|
||||
|
||||
export default async function DeploymentsPage() {
|
||||
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold">Deployments</h1>
|
||||
<Link href="/deployments/new" className={buttonVariants()}>
|
||||
New deployment
|
||||
</Link>
|
||||
</div>
|
||||
{!docker?.connected && (
|
||||
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
|
||||
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
|
||||
<Link href="/settings/runtimes" className="underline">
|
||||
Settings → Runtimes
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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/enums";
|
||||
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 { PageHero } from "@/components/hero/page-hero";
|
||||
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 (
|
||||
<PageHero title={`Edit ${endpoint.name}`} painting={{ view: 0.55, focus: [0.75, 0.35], anchor: [0.65, 0.35] }}>
|
||||
<EndpointForm initial={endpoint} />
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
"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 { PageHero } from "@/components/hero/page-hero";
|
||||
import type { EndpointView } from "@/lib/endpoints";
|
||||
import { ProbeResult } from "../endpoint-form";
|
||||
import { EndpointStatus } from "../endpoint-status";
|
||||
|
||||
/** The page banner: name, URL, connection test, edit and delete; the page's content below it. */
|
||||
export function EndpointHeader({
|
||||
endpoint,
|
||||
runCount,
|
||||
children,
|
||||
}: {
|
||||
endpoint: EndpointView;
|
||||
runCount: number;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
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 (
|
||||
<PageHero
|
||||
title={endpoint.name}
|
||||
description={
|
||||
<span className="break-all">
|
||||
{endpoint.baseUrl}
|
||||
{endpoint.hasApiKey ? " · API key set" : ""}
|
||||
</span>
|
||||
}
|
||||
painting={{ view: 0.55, focus: [0.75, 0.35], anchor: [0.65, 0.35] }}
|
||||
actions={
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{probe && <ProbeResult probe={probe} />}
|
||||
{children}
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
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 (
|
||||
<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/55 px-4 py-3 text-xs backdrop-blur-md whitespace-pre-wrap text-muted-foreground ring-1 ring-foreground/10">{endpoint.hardware.description}</p>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</EndpointHeader>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
"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 } from "@/lib/db/enums";
|
||||
import type { EndpointHardware, 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 { PageHero } from "@/components/hero/page-hero";
|
||||
import { EndpointForm } from "../endpoint-form";
|
||||
|
||||
export const metadata: Metadata = { title: "New endpoint" };
|
||||
|
||||
export default function NewEndpointPage() {
|
||||
return (
|
||||
<PageHero title="New endpoint" painting={{ view: 0.55, focus: [0.75, 0.35], anchor: [0.65, 0.35] }}>
|
||||
<EndpointForm />
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -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 { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { listEndpoints } from "@/lib/endpoints";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
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 = r.headline.decode;
|
||||
if (r.kind === "eval" && cur.quality == null) cur.quality = r.qualityScore;
|
||||
latest.set(r.endpointId, cur);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageHero
|
||||
title="Endpoints"
|
||||
description="OpenAI-compatible servers to benchmark. They run elsewhere; Kaname only sends them requests."
|
||||
painting={{ view: 0.6, focus: [0.75, 0.35], anchor: [0.62, 0.35] }}
|
||||
actions={
|
||||
<Link href="/endpoints/new" className={buttonVariants()}>
|
||||
<PlusIcon />
|
||||
Add endpoint
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
|
||||
{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>
|
||||
)}
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { CirclePlusIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
/** Multi-select dropdown for one facet, with per-value counts. */
|
||||
/** Multi-select filter for one facet (a dashed pill in the table toolbar), with per-value counts. */
|
||||
export function FacetFilter({
|
||||
label,
|
||||
values,
|
||||
@@ -30,13 +32,26 @@ export function FacetFilter({
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={<Button variant={active ? "secondary" : "outline"} size="sm" disabled={values.length === 0} />}
|
||||
render={<Button variant="outline" size="sm" className="h-8 border-dashed bg-transparent" disabled={values.length === 0} />}
|
||||
>
|
||||
<CirclePlusIcon className="opacity-60" />
|
||||
{label}
|
||||
{active && <span className="rounded bg-background/60 px-1 text-xs tabular-nums">{selected.length}</span>}
|
||||
<ChevronDownIcon className="opacity-60" />
|
||||
{active && (
|
||||
<>
|
||||
<span className="mx-0.5 h-4 w-px bg-border" aria-hidden />
|
||||
{selected.length > 2 ? (
|
||||
<span className="rounded bg-muted px-1.5 text-xs font-normal">{selected.length} selected</span>
|
||||
) : (
|
||||
selected.map((v) => (
|
||||
<span key={v} className="max-w-28 truncate rounded bg-muted px-1.5 text-xs font-normal">
|
||||
{format(v)}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-auto min-w-48">
|
||||
<DropdownMenuContent className="w-auto min-w-52">
|
||||
{values.map(([value, count]) => (
|
||||
<DropdownMenuCheckboxItem
|
||||
key={value}
|
||||
@@ -49,6 +64,14 @@ export function FacetFilter({
|
||||
<span className="ml-4 text-xs text-muted-foreground tabular-nums">{count}</span>
|
||||
</DropdownMenuCheckboxItem>
|
||||
))}
|
||||
{active && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => onChange([])} className="justify-center text-muted-foreground">
|
||||
Clear {label.toLowerCase()}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ApprovalBar } from "@/components/approval-bar";
|
||||
import { cancelJob } from "@/components/job-actions";
|
||||
import { JobFilesTable } from "@/components/job-files-table";
|
||||
import { JobProgress } from "@/components/job-progress";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
@@ -24,7 +22,6 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
const files = snapshot?.files ?? [];
|
||||
const open = OPEN.includes(job.state);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const logRef = useRef<HTMLDivElement>(null);
|
||||
const [follow, setFollow] = useState(true);
|
||||
@@ -42,18 +39,19 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
const duration = job.startedAt != null ? ((job.finishedAt ?? now) - job.startedAt) / 1000 : null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-xl font-semibold">
|
||||
<PageHero
|
||||
title={
|
||||
<>
|
||||
{jobLabel(job)} ·{" "}
|
||||
<Link href={`/${job.repoId}`} className="hover:underline">
|
||||
{job.repoId}
|
||||
</Link>
|
||||
</h1>
|
||||
<RequestedByBadge name={job.requestedBy} />
|
||||
{open && (
|
||||
</>
|
||||
}
|
||||
painting={{ view: 0.5, focus: [0.3, 0.55], anchor: [0.7, 0.45] }}
|
||||
actions={
|
||||
open && (
|
||||
<Button
|
||||
className="ml-auto"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={busy || job.cancelRequested}
|
||||
@@ -65,10 +63,9 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
>
|
||||
{job.cancelRequested ? "Cancelling…" : "Cancel"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{job.state === "pending_approval" && <ApprovalBar job={job} onRemoved={() => router.push("/")} />}
|
||||
)
|
||||
}
|
||||
>
|
||||
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
@@ -76,12 +73,6 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">Created</dt>
|
||||
<dd><LocalTime value={job.createdAt} /></dd>
|
||||
{job.requestedBy && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Requested by</dt>
|
||||
<dd>{job.requestedBy} (API token)</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Started</dt>
|
||||
<dd>
|
||||
<LocalTime value={job.startedAt} />
|
||||
@@ -157,6 +148,6 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
+21
-13
@@ -2,34 +2,39 @@ import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { auth, signOut } from "@/auth";
|
||||
import { AppNav } from "@/components/app-nav";
|
||||
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
|
||||
import { BackdropProvider } from "@/components/hero/dot-painting";
|
||||
import { LabelSettingsProvider } from "@/components/labels";
|
||||
import { UserMenu } from "@/components/user-menu";
|
||||
import { WorkerIndicator } from "@/components/worker-indicator";
|
||||
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
const session = await auth();
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const [worker, fileRoles, recommendedRoles] = await Promise.all([
|
||||
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
|
||||
getWorkerStatus(),
|
||||
getFileRoleStyles(),
|
||||
getRecommendedRoles(),
|
||||
getBackdrop(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col overflow-x-clip">
|
||||
<header className="border-b">
|
||||
<div className="mx-auto flex h-14 max-w-7xl items-center gap-3 px-4 sm:gap-6">
|
||||
<Link href="/" className="flex items-center gap-2 font-semibold">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/icon.svg" alt="" className="size-6" />
|
||||
Kaname
|
||||
<span className="hidden text-xs font-normal text-muted-foreground sm:inline">{process.env.APP_VERSION ?? "dev"}</span>
|
||||
</Link>
|
||||
<AppNav />
|
||||
<div className="ml-auto flex items-center gap-3">
|
||||
{/* Floating menu: two pills (name + navigation, status + account) over the page. */}
|
||||
<header className="pointer-events-none sticky top-0 z-40">
|
||||
<div className="mx-auto flex h-16 max-w-7xl items-center justify-between gap-3 px-4 pt-3">
|
||||
<div className="pointer-events-auto flex h-12 min-w-0 items-center gap-3 rounded-2xl bg-black/80 px-3 text-white shadow-lg ring-1 ring-white/10 backdrop-blur-md sm:gap-5 dark [color-scheme:dark]">
|
||||
<Link href="/" className="flex items-center gap-2 pl-1 font-semibold">
|
||||
Kaname
|
||||
<span className="hidden text-xs font-normal text-muted-foreground sm:inline">{process.env.APP_VERSION ?? "dev"}</span>
|
||||
</Link>
|
||||
<AppNav />
|
||||
</div>
|
||||
<div className="pointer-events-auto flex h-12 items-center gap-3 rounded-2xl bg-black/80 px-3 text-white shadow-lg ring-1 ring-white/10 backdrop-blur-md dark [color-scheme:dark]">
|
||||
<CommandPaletteButton />
|
||||
<WorkerIndicator initial={worker} />
|
||||
<UserMenu
|
||||
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
|
||||
@@ -41,8 +46,11 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<CommandPalette />
|
||||
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
<BackdropProvider backdrop={backdrop}>
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
</BackdropProvider>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { LibraryHero } from "@/components/hero/library-hero";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
import { AddModelPanel, AddModelToggle } from "./add-model-panel";
|
||||
|
||||
type HeroProps = Omit<React.ComponentProps<typeof LibraryHero>, "action" | "initialWorker">;
|
||||
type PanelProps = Omit<React.ComponentProps<typeof AddModelPanel>, "open" | "setOpen">;
|
||||
|
||||
/** The hero with the "Add model" toggle, and the form it opens below. */
|
||||
export function LibraryTop({ hero, panel, worker, defaultOpen }: { hero: HeroProps; panel: PanelProps; worker: WorkerStatus; defaultOpen: boolean }) {
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
return (
|
||||
<>
|
||||
<LibraryHero {...hero} initialWorker={worker} action={<AddModelToggle open={open} onToggle={() => setOpen(!open)} />} />
|
||||
{/* Above the hero, which runs on behind what follows. */}
|
||||
<div className="relative z-10 flex flex-col gap-4 empty:hidden">
|
||||
<AddModelPanel {...panel} open={open} setOpen={setOpen} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+151
-118
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon, SearchIcon, XIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
@@ -8,19 +8,17 @@ import { JobProgress, JobStateBadge } from "@/components/job-progress";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
|
||||
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { TagBadge, TagDot } from "@/components/tag-badge";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import type { ModelStatus } from "@/lib/db/schema";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import type { JobSnapshot } from "@/lib/jobs";
|
||||
import type { LibraryRow } from "@/lib/library";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
EMPTY_FILTERS,
|
||||
type Facet,
|
||||
@@ -29,12 +27,14 @@ import {
|
||||
type Filters,
|
||||
matchesFilters,
|
||||
matchesQuery,
|
||||
PENDING_APPROVAL,
|
||||
queryTerms,
|
||||
type SearchableModel,
|
||||
searchText,
|
||||
} from "@/lib/search";
|
||||
import { FacetFilter } from "./facet-filter";
|
||||
|
||||
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
const PAGE_SIZES = [10, 25, 50, 100];
|
||||
|
||||
const FACET_LABEL: Record<Facet, string> = {
|
||||
author: "Author",
|
||||
@@ -42,13 +42,12 @@ const FACET_LABEL: Record<Facet, string> = {
|
||||
quant: "Quant",
|
||||
tag: "Tag",
|
||||
status: "Status",
|
||||
requester: "Requested by",
|
||||
};
|
||||
|
||||
const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (MODEL_STATUS[v as ModelStatus]?.label ?? v));
|
||||
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
|
||||
|
||||
function toSearchable(r: LibraryRow): SearchableModel {
|
||||
return {
|
||||
const m: SearchableModel = {
|
||||
repoId: r.repoId,
|
||||
author: r.author,
|
||||
families: r.families,
|
||||
@@ -66,9 +65,8 @@ function toSearchable(r: LibraryRow): SearchableModel {
|
||||
: r.updateAvailable
|
||||
? "update available"
|
||||
: null,
|
||||
requestedBy: r.requestedBy,
|
||||
pendingApproval: r.pendingApproval,
|
||||
};
|
||||
return { ...m, text: searchText(m) };
|
||||
}
|
||||
|
||||
/** Search + facet filters (kept in the URL) over the library table. */
|
||||
@@ -77,6 +75,8 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
const pathname = usePathname();
|
||||
const params = useSearchParams();
|
||||
const [query, setQuery] = useState(() => params.get("q") ?? "");
|
||||
const [page, setPage] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [filters, setFilters] = useState<Filters>(() => {
|
||||
const f = { ...EMPTY_FILTERS };
|
||||
for (const facet of FACETS) f[facet] = params.getAll(facet);
|
||||
@@ -90,25 +90,42 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
const qs = p.toString();
|
||||
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
// A new search or filter starts on the first page.
|
||||
const updateQuery = (q: string) => {
|
||||
setQuery(q);
|
||||
setPage(0);
|
||||
sync(q, filters);
|
||||
};
|
||||
const updateFilter = (facet: Facet, values: string[]) => {
|
||||
const next = { ...filters, [facet]: values };
|
||||
setFilters(next);
|
||||
setPage(0);
|
||||
sync(query, next);
|
||||
};
|
||||
const clearAll = () => {
|
||||
setQuery("");
|
||||
setFilters(EMPTY_FILTERS);
|
||||
setPage(0);
|
||||
sync("", EMPTY_FILTERS);
|
||||
};
|
||||
|
||||
// Search text and counts are computed once per change of rows, query or filters, not on every
|
||||
// render (live job progress re-renders this table while downloads run).
|
||||
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
|
||||
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
|
||||
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
|
||||
const terms = useMemo(() => queryTerms(query), [query]);
|
||||
const visible = useMemo(
|
||||
() => rows.filter((_, i) => matchesQuery(searchable[i], terms) && matchesFilters(searchable[i], filters)),
|
||||
[rows, searchable, terms, filters],
|
||||
);
|
||||
const facetOptions = useMemo(
|
||||
() => Object.fromEntries(FACETS.map((facet) => [facet, facetCounts(searchable, facet, terms, filters)])) as Record<Facet, [string, number][]>,
|
||||
[searchable, terms, filters],
|
||||
);
|
||||
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
|
||||
const pages = Math.max(1, Math.ceil(visible.length / pageSize));
|
||||
const current = Math.min(page, pages - 1);
|
||||
const shown = visible.slice(current * pageSize, (current + 1) * pageSize);
|
||||
|
||||
const { snapshot } = useLive();
|
||||
const openJobs = new Map<string, JobSnapshot>();
|
||||
@@ -117,111 +134,80 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="relative min-w-56 flex-1">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => updateQuery(e.target.value)}
|
||||
placeholder="Search repo, author, family, quant, tag…"
|
||||
className="pl-8"
|
||||
aria-label="Search models"
|
||||
/>
|
||||
// Glass: the painting from the hero shows through, blurred.
|
||||
<Card className="relative z-10 gap-0 overflow-hidden bg-card/55 py-0 backdrop-blur-md">
|
||||
{/* Toolbar: title, search and filters, part of the table. */}
|
||||
<div className="flex flex-col gap-3 border-b px-4 py-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 className="mr-1 text-base font-semibold">Models</h2>
|
||||
<span className="rounded-md bg-muted px-1.5 text-xs text-muted-foreground tabular-nums">
|
||||
{anyActive ? `${visible.length} of ${rows.length}` : rows.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* Same height and border as the filter pills. */}
|
||||
<div className="relative w-full sm:w-64">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => updateQuery(e.target.value)}
|
||||
placeholder="Search models…"
|
||||
className="h-8 bg-transparent pl-8 text-sm"
|
||||
aria-label="Search models"
|
||||
/>
|
||||
</div>
|
||||
{FACETS.map((facet) => (
|
||||
<FacetFilter
|
||||
key={facet}
|
||||
label={FACET_LABEL[facet]}
|
||||
values={facetOptions[facet]}
|
||||
selected={filters[facet]}
|
||||
onChange={(v) => updateFilter(facet, v)}
|
||||
format={facet === "status" ? statusLabel : undefined}
|
||||
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : undefined}
|
||||
/>
|
||||
))}
|
||||
{anyActive && (
|
||||
<Button variant="ghost" size="sm" className="h-8" onClick={clearAll}>
|
||||
Reset
|
||||
<XIcon />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{FACETS.map((facet) => (
|
||||
<FacetFilter
|
||||
key={facet}
|
||||
label={FACET_LABEL[facet]}
|
||||
values={facetCounts(searchable, facet, query, filters)}
|
||||
selected={filters[facet]}
|
||||
onChange={(v) => updateFilter(facet, v)}
|
||||
format={facet === "status" ? statusLabel : undefined}
|
||||
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{anyActive && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{visible.length} of {rows.length} models
|
||||
</span>
|
||||
{FACETS.flatMap((facet) =>
|
||||
filters[facet].map((v) => (
|
||||
<Badge key={`${facet}:${v}`} variant="secondary" className="gap-1">
|
||||
{facet === "tag" && <TagDot name={v} color={tagColors.get(v)} />}
|
||||
{FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove filter ${v}`}
|
||||
onClick={() => updateFilter(facet, filters[facet].filter((x) => x !== v))}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
)),
|
||||
)}
|
||||
<Button variant="ghost" size="xs" onClick={clearAll}>
|
||||
Clear all
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>No matching models</CardTitle>
|
||||
<CardDescription>Try a different search or remove a filter.</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<div className="flex flex-col items-center gap-1 px-4 py-12 text-center">
|
||||
<p className="text-sm font-medium">No matching models</p>
|
||||
<p className="text-sm text-muted-foreground">Try a different search or remove a filter.</p>
|
||||
</div>
|
||||
) : (
|
||||
<Card className="py-0">
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Model</TableHead>
|
||||
<TableHead className="pl-4">Model</TableHead>
|
||||
<TableHead>Selection</TableHead>
|
||||
<TableHead className="text-right">Size</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
|
||||
<TableHead className="w-56">Status</TableHead>
|
||||
<TableHead className="w-24">
|
||||
<span className="sr-only">Deploy</span>
|
||||
</TableHead>
|
||||
<TableHead className="w-56 pr-4">Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{visible.map((r) => {
|
||||
{shown.map((r) => {
|
||||
const job = openJobs.get(r.id);
|
||||
const base = r.baseModels[0];
|
||||
return (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link href={`/${r.repoId}`} className="font-medium hover:underline">
|
||||
{r.repoId}
|
||||
<TableCell className="pl-4 whitespace-normal">
|
||||
<Link href={`/${r.repoId}`} className="hover:underline">
|
||||
<span className="text-muted-foreground">{r.author}/</span>
|
||||
<span className="font-medium">{r.repoId.slice(r.author.length + 1)}</span>
|
||||
</Link>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
<RequestedByBadge name={r.requestedBy} className="h-4 text-[10px]" />
|
||||
{base && base !== r.repoId && <span>base {base}</span>}
|
||||
{r.architecture && <span>{r.architecture}</span>}
|
||||
{r.deployments.map((d) => (
|
||||
<Link
|
||||
key={d.id}
|
||||
href={`/deployments/${d.id}`}
|
||||
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
|
||||
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
|
||||
>
|
||||
<RocketIcon className="size-3" />
|
||||
<span className="max-w-40 truncate">{d.name}</span>
|
||||
<span
|
||||
className={cn(
|
||||
"size-1.5 rounded-full",
|
||||
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
|
||||
)}
|
||||
/>
|
||||
</Link>
|
||||
))}
|
||||
{r.tags.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
@@ -233,23 +219,41 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
))}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} file${r.fileCount === 1 ? "" : "s"}`}
|
||||
<TableCell>
|
||||
{r.quants.length > 0 ? (
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{r.quants.map((q) => (
|
||||
<span key={q} className="rounded-md border px-1.5 font-mono text-[11px] leading-5">
|
||||
{q}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{r.fileCount} file{r.fileCount === 1 ? "" : "s"}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
<code className="font-mono text-xs" title={r.pinnedSha}>
|
||||
{r.trackedRevision}@{shortSha(r.pinnedSha)}
|
||||
</code>
|
||||
{r.source === "local" ? (
|
||||
<span className="text-xs text-muted-foreground" title="A folder without a Hugging Face repo">
|
||||
local
|
||||
</span>
|
||||
) : (
|
||||
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
|
||||
{r.trackedRevision}@{shortSha(r.pinnedSha)}
|
||||
</code>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
|
||||
<LocalTime value={r.downloadedAt} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TableCell className="pr-4">
|
||||
{job ? (
|
||||
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
|
||||
<JobStateBadge job={job} />
|
||||
{job.state !== "queued" && job.state !== "pending_approval" && <JobProgress job={job} compact />}
|
||||
{job.state !== "queued" && <JobProgress job={job} compact />}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="flex flex-wrap gap-1">
|
||||
@@ -263,26 +267,55 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{r.deployable && (
|
||||
<Link
|
||||
href={`/deployments/new?model=${r.id}`}
|
||||
className={buttonVariants({ variant: "outline", size: "xs" })}
|
||||
title="Serve this model with a runtime"
|
||||
aria-label={`Deploy ${r.repoId}`}
|
||||
>
|
||||
<RocketIcon />
|
||||
Deploy
|
||||
</Link>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t px-4 py-2.5 text-sm">
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
{current * pageSize + 1}–{Math.min(visible.length, (current + 1) * pageSize)} of {visible.length}
|
||||
</span>
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="flex items-center gap-2 text-muted-foreground">
|
||||
<span className="hidden sm:inline">Rows per page</span>
|
||||
<NativeSelect
|
||||
value={pageSize}
|
||||
onChange={(e) => {
|
||||
setPageSize(Number(e.target.value));
|
||||
setPage(0);
|
||||
}}
|
||||
className="h-8 w-20"
|
||||
aria-label="Rows per page"
|
||||
>
|
||||
{PAGE_SIZES.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
Page {current + 1} of {pages}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setPage(0)} disabled={current === 0} aria-label="First page">
|
||||
<ChevronsLeftIcon />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setPage(current - 1)} disabled={current === 0} aria-label="Previous page">
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setPage(current + 1)} disabled={current >= pages - 1} aria-label="Next page">
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setPage(pages - 1)} disabled={current >= pages - 1} aria-label="Last page">
|
||||
<ChevronsRightIcon />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
+17
-8
@@ -1,21 +1,30 @@
|
||||
import { auth } from "@/auth";
|
||||
import { listLibrary } from "@/lib/library";
|
||||
import { listLocalFolders } from "@/lib/local-folders";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
import { AddModelPanel } from "./add-model-panel";
|
||||
import { LibraryTop } from "./library-top";
|
||||
import { LibraryView } from "./library-view";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function LibraryPage() {
|
||||
const [rows, worker, folders] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders()]);
|
||||
export default async function LibraryPage({ searchParams }: PageProps<"/">) {
|
||||
const [rows, worker, folders, session] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders(), auth()]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Opens by default while the library is empty and there's nothing on disk to import. */}
|
||||
<AddModelPanel
|
||||
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
|
||||
defaultOpen={rows.length === 0 && folders.length === 0}
|
||||
folders={folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes }))}
|
||||
{/* The form opens by default while the library is empty and there's nothing on disk to import,
|
||||
and with ?add=1 (the ⌘K palette's "Add model"). */}
|
||||
<LibraryTop
|
||||
worker={worker}
|
||||
defaultOpen={(rows.length === 0 && folders.length === 0) || (await searchParams).add === "1"}
|
||||
hero={{
|
||||
name: session?.user?.name ?? null,
|
||||
models: rows.length,
|
||||
libraryBytes: rows.reduce((s, r) => s + r.presentBytes, 0),
|
||||
updates: rows.filter((r) => r.updateAvailable && (r.hubState === "available" || !r.hubState)).length,
|
||||
goneFromHub: rows.filter((r) => r.hubState === "repo_missing" || r.hubState === "commit_missing").length,
|
||||
}}
|
||||
panel={{ freeBytes: worker.online ? worker.modelsDirFreeBytes : null, folders }}
|
||||
/>
|
||||
{rows.length > 0 && <LibraryView rows={rows} />}
|
||||
</div>
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiKeyRow } from "@/lib/api-keys";
|
||||
|
||||
/** Keys that deployments with "Require an API key" accept. */
|
||||
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
|
||||
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Runtime API keys</CardTitle>
|
||||
<CardDescription>
|
||||
Deployments with “Require an API key” accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer <key></code>.
|
||||
Changes apply when a deployment (re)starts.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<NewKeyRow onCreated={setCreated} />
|
||||
{created && (
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
|
||||
<p className="text-sm font-medium">API key “{created.name}” added. You can show it again from the list.</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.key}</code>
|
||||
<CopyButton value={created.key} label="Copy API key" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{keys.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No API keys yet.</p>
|
||||
) : (
|
||||
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
|
||||
{keys.map((k) => (
|
||||
<KeyRow key={k.id} apiKey={k} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [key, setKey] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function create(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, key: key.trim() || undefined }),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
|
||||
return;
|
||||
}
|
||||
onCreated({ name: json.name, key: json.key });
|
||||
setName("");
|
||||
setKey("");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
|
||||
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
|
||||
<Input
|
||||
value={key}
|
||||
maxLength={256}
|
||||
disabled={busy}
|
||||
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
|
||||
placeholder="Key (empty: generate one)"
|
||||
aria-label="Key value"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
className="font-mono text-xs md:text-xs"
|
||||
/>
|
||||
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
|
||||
<PlusIcon />
|
||||
Add
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
|
||||
const router = useRouter();
|
||||
const [shown, setShown] = useState<string | null>(null);
|
||||
|
||||
async function toggle() {
|
||||
if (shown) return setShown(null);
|
||||
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
|
||||
else setShown(json.key);
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
|
||||
if (!res.ok) toast.error(`Could not delete (${res.status})`);
|
||||
else toast.success(`API key "${apiKey.name}" deleted`);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 px-4 py-2.5">
|
||||
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
|
||||
{shown ? (
|
||||
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
|
||||
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
|
||||
{shown}
|
||||
</code>
|
||||
<CopyButton value={shown} label="Copy API key" />
|
||||
</span>
|
||||
) : (
|
||||
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
|
||||
)}
|
||||
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
|
||||
{shown ? <EyeOffIcon /> : <EyeIcon />}
|
||||
</Button>
|
||||
<span className="hidden text-xs text-muted-foreground sm:inline">
|
||||
<LocalTime value={apiKey.createdAt} />
|
||||
</span>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
|
||||
<Trash2Icon />
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete API key “{apiKey.name}”?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listApiKeys } from "@/lib/api-keys";
|
||||
import { ApiKeySettings } from "./api-key-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Runtime API keys · Settings" };
|
||||
|
||||
export default async function ApiKeySettingsPage() {
|
||||
return <ApiKeySettings keys={await listApiKeys()} />;
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ShieldCheckIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { type ApprovalMode, type Guardrails, parseAuthorList } from "@/lib/agent-guardrails";
|
||||
|
||||
const GB = 1_000_000_000;
|
||||
const toGb = (b: number) => String(Math.round((b / GB) * 1000) / 1000);
|
||||
|
||||
/** Limits for downloads requested through the API. Saved together with one button. */
|
||||
export function GuardrailSettings({ initial }: { initial: Guardrails }) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
|
||||
const [maxGb, setMaxGb] = useState(toGb(initial.maxRequestBytes));
|
||||
const [minFreeGb, setMinFreeGb] = useState(toGb(initial.minFreeBytes));
|
||||
const [maxJobs, setMaxJobs] = useState(String(initial.maxOpenJobs));
|
||||
const [authors, setAuthors] = useState(initial.allowedAuthors.join(", "));
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
let authorError: string | null = null;
|
||||
let authorList: string[] = [];
|
||||
try {
|
||||
authorList = parseAuthorList(authors);
|
||||
} catch (err) {
|
||||
authorError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
const num = (s: string) => Number(s.replace(",", "."));
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (authorError) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/agent", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
approvalMode: mode,
|
||||
maxRequestBytes: Math.round(num(maxGb) * GB),
|
||||
minFreeBytes: Math.round(num(minFreeGb) * GB),
|
||||
maxOpenJobs: Math.round(num(maxJobs)),
|
||||
allowedAuthors: authorList,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
|
||||
toast.success("Guardrails saved");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<ShieldCheckIcon className="size-4 text-muted-foreground" />
|
||||
Guardrails for API downloads
|
||||
</CardTitle>
|
||||
<CardDescription>Apply to every download requested with a token, across all tokens. Downloads you start in the UI are not affected.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={save} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="g-mode">Approval</Label>
|
||||
<NativeSelect id="g-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
|
||||
<option value="approve">Ask me: requests wait as “pending approval”</option>
|
||||
<option value="auto">Automatic: downloads start right away</option>
|
||||
</NativeSelect>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="g-max">Max size per request (GB)</Label>
|
||||
<Input id="g-max" value={maxGb} onChange={(e) => setMaxGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="g-free">Keep free on the models folder (GB)</Label>
|
||||
<Input id="g-free" value={minFreeGb} onChange={(e) => setMinFreeGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="g-jobs">Agent jobs at once</Label>
|
||||
<Input id="g-jobs" value={maxJobs} onChange={(e) => setMaxJobs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="g-authors">Allowed authors</Label>
|
||||
<Input id="g-authors" value={authors} onChange={(e) => setAuthors(e.target.value)} placeholder="Empty: any author. e.g. unsloth, ggml-org, Qwen" aria-invalid={!!authorError} />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{authorError ?? "Hugging Face users or organizations (the part before the slash), comma-separated."}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
“Agent jobs at once” counts requests that are pending approval, queued or downloading. The free-space check also subtracts what other open
|
||||
downloads still need.
|
||||
</p>
|
||||
<Button type="submit" className="self-start" disabled={busy || !!authorError}>
|
||||
Save guardrails
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listActivity } from "@/lib/agent-activity";
|
||||
import { listTokens } from "@/lib/api-tokens";
|
||||
import { listRuntimes } from "@/lib/runtimes";
|
||||
import { getGuardrails, getTuning } from "@/lib/settings";
|
||||
import { GuardrailSettings } from "./guardrail-settings";
|
||||
import { TokenSettings } from "./token-settings";
|
||||
import { TuningSettings } from "./tuning-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "API tokens · Settings" };
|
||||
|
||||
export default async function ApiTokenSettingsPage() {
|
||||
const [tokens, guardrails, tuning, runtimes] = await Promise.all([listTokens(), getGuardrails(), getTuning(), listRuntimes()]);
|
||||
const activity = Object.fromEntries(
|
||||
await Promise.all(
|
||||
tokens.map(async (t) => [t.id, (await listActivity(t.id, 50)).map((a) => ({ ...a, createdAt: a.createdAt.toISOString() }))] as const),
|
||||
),
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<TokenSettings tokens={tokens} activity={activity} />
|
||||
<GuardrailSettings initial={guardrails} />
|
||||
<TuningSettings initial={tuning} runtimes={runtimes.map((r) => ({ id: r.id, name: r.name, pulled: r.imageState === "present" }))} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,390 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { BotIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { SCOPE_LABEL } from "@/lib/token-scopes";
|
||||
import type { ApiTokenRow } from "@/lib/api-tokens";
|
||||
import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
|
||||
|
||||
/** Bearer tokens for /api/v1 (e.g. an AI agent). The token is shown once, then only its prefix. */
|
||||
export function TokenSettings({
|
||||
tokens,
|
||||
activity,
|
||||
}: {
|
||||
tokens: ApiTokenRow[];
|
||||
activity: Record<string, ActivityItem[]>;
|
||||
}) {
|
||||
const [created, setCreated] = useState<{
|
||||
name: string;
|
||||
token: string;
|
||||
} | null>(null);
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API tokens</CardTitle>
|
||||
<CardDescription>
|
||||
For programs and agents calling Kaname's API at{" "}
|
||||
<code className="font-mono text-xs">/api/v1</code> with{" "}
|
||||
<code className="font-mono text-xs">
|
||||
Authorization: Bearer <token>
|
||||
</code>
|
||||
. No token can delete models or files, change settings, or manage
|
||||
runtimes and tokens.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<NewTokenForm onCreated={setCreated} />
|
||||
{created && (
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
|
||||
<p className="text-sm font-medium">
|
||||
Token “{created.name}” created. Copy it now: it is not
|
||||
shown again.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">
|
||||
{created.token}
|
||||
</code>
|
||||
<CopyButton value={created.token} label="Copy token" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tokens.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No tokens yet.</p>
|
||||
) : (
|
||||
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
|
||||
{tokens.map((t) => (
|
||||
<TokenRow key={t.id} token={t} activity={activity[t.id] ?? []} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function NewTokenForm({
|
||||
onCreated,
|
||||
}: {
|
||||
onCreated: (t: { name: string; token: string }) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [scopes, setScopes] = useState<TokenScope[]>(["models:read"]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function create(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/api-tokens", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, scopes }),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok)
|
||||
return toast.error(
|
||||
json.error?.message ?? `Could not create the token (${res.status})`,
|
||||
);
|
||||
onCreated({ name: name.trim().toLowerCase(), token: json.token });
|
||||
setName("");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={create}
|
||||
className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
maxLength={40}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))
|
||||
}
|
||||
placeholder="Name, e.g. hermes"
|
||||
aria-label="Token name"
|
||||
className="max-w-56"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={busy || !name || scopes.length === 0}
|
||||
>
|
||||
<PlusIcon />
|
||||
Create token
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{TOKEN_SCOPES.map((s) => (
|
||||
<label
|
||||
key={s}
|
||||
className="flex cursor-pointer items-start gap-2 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
checked={scopes.includes(s)}
|
||||
onCheckedChange={(v) =>
|
||||
setScopes((cur) =>
|
||||
v ? [...cur, s] : cur.filter((x) => x !== s),
|
||||
)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span className="flex flex-col">
|
||||
<code className="font-mono text-xs">{s}</code>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{SCOPE_LABEL[s]}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The name is shown as “requested by” on everything the token
|
||||
asks for.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function TokenRow({
|
||||
token,
|
||||
activity,
|
||||
}: {
|
||||
token: ApiTokenRow;
|
||||
activity: ActivityItem[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const revoked = !!token.revokedAt;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [scopes, setScopes] = useState<TokenScope[]>(token.scopes);
|
||||
const [showActivity, setShowActivity] = useState(false);
|
||||
|
||||
async function saveScopes() {
|
||||
const res = await fetch(`/api/api-tokens/${token.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ scopes }),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok)
|
||||
return void toast.error(json.error?.message ?? `Failed (${res.status})`);
|
||||
toast.success(`Scopes of "${token.name}" changed`);
|
||||
setEditing(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function act(method: "POST" | "DELETE") {
|
||||
const res = await fetch(`/api/api-tokens/${token.id}`, { method });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) toast.error(json.error?.message ?? `Failed (${res.status})`);
|
||||
else
|
||||
toast.success(
|
||||
method === "POST"
|
||||
? `Token "${token.name}" revoked`
|
||||
: `Token "${token.name}" deleted`,
|
||||
);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 px-4 py-2.5">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<BotIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{token.name}</span>
|
||||
<code className="font-mono text-xs text-muted-foreground">
|
||||
{token.prefix}…
|
||||
</code>
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{token.scopes.map((s) => (
|
||||
<Badge key={s} variant="outline" className="font-mono text-[10px]">
|
||||
{s}
|
||||
</Badge>
|
||||
))}
|
||||
</span>
|
||||
{revoked && <Badge variant="destructive">revoked</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{token.lastUsedAt ? (
|
||||
<>
|
||||
used <LocalTime value={token.lastUsedAt} />
|
||||
</>
|
||||
) : (
|
||||
"never used"
|
||||
)}
|
||||
</span>
|
||||
{activity.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowActivity((v) => !v)}
|
||||
>
|
||||
Activity ({activity.length})
|
||||
</Button>
|
||||
)}
|
||||
{!revoked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditing((v) => !v)}
|
||||
>
|
||||
Scopes
|
||||
</Button>
|
||||
)}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>
|
||||
{revoked ? <Trash2Icon /> : "Revoke"}
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{revoked ? "Delete" : "Revoke"} token “{token.name}
|
||||
”?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{revoked
|
||||
? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label."
|
||||
: "It stops working immediately. Downloads it already requested are not affected."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={() => act(revoked ? "DELETE" : "POST")}
|
||||
>
|
||||
{revoked ? "Delete" : "Revoke"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
{editing && (
|
||||
<div className="flex flex-col gap-2 rounded-lg border p-3">
|
||||
{TOKEN_SCOPES.map((s) => (
|
||||
<label
|
||||
key={s}
|
||||
className="flex cursor-pointer items-start gap-2 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
checked={scopes.includes(s)}
|
||||
onCheckedChange={(v) =>
|
||||
setScopes((cur) =>
|
||||
v ? [...cur, s] : cur.filter((x) => x !== s),
|
||||
)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span className="flex flex-col">
|
||||
<span className="font-mono text-xs">{s}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{SCOPE_LABEL[s]}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
<Button
|
||||
size="sm"
|
||||
className="self-start"
|
||||
disabled={scopes.length === 0}
|
||||
onClick={saveScopes}
|
||||
>
|
||||
Save scopes
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{showActivity && <ActivityList items={activity} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type ActivityItem = {
|
||||
id: string;
|
||||
action: string;
|
||||
targetType: string | null;
|
||||
targetId: string | null;
|
||||
outcome: string;
|
||||
code: string | null;
|
||||
message: string | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const TARGET_HREF: Record<string, (id: string) => string> = {
|
||||
deployment: (id) => `/deployments/${id}`,
|
||||
benchmark: (id) => `/benchmarks/${id}`,
|
||||
sweep: (id) => `/benchmarks/sweeps/${id}`,
|
||||
model: (id) => `/models/${id}`,
|
||||
};
|
||||
|
||||
/** What the token did, newest first: outcome, and the reason when a guardrail refused it. */
|
||||
function ActivityList({ items }: { items: ActivityItem[] }) {
|
||||
return (
|
||||
<ul className="flex max-h-80 flex-col gap-1 overflow-y-auto rounded-lg border p-2 text-xs">
|
||||
{items.map((a) => (
|
||||
<li key={a.id} className="flex flex-wrap items-baseline gap-x-2">
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
<LocalTime value={a.createdAt} />
|
||||
</span>
|
||||
<span className="font-mono">{a.action}</span>
|
||||
<span
|
||||
className={
|
||||
a.outcome === "refused"
|
||||
? "text-destructive"
|
||||
: a.outcome === "pending_approval"
|
||||
? "text-amber-700 dark:text-amber-300"
|
||||
: "text-emerald-700 dark:text-emerald-300"
|
||||
}
|
||||
>
|
||||
{a.outcome === "refused"
|
||||
? `refused: ${a.code}`
|
||||
: a.outcome === "pending_approval"
|
||||
? "awaiting approval"
|
||||
: "ok"}
|
||||
</span>
|
||||
{a.targetType && a.targetId && TARGET_HREF[a.targetType] && (
|
||||
<Link
|
||||
href={TARGET_HREF[a.targetType](a.targetId)}
|
||||
className="underline"
|
||||
>
|
||||
{a.targetType}
|
||||
</Link>
|
||||
)}
|
||||
{a.message && (
|
||||
<span className="w-full text-muted-foreground">{a.message}</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ShieldCheckIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import type { ApprovalMode } from "@/lib/agent-guardrails";
|
||||
import { DEFAULT_ALLOWED_ARGS, parseFlagList, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
|
||||
const intText = (s: string) => s.replace(/\D/g, "");
|
||||
const decText = (s: string) => s.replace(/[^\d.,]/g, "");
|
||||
const num = (s: string) => Number(s.replace(",", "."));
|
||||
|
||||
/** Limits for deployments, benchmark runs and sweeps requested through the API. */
|
||||
export function TuningSettings({ initial, runtimes }: { initial: TuningGuardrails; runtimes: { id: string; name: string; pulled: boolean }[] }) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
|
||||
const [maxDeps, setMaxDeps] = useState(String(initial.maxAgentDeployments));
|
||||
const [runMin, setRunMin] = useState(String(initial.maxRunMinutes));
|
||||
const [sweepMin, setSweepMin] = useState(String(initial.maxSweepMinutes));
|
||||
const [variants, setVariants] = useState(String(initial.maxSweepVariants));
|
||||
const [allowed, setAllowed] = useState<string[]>(initial.allowedRuntimeIds);
|
||||
const [llamaArgs, setLlamaArgs] = useState(initial.allowedArgs["llama.cpp"].join(" "));
|
||||
const [vllmArgs, setVllmArgs] = useState(initial.allowedArgs.vllm.join(" "));
|
||||
const [portFrom, setPortFrom] = useState(initial.hostPortRange ? String(initial.hostPortRange.from) : "");
|
||||
const [portTo, setPortTo] = useState(initial.hostPortRange ? String(initial.hostPortRange.to) : "");
|
||||
const [memGiB, setMemGiB] = useState(initial.maxMemoryMb ? String(Math.round((initial.maxMemoryMb / 1024) * 10) / 10) : "");
|
||||
const [cpus, setCpus] = useState(initial.maxCpus != null ? String(initial.maxCpus) : "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
let argError: string | null = null;
|
||||
let llama: string[] = [];
|
||||
let vllm: string[] = [];
|
||||
try {
|
||||
llama = parseFlagList(llamaArgs);
|
||||
vllm = parseFlagList(vllmArgs);
|
||||
} catch (err) {
|
||||
argError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (argError) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/tuning", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
approvalMode: mode,
|
||||
maxAgentDeployments: num(maxDeps),
|
||||
maxRunMinutes: num(runMin),
|
||||
maxSweepMinutes: num(sweepMin),
|
||||
maxSweepVariants: num(variants),
|
||||
allowedRuntimeIds: allowed,
|
||||
allowedArgs: { "llama.cpp": llama, vllm },
|
||||
hostPortRange: portFrom && portTo ? { from: num(portFrom), to: num(portTo) } : null,
|
||||
maxMemoryMb: memGiB ? Math.round(num(memGiB) * 1024) : null,
|
||||
maxCpus: cpus ? num(cpus) : null,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return void toast.error(json.error?.message ?? `Could not save (${res.status})`);
|
||||
toast.success("Guardrails saved");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const field = (id: string, label: string, value: string, set: (v: string) => void, opts: { placeholder?: string; decimal?: boolean } = {}) => (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input id={id} value={value} onChange={(e) => set((opts.decimal ? decText : intText)(e.target.value))} inputMode={opts.decimal ? "decimal" : "numeric"} placeholder={opts.placeholder} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<ShieldCheckIcon className="size-4 text-muted-foreground" />
|
||||
Guardrails for API deployments and benchmarks
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
For tokens with the deployments and benchmarks scopes. Agents only change and benchmark deployments their own token created, never protected ones (the
|
||||
shield on a deployment's page), and can't start anything that would crowd a running protected deployment out of VRAM.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={save} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="t-mode">Approval</Label>
|
||||
<NativeSelect id="t-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
|
||||
<option value="approve">Ask me: starts, runs and sweeps wait for approval</option>
|
||||
<option value="auto">Automatic: they go ahead right away</option>
|
||||
</NativeSelect>
|
||||
<p className="text-xs text-muted-foreground">Creating or editing a stopped deployment, stopping and deleting their own ones never needs approval.</p>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{field("t-deps", "Agent deployments at once", maxDeps, setMaxDeps)}
|
||||
{field("t-run", "Max minutes per run", runMin, setRunMin)}
|
||||
{field("t-sweep", "Max minutes per sweep", sweepMin, setSweepMin)}
|
||||
{field("t-var", "Max variants per sweep", variants, setVariants)}
|
||||
</div>
|
||||
<p className="-mt-2 text-xs text-muted-foreground">
|
||||
One agent run or sweep at a time, and no agent deployment starts while one is measured. Raise “deployments at once” to 2 for A/B runs.
|
||||
</p>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{field("t-mem", "Memory cap per deployment (GiB)", memGiB, setMemGiB, { placeholder: "host RAM", decimal: true })}
|
||||
{field("t-cpu", "CPU cap (cores)", cpus, setCpus, { placeholder: "all cores", decimal: true })}
|
||||
{field("t-pf", "Host ports from", portFrom, setPortFrom, { placeholder: "none" })}
|
||||
{field("t-pt", "Host ports to", portTo, setPortTo, { placeholder: "none" })}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Runtimes agents may use</Label>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1.5">
|
||||
{runtimes.map((r) => (
|
||||
<label key={r.id} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox checked={allowed.includes(r.id)} onCheckedChange={(v) => setAllowed((cur) => (v ? [...cur, r.id] : cur.filter((x) => x !== r.id)))} />
|
||||
{r.name}
|
||||
{!r.pulled && <span className="text-xs text-muted-foreground">(not pulled)</span>}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">None ticked: every runtime with a pulled image.</p>
|
||||
</div>
|
||||
{(
|
||||
[
|
||||
["llama.cpp", llamaArgs, setLlamaArgs],
|
||||
["vllm", vllmArgs, setVllmArgs],
|
||||
] as const
|
||||
).map(([engine, value, set]) => (
|
||||
<div key={engine} className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`t-args-${engine}`}>Extra argument flags agents may use: {engine}</Label>
|
||||
<textarea
|
||||
id={`t-args-${engine}`}
|
||||
value={value}
|
||||
onChange={(e) => set(e.target.value)}
|
||||
rows={3}
|
||||
spellCheck={false}
|
||||
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
/>
|
||||
<button type="button" className="self-start text-xs text-muted-foreground underline" onClick={() => set(DEFAULT_ALLOWED_ARGS[engine].join(" "))}>
|
||||
Reset to the default list
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{argError ??
|
||||
"Anything else is refused with the offending argument named, and values can't be paths or URLs. Docker options (devices, volumes, privileges, network) never come from arguments: they belong to the runtime, which tokens can't change."}
|
||||
</p>
|
||||
<Button type="submit" className="self-start" disabled={busy || !!argError}>
|
||||
Save guardrails
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { ImageIcon, ImageUpIcon, Loader2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { DotPainting } from "@/components/hero/dot-painting";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { type Backdrop, BACKDROP_MAX_CELLS } from "@/lib/backdrop";
|
||||
|
||||
/**
|
||||
* Turns an image into a brightness grid like the built-in painting: at most BACKDROP_MAX_CELLS on
|
||||
* the long side, transparency on white, contrast-stretched (2nd–98th percentile) to levels 0–f.
|
||||
*/
|
||||
async function toBackdrop(file: File): Promise<Backdrop> {
|
||||
let img: ImageBitmap | HTMLCanvasElement = await createImageBitmap(file);
|
||||
const s = Math.min(1, BACKDROP_MAX_CELLS / Math.max(img.width, img.height));
|
||||
const w = Math.max(8, Math.round(img.width * s));
|
||||
const h = Math.max(8, Math.round(img.height * s));
|
||||
// Halve in steps first: one big downscale skips most pixels and looks noisy.
|
||||
while (img.width > w * 2 && img.height > h * 2) {
|
||||
const half = document.createElement("canvas");
|
||||
half.width = Math.round(img.width / 2);
|
||||
half.height = Math.round(img.height / 2);
|
||||
half.getContext("2d")!.drawImage(img, 0, 0, half.width, half.height);
|
||||
img = half;
|
||||
}
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const g = canvas.getContext("2d", { willReadFrequently: true })!;
|
||||
g.fillStyle = "#fff";
|
||||
g.fillRect(0, 0, w, h);
|
||||
g.imageSmoothingQuality = "high";
|
||||
g.drawImage(img, 0, 0, w, h);
|
||||
const px = g.getImageData(0, 0, w, h).data;
|
||||
const lum = new Float32Array(w * h);
|
||||
for (let i = 0; i < lum.length; i++) lum[i] = 0.2126 * px[i * 4] + 0.7152 * px[i * 4 + 1] + 0.0722 * px[i * 4 + 2];
|
||||
const sorted = Float32Array.from(lum).sort();
|
||||
const lo = sorted[Math.floor(sorted.length * 0.02)];
|
||||
const hi = sorted[Math.ceil(sorted.length * 0.98) - 1];
|
||||
const range = Math.max(1, hi - lo);
|
||||
let dots = "";
|
||||
for (const l of lum) dots += Math.round(Math.min(1, Math.max(0, (l - lo) / range)) * 15).toString(16);
|
||||
return { w, h, dots, focus: [0.5, 0.5] };
|
||||
}
|
||||
|
||||
/** Upload a picture for the dot painting behind the page headers, pick its focus point, or go back to the built-in one. */
|
||||
export function BackdropSettings({ initial }: { initial: Backdrop | null }) {
|
||||
const router = useRouter();
|
||||
const [saved, setSaved] = useState(initial);
|
||||
// The picture being edited: the saved one, a new upload, or null (built-in painting).
|
||||
const [draft, setDraft] = useState(initial);
|
||||
const [reading, setReading] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
|
||||
const dirty = draft?.dots !== saved?.dots || draft?.focus[0] !== saved?.focus[0] || draft?.focus[1] !== saved?.focus[1];
|
||||
|
||||
async function pick(file: File | undefined) {
|
||||
if (!file) return;
|
||||
setReading(true);
|
||||
try {
|
||||
setDraft(await toBackdrop(file));
|
||||
} catch {
|
||||
toast.error(`"${file.name}" couldn't be read as an image.`);
|
||||
} finally {
|
||||
setReading(false);
|
||||
if (input.current) input.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function save(next: Backdrop | null) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/appearance", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ backdrop: next }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
|
||||
setSaved(body.backdrop);
|
||||
setDraft(body.backdrop);
|
||||
toast.success(body.backdrop ? "Background picture saved" : "Back to The Creation of Adam");
|
||||
router.refresh(); // the headers get the picture from the layout
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Background picture</CardTitle>
|
||||
<CardDescription>
|
||||
The dot matrix behind every page header. Upload your own picture and it is drawn in dots the same way, in the theme's colors. Only the dots are
|
||||
saved, not the image, and they apply for everyone using this Kaname.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
{draft ? (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="relative w-full max-w-xl cursor-crosshair overflow-hidden rounded-lg bg-background ring-1 ring-foreground/10"
|
||||
style={{ aspectRatio: `${draft.w} / ${draft.h}` }}
|
||||
onClick={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
const f = (v: number) => Math.round(Math.min(1, Math.max(0, v)) * 1000) / 1000;
|
||||
setDraft({ ...draft, focus: [f((e.clientX - r.left) / r.width), f((e.clientY - r.top) / r.height)] });
|
||||
}}
|
||||
aria-label="Set the focus point"
|
||||
>
|
||||
<DotPainting source={draft} anchor={draft.focus} className="absolute inset-0 size-full text-foreground/75" />
|
||||
<span
|
||||
className="absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-primary/30 shadow"
|
||||
style={{ left: `${draft.focus[0] * 100}%`, top: `${draft.focus[1] * 100}%` }}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
<p className="text-xs text-muted-foreground">Click the part that should stay in view when a header crops the picture.</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-muted-foreground">
|
||||
<ImageIcon className="size-4" />
|
||||
<span>
|
||||
Showing the built-in painting, Michelangelo's <i>The Creation of Adam</i>.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input ref={input} type="file" accept="image/*" className="hidden" onChange={(e) => void pick(e.target.files?.[0])} />
|
||||
<Button variant="outline" disabled={reading || busy} onClick={() => input.current?.click()}>
|
||||
{reading ? <Loader2Icon className="animate-spin" /> : <ImageUpIcon />}
|
||||
{draft ? "Choose another picture" : "Upload a picture"}
|
||||
</Button>
|
||||
{dirty && (
|
||||
<>
|
||||
<Button disabled={busy || reading} onClick={() => void save(draft)}>
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="ghost" disabled={busy} onClick={() => setDraft(saved)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{saved && !dirty && (
|
||||
<Button variant="ghost" disabled={busy} onClick={() => void save(null)}>
|
||||
Use the built-in painting
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getBackdrop } from "@/lib/settings";
|
||||
import { BackdropSettings } from "./backdrop-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Appearance · Settings" };
|
||||
|
||||
export default async function AppearanceSettingsPage() {
|
||||
return <BackdropSettings initial={await getBackdrop()} />;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getDownloadSpeedLimit, 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";
|
||||
@@ -11,6 +12,7 @@ export default async function DownloadSettingsPage() {
|
||||
<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 id="scan" className="scroll-mt-24">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -1,267 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import type { HardwareOverrides, HostHardware } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { formatLink, onOff } from "@/lib/hardware";
|
||||
|
||||
type GpuForm = { name: string; vramMb: string; linkCurrent: string; linkMax: string; rebar: "" | "on" | "off" };
|
||||
|
||||
const toForm = (o: NonNullable<HardwareOverrides["gpus"]>[string] | undefined): GpuForm => ({
|
||||
name: o?.name ?? "",
|
||||
vramMb: o?.vramMb != null ? String(o.vramMb) : "",
|
||||
linkCurrent: o?.linkCurrent ?? "",
|
||||
linkMax: o?.linkMax ?? "",
|
||||
rebar: o?.rebar == null ? "" : o.rebar ? "on" : "off",
|
||||
});
|
||||
|
||||
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
|
||||
|
||||
/** What Kaname detected on the Docker host, with manual values for what it can't see. */
|
||||
export function HardwareSettings({
|
||||
detected,
|
||||
overrides,
|
||||
summary,
|
||||
dockerConnected,
|
||||
}: {
|
||||
detected: HostHardware | null;
|
||||
overrides: HardwareOverrides;
|
||||
summary: string[];
|
||||
dockerConnected: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [gpus, setGpus] = useState<Record<string, GpuForm>>(() => Object.fromEntries((detected?.gpus ?? []).map((g) => [g.pciAddress, toForm(overrides.gpus?.[g.pciAddress])])));
|
||||
const [p2p, setP2p] = useState(overrides.p2p ?? "");
|
||||
const [storage, setStorage] = useState(overrides.storage ?? "");
|
||||
const [hypervisor, setHypervisor] = useState(overrides.hypervisor ?? "");
|
||||
const [passthrough, setPassthrough] = useState(overrides.gpuPassthrough == null ? "" : overrides.gpuPassthrough ? "yes" : "no");
|
||||
const [gpuDriver, setGpuDriver] = useState(overrides.gpuDriver ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const setGpu = (addr: string, patch: Partial<GpuForm>) => setGpus((g) => ({ ...g, [addr]: { ...g[addr], ...patch } }));
|
||||
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const body: HardwareOverrides = {
|
||||
gpus: Object.fromEntries(
|
||||
Object.entries(gpus).map(([addr, g]) => [
|
||||
addr,
|
||||
{
|
||||
name: g.name || undefined,
|
||||
vramMb: g.vramMb ? Number(g.vramMb) : undefined,
|
||||
linkCurrent: g.linkCurrent || undefined,
|
||||
linkMax: g.linkMax || undefined,
|
||||
rebar: g.rebar ? g.rebar === "on" : undefined,
|
||||
},
|
||||
]),
|
||||
),
|
||||
p2p: (p2p || undefined) as HardwareOverrides["p2p"],
|
||||
storage: storage || undefined,
|
||||
hypervisor: hypervisor || undefined,
|
||||
gpuPassthrough: passthrough ? passthrough === "yes" : undefined,
|
||||
gpuDriver: gpuDriver || undefined,
|
||||
};
|
||||
const res = await fetch("/api/settings/hardware", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
const out = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return void toast.error(out.error?.message ?? `Could not save (${res.status})`);
|
||||
toast.success("Saved; new benchmark runs use these values");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!detected) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Hardware</CardTitle>
|
||||
<CardDescription>
|
||||
{dockerConnected ? "The worker hasn't reported its hardware yet (it checks every few minutes)." : "Hardware is detected by the worker once Docker is connected (Settings → Runtimes)."}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const v = detected.virtualization;
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>GPUs</CardTitle>
|
||||
<CardDescription>
|
||||
Recorded with every benchmark run. Detected from sysfs as the worker sees it; in a VM the PCIe link is the one the VM sees, which may not be the physical
|
||||
slot. Fill in a field to replace the detected value (empty = detected).
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{detected.gpus.length === 0 && <p className="text-sm text-muted-foreground">No NVIDIA, Intel or AMD GPU found.</p>}
|
||||
{detected.gpus.map((g) => {
|
||||
const f = gpus[g.pciAddress];
|
||||
return (
|
||||
<div key={g.pciAddress} className="flex flex-col gap-3 rounded-lg border p-3">
|
||||
<div className="text-sm">
|
||||
<span className="font-medium">{g.name ?? "Unknown GPU"}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· {g.pciAddress} · {g.driver ?? "no driver"}
|
||||
{g.driverVersion ? ` ${g.driverVersion}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Field id={`n-${g.pciAddress}`} label="Name" detected={g.name} value={f.name} onChange={(x) => setGpu(g.pciAddress, { name: x })} />
|
||||
<Field
|
||||
id={`v-${g.pciAddress}`}
|
||||
label="VRAM (MiB)"
|
||||
detected={g.vramMb != null ? String(g.vramMb) : null}
|
||||
value={f.vramMb}
|
||||
onChange={(x) => setGpu(g.pciAddress, { vramMb: x.replace(/\D/g, "") })}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`r-${g.pciAddress}`}>ReBAR</Label>
|
||||
<NativeSelect id={`r-${g.pciAddress}`} value={f.rebar} onChange={(e) => setGpu(g.pciAddress, { rebar: e.target.value as GpuForm["rebar"] })}>
|
||||
<option value="">Detected: {onOff(g.rebar)}</option>
|
||||
<option value="on">on</option>
|
||||
<option value="off">off</option>
|
||||
</NativeSelect>
|
||||
<p className="text-xs text-muted-foreground">Largest BAR {g.barMb != null ? formatBytes(g.barMb * 2 ** 20) : "unknown"}</p>
|
||||
</div>
|
||||
<Field
|
||||
id={`lc-${g.pciAddress}`}
|
||||
label="PCIe link (current)"
|
||||
detected={formatLink(g.linkCurrent)}
|
||||
value={f.linkCurrent}
|
||||
placeholderHint="e.g. Gen4 x8"
|
||||
onChange={(x) => setGpu(g.pciAddress, { linkCurrent: x })}
|
||||
/>
|
||||
<Field
|
||||
id={`lm-${g.pciAddress}`}
|
||||
label="PCIe link (maximum)"
|
||||
detected={formatLink(g.linkMax)}
|
||||
value={f.linkMax}
|
||||
placeholderHint="e.g. Gen5 x16"
|
||||
onChange={(x) => setGpu(g.pciAddress, { linkMax: x })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{detected.gpus.length > 1 && (
|
||||
<div className="flex max-w-xs flex-col gap-1.5">
|
||||
<Label htmlFor="hw-p2p">Peer-to-peer between GPUs</Label>
|
||||
<NativeSelect id="hw-p2p" value={p2p} onChange={(e) => setP2p(e.target.value as typeof p2p)}>
|
||||
<option value="">Detected: {detected.p2p ?? "unknown"}</option>
|
||||
<option value="on">on</option>
|
||||
<option value="partial">partial</option>
|
||||
<option value="off">off</option>
|
||||
</NativeSelect>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>System</CardTitle>
|
||||
<CardDescription>Part of the system summary recorded with each run, passed to BetterBench and shown in the launch80 preview.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
id="hw-storage"
|
||||
label="Models disk"
|
||||
detected={detected.storage ? [detected.storage.model, detected.storage.kind && STORAGE_KIND[detected.storage.kind]].filter(Boolean).join(", ") : null}
|
||||
value={storage}
|
||||
onChange={setStorage}
|
||||
/>
|
||||
<Field
|
||||
id="hw-virt"
|
||||
label="Virtualization"
|
||||
detected={v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}` : "bare metal"}
|
||||
value={hypervisor}
|
||||
placeholderHint="e.g. Proxmox VE 9 (KVM)"
|
||||
onChange={setHypervisor}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="hw-pt">GPU passthrough</Label>
|
||||
<NativeSelect id="hw-pt" value={passthrough} onChange={(e) => setPassthrough(e.target.value)}>
|
||||
<option value="">Detected: {v.vm ? (detected.gpus.length ? "yes" : "no") : v.vm === false ? "no (bare metal)" : "unknown"}</option>
|
||||
<option value="yes">yes</option>
|
||||
<option value="no">no</option>
|
||||
</NativeSelect>
|
||||
</div>
|
||||
<Field
|
||||
id="hw-driver"
|
||||
label="GPU driver"
|
||||
detected={[...new Set(detected.gpus.map((g) => [g.driver, g.driverVersion].filter(Boolean).join(" ")))].join(", ") || null}
|
||||
value={gpuDriver}
|
||||
placeholderHint="e.g. xe, compute runtime 25.35"
|
||||
onChange={setGpuDriver}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" disabled={busy}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>System summary</CardTitle>
|
||||
<CardDescription>
|
||||
Exactly what runs record and publish (after saving). Never the hostname, IP addresses, users or paths. Checked <LocalTime value={detected.checkedAt} />.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="flex flex-col gap-1 text-sm">
|
||||
{summary.map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({
|
||||
id,
|
||||
label,
|
||||
detected,
|
||||
value,
|
||||
onChange,
|
||||
placeholderHint,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
detected: string | null;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholderHint?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input id={id} value={value} onChange={(e) => onChange(e.target.value)} placeholder={detected ?? placeholderHint ?? "unknown"} maxLength={120} />
|
||||
<p className="text-xs text-muted-foreground">Detected: {detected ?? "unknown"}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { kanameVersion } from "@/lib/benchmark-snapshot";
|
||||
import { applyOverrides, systemSummary, systemSummaryLines } from "@/lib/hardware";
|
||||
import { getDockerInfo } from "@/lib/runtimes";
|
||||
import { getHardwareOverrides } from "@/lib/settings";
|
||||
import { HardwareSettings } from "./hardware-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Hardware · Settings" };
|
||||
|
||||
export default async function HardwareSettingsPage() {
|
||||
const [docker, overrides] = await Promise.all([getDockerInfo(), getHardwareOverrides()]);
|
||||
const hardware = docker?.hardware ?? null;
|
||||
const effective = applyOverrides(hardware, overrides);
|
||||
return (
|
||||
<HardwareSettings
|
||||
detected={hardware}
|
||||
overrides={overrides}
|
||||
summary={systemSummaryLines(systemSummary(effective, docker?.os ?? null, kanameVersion()))}
|
||||
dockerConnected={!!docker?.connected}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,25 @@
|
||||
import { BotIcon, BoxesIcon, CpuIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { DownloadIcon, PaletteIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { SettingsNav } from "./settings-nav";
|
||||
|
||||
const SECTIONS = [
|
||||
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
|
||||
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
|
||||
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
|
||||
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
|
||||
{ href: "/settings/hardware", label: "Hardware", icon: <CpuIcon className="size-4" /> },
|
||||
{ href: "/settings/api-keys", label: "Runtime API keys", icon: <KeyRoundIcon className="size-4" /> },
|
||||
{ href: "/settings/api-tokens", label: "API tokens", icon: <BotIcon className="size-4" /> },
|
||||
{ href: "/settings/appearance", label: "Appearance", icon: <PaletteIcon className="size-4" /> },
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">Settings</h1>
|
||||
<PageHero
|
||||
title="Settings"
|
||||
description="File labels, tags, how Kaname downloads and scans models, and the background picture."
|
||||
painting={{ view: 0.4, focus: [0.5, 0.43], anchor: [0.7, 0.4] }}
|
||||
>
|
||||
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
|
||||
<SettingsNav sections={SECTIONS} />
|
||||
<div className="min-w-0">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
import { RuntimesView } from "./runtimes-view";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Runtimes · Settings" };
|
||||
|
||||
export default async function RuntimesPage() {
|
||||
const [runtimes, docker, worker] = await Promise.all([listRuntimes(), getDockerInfo(), getWorkerStatus()]);
|
||||
return <RuntimesView runtimes={runtimes} docker={docker} workerOnline={worker.online} />;
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ArgsEditor } from "@/components/args-editor";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
|
||||
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
|
||||
import { ACCELERATOR_DEVICES, ACCELERATOR_LABEL, formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
|
||||
{ id: "llama.cpp", label: "llama.cpp-compatible", hint: "llama-server command line, GGUF models" },
|
||||
{ id: "vllm", label: "vLLM-compatible", hint: "vllm serve command line, safetensors models" },
|
||||
];
|
||||
|
||||
const textareaClass =
|
||||
"min-h-20 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
|
||||
|
||||
/** Create/edit a runtime. Validates locally with the same rules as the server. */
|
||||
export function RuntimeForm({
|
||||
initial,
|
||||
submitLabel,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: {
|
||||
initial: RuntimeInput;
|
||||
submitLabel: string;
|
||||
onSubmit: (value: RuntimeInput) => Promise<boolean>;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [name, setName] = useState(initial.name);
|
||||
const [engine, setEngine] = useState<RuntimeEngine>(initial.engine);
|
||||
const [accelerator, setAccelerator] = useState<RuntimeAccelerator>(initial.accelerator ?? "cpu");
|
||||
const [image, setImage] = useState(initial.image);
|
||||
const [description, setDescription] = useState(initial.description ?? "");
|
||||
const [engineName, setEngineName] = useState(initial.engineName ?? "");
|
||||
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
|
||||
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
|
||||
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
|
||||
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
|
||||
const [numa, setNuma] = useState(!!initial.numaTuning);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
let value: RuntimeInput;
|
||||
try {
|
||||
value = validateRuntime({
|
||||
name,
|
||||
engine,
|
||||
accelerator,
|
||||
image,
|
||||
description,
|
||||
engineName,
|
||||
env: parseEnvLines(envText),
|
||||
extraArgs: rowsToArgs(argRows),
|
||||
devices: devicesText.split(/[,\s]+/),
|
||||
shmSizeMb: shm.trim() ? Number(shm) : null,
|
||||
numaTuning: numa,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof RuntimeValidationError ? err.message : String(err));
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSubmit(value);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="flex flex-col gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-name">Name</Label>
|
||||
<Input id="rt-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="vLLM XPU (Arc patches)" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-image">Image</Label>
|
||||
<Input
|
||||
id="rt-image"
|
||||
value={image}
|
||||
onChange={(e) => setImage(e.target.value)}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
placeholder="registry.example.com/org/image:tag"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Engine type</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{ENGINES.map((e) => (
|
||||
<button
|
||||
key={e.id}
|
||||
type="button"
|
||||
onClick={() => setEngine(e.id)}
|
||||
className={cn(
|
||||
"flex flex-col items-start rounded-lg border px-3 py-2 text-left text-sm transition-colors",
|
||||
engine === e.id ? "border-primary bg-primary/5" : "hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<span className="font-medium">{e.label}</span>
|
||||
<span className="text-xs text-muted-foreground">{e.hint}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Decides how Kaname builds the command line. Forks with the same CLI (e.g. patched vLLM builds) use the same type.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-acc">Runs on</Label>
|
||||
<NativeSelect
|
||||
id="rt-acc"
|
||||
value={accelerator}
|
||||
onChange={(e) => {
|
||||
const next = e.target.value as RuntimeAccelerator;
|
||||
setAccelerator(next);
|
||||
// Suggest the device nodes the accelerator needs.
|
||||
if (!devicesText.trim()) setDevicesText(ACCELERATOR_DEVICES[next].join(", "));
|
||||
}}
|
||||
>
|
||||
{RUNTIME_ACCELERATORS.map((a) => (
|
||||
<option key={a} value={a}>
|
||||
{ACCELERATOR_LABEL[a]}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{accelerator === "nvidia"
|
||||
? "GPUs are requested from Docker (NVIDIA Container Toolkit on the host); each deployment picks which ones."
|
||||
: accelerator === "dri"
|
||||
? "Intel and AMD GPUs are passed in as /dev/dri (Vulkan, Intel SYCL, vLLM XPU). The image must be built for it."
|
||||
: accelerator === "rocm"
|
||||
? "AMD GPUs with ROCm: /dev/kfd and /dev/dri are passed in."
|
||||
: "CPU and RAM only."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-desc">Description</Label>
|
||||
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-engine-name">Engine name</Label>
|
||||
<Input id="rt-engine-name" value={engineName} onChange={(e) => setEngineName(e.target.value)} maxLength={60} placeholder={engine} spellCheck={false} />
|
||||
<p className="text-xs text-muted-foreground">For forks: recorded with every benchmark next to the version the server reports, e.g. vllm-radiance.</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-env">Environment</Label>
|
||||
<textarea
|
||||
id="rt-env"
|
||||
value={envText}
|
||||
onChange={(e) => setEnvText(e.target.value)}
|
||||
spellCheck={false}
|
||||
className={textareaClass}
|
||||
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Extra arguments</Label>
|
||||
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--dtype", value: "bfloat16" } : { flag: "--temp", value: "0.7" }} />
|
||||
<p className="text-xs text-muted-foreground">Added to every deployment's command; a deployment can override them.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-shm">Shared memory (MiB)</Label>
|
||||
<Input id="rt-shm" value={shm} onChange={(e) => setShm(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric" placeholder="Docker default (64)" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-devices">Devices</Label>
|
||||
<Input
|
||||
id="rt-devices"
|
||||
value={devicesText}
|
||||
onChange={(e) => setDevicesText(e.target.value)}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
placeholder="/dev/dri, /dev/kfd"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg bg-muted/50 px-3 py-2.5 text-sm">
|
||||
<Checkbox checked={numa} onCheckedChange={(v) => setNuma(v === true)} className="mt-0.5" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span>NUMA tuning</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Adds <code>CAP_SYS_NICE</code> and <code>seccomp=unconfined</code>, as vLLM recommends for its CPU build. This relaxes
|
||||
the container's isolation; leave it off unless you need the extra speed.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{error && <p className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</p>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{saving ? "Saving…" : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronDownIcon, CopyIcon, DownloadCloudIcon, PencilIcon, PlusIcon, ServerIcon, Trash2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
|
||||
import { formatBytes, percent } from "@/lib/format";
|
||||
import { ACCELERATOR_LABEL, RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { RuntimeForm } from "./runtime-form";
|
||||
|
||||
type Runtime = typeof runtimes.$inferSelect;
|
||||
|
||||
const FEATURE_LABEL: Record<string, string> = {
|
||||
avx2: "AVX2",
|
||||
avx512f: "AVX-512",
|
||||
avx512_bf16: "AVX-512 BF16",
|
||||
avx512_vnni: "AVX-512 VNNI",
|
||||
avx512bw: "AVX-512 BW",
|
||||
amx_bf16: "AMX BF16",
|
||||
amx_int8: "AMX INT8",
|
||||
f16c: "F16C",
|
||||
fma: "FMA",
|
||||
};
|
||||
|
||||
async function send(url: string, method: string, body?: unknown): Promise<boolean> {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: body ? { "Content-Type": "application/json" } : undefined,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (res.ok) return true;
|
||||
const json = await res.json().catch(() => ({}));
|
||||
toast.error(json.error?.message ?? `Request failed (${res.status})`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const toInput = (r: Runtime): RuntimeInput => ({
|
||||
name: r.name,
|
||||
engine: r.engine,
|
||||
accelerator: r.accelerator,
|
||||
image: r.image,
|
||||
description: r.description,
|
||||
engineName: r.engineName,
|
||||
env: r.env,
|
||||
extraArgs: r.extraArgs,
|
||||
devices: r.devices,
|
||||
shmSizeMb: r.shmSizeMb,
|
||||
numaTuning: r.numaTuning,
|
||||
});
|
||||
|
||||
export function RuntimesView({ runtimes, docker, workerOnline }: { runtimes: Runtime[]; docker: DockerHostInfo | null; workerOnline: boolean }) {
|
||||
const router = useRouter();
|
||||
const [creating, setCreating] = useState<(RuntimeInput & { preset?: string }) | null>(null);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const anyPulling = runtimes.some((r) => r.imageState === "pulling" || (r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt)));
|
||||
|
||||
// While a pull runs, refresh the server data every 2 s for its progress.
|
||||
useEffect(() => {
|
||||
if (!anyPulling) return;
|
||||
const t = setInterval(() => router.refresh(), 2_000);
|
||||
return () => clearInterval(t);
|
||||
}, [anyPulling, router]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<HostCard docker={docker} workerOnline={workerOnline} />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Runtimes</CardTitle>
|
||||
<CardDescription>
|
||||
Container images that serve models: official llama.cpp and vLLM builds, or your own forks from any registry. Kaname
|
||||
only starts images registered here, with the models mounted read-only.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button size="sm" />}>
|
||||
<PlusIcon />
|
||||
Add runtime
|
||||
<ChevronDownIcon className="opacity-70" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-72">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel>From a preset</DropdownMenuLabel>
|
||||
{RUNTIME_PRESETS.map((p) => (
|
||||
<DropdownMenuItem key={p.id} onClick={() => setCreating({ ...p, name: p.name, preset: p.id })} className="flex-col items-start gap-0">
|
||||
<span>{p.name}</span>
|
||||
<span className="text-xs text-muted-foreground">{p.summary}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setCreating({ name: "", engine: "vllm", image: "" })}>Custom image (fork)…</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
{creating && (
|
||||
<div className="rounded-lg p-4 ring-1 ring-primary/40">
|
||||
<RuntimeForm
|
||||
initial={creating}
|
||||
submitLabel="Add runtime"
|
||||
onCancel={() => setCreating(null)}
|
||||
onSubmit={async (value) => {
|
||||
const ok = await send("/api/runtimes", "POST", { ...value, preset: creating.preset });
|
||||
if (ok) {
|
||||
toast.success(`Runtime "${value.name}" added`);
|
||||
setCreating(null);
|
||||
router.refresh();
|
||||
}
|
||||
return ok;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{runtimes.length === 0 && !creating && <p className="text-sm text-muted-foreground">No runtimes yet. Add one from a preset.</p>}
|
||||
{runtimes.map((r) =>
|
||||
editing === r.id ? (
|
||||
<div key={r.id} className="rounded-lg p-4 ring-1 ring-primary/40">
|
||||
<RuntimeForm
|
||||
initial={toInput(r)}
|
||||
submitLabel="Save"
|
||||
onCancel={() => setEditing(null)}
|
||||
onSubmit={async (value) => {
|
||||
const ok = await send(`/api/runtimes/${r.id}`, "PUT", value);
|
||||
if (ok) {
|
||||
setEditing(null);
|
||||
router.refresh();
|
||||
}
|
||||
return ok;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<RuntimeRow
|
||||
key={r.id}
|
||||
runtime={r}
|
||||
dockerReady={!!docker?.connected}
|
||||
onEdit={() => setEditing(r.id)}
|
||||
onDuplicate={() => setCreating({ ...toInput(r), name: `${r.name} (copy)` })}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; workerOnline: boolean }) {
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ServerIcon className="size-4 text-muted-foreground" />
|
||||
Docker host
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{!workerOnline
|
||||
? "The worker is offline; these facts may be outdated."
|
||||
: !docker
|
||||
? "Not connected. Runtimes need the worker to reach Docker through the socket proxy (DOCKER_HOST)."
|
||||
: docker.connected
|
||||
? `Docker ${docker.serverVersion} on ${docker.os} (${docker.architecture})`
|
||||
: `Can't reach Docker: ${docker.error}`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
{docker && (
|
||||
<CardContent>
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1.5 text-sm">
|
||||
<dt className="text-muted-foreground">CPU</dt>
|
||||
<dd>
|
||||
{docker.cpuModel ?? "unknown"}
|
||||
{docker.cpus != null && <span className="text-muted-foreground"> · {docker.cpus} threads</span>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Features</dt>
|
||||
<dd className="flex flex-wrap gap-1">
|
||||
{docker.cpuFeatures.length === 0 ? (
|
||||
<span className="text-muted-foreground">unknown</span>
|
||||
) : (
|
||||
docker.cpuFeatures.map((f) => (
|
||||
<span
|
||||
key={f}
|
||||
className={cn(
|
||||
"rounded border px-1.5 text-xs",
|
||||
f.startsWith("avx512") || f.startsWith("amx") ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{FEATURE_LABEL[f] ?? f}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Memory</dt>
|
||||
<dd>{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}</dd>
|
||||
<dt className="text-muted-foreground">GPUs</dt>
|
||||
<dd className="flex flex-col gap-0.5">
|
||||
{docker.gpus && docker.gpus.length > 0 ? (
|
||||
docker.gpus.map((g) => (
|
||||
<span key={g.uuid}>
|
||||
{g.index}: {g.name} <span className="text-muted-foreground">· {formatBytes(g.memoryMb * 2 ** 20)} · driver {g.driver}</span>
|
||||
</span>
|
||||
))
|
||||
) : docker.nvidia ? (
|
||||
<span className={cn(docker.gpuError && "text-amber-700 dark:text-amber-300")}>
|
||||
{docker.gpuError ? `NVIDIA runtime found, but listing GPUs failed: ${docker.gpuError}` : "NVIDIA runtime found, no GPUs listed."}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
No NVIDIA GPUs (no NVIDIA runtime in Docker). Intel/AMD GPUs aren't listed; pass /dev/dri to a runtime to use them.
|
||||
</span>
|
||||
)}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Network</dt>
|
||||
<dd className={cn("font-mono text-xs", !docker.network && "text-amber-700 dark:text-amber-300")}>
|
||||
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Models</dt>
|
||||
<dd className={cn("font-mono text-xs break-all", !docker.modelsSource && "text-amber-700 dark:text-amber-300")}>
|
||||
{docker.modelsSource ? `${docker.modelsSource.source} (${docker.modelsSource.type}, mounted read-only)` : "not detected (set KANAME_MODELS_SOURCE)"}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Checked</dt>
|
||||
<dd>
|
||||
<LocalTime value={docker.checkedAt} />
|
||||
</dd>
|
||||
</dl>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageState({ r }: { r: Runtime }) {
|
||||
const requested = !!r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt);
|
||||
if (r.imageState === "pulling" || requested) {
|
||||
const p = r.pullProgress;
|
||||
return (
|
||||
<div className="flex min-w-48 flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{p ? `${p.status} · ${formatBytes(p.doneBytes)}${p.totalBytes ? ` / ${formatBytes(p.totalBytes)}` : ""}` : "Pull queued…"}
|
||||
</span>
|
||||
<Progress value={p && p.totalBytes ? percent(p.doneBytes, p.totalBytes) : 0} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (r.imageState === "present") {
|
||||
return (
|
||||
<span className="text-xs text-emerald-700 dark:text-emerald-400">
|
||||
Pulled · {r.imageSize != null ? formatBytes(r.imageSize) : "?"}
|
||||
{r.imageCreated && (
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· built <LocalTime value={r.imageCreated} />
|
||||
</span>
|
||||
)}
|
||||
{r.imageDigest && (
|
||||
<span className="font-mono text-muted-foreground" title={r.imageDigest}>
|
||||
{" "}
|
||||
· {r.imageDigest.slice(0, 19)}…
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (r.imageState === "failed") return <span className="text-xs break-all text-destructive">Pull failed: {r.pullError}</span>;
|
||||
if (r.imageState === "missing") return <span className="text-xs text-muted-foreground">Not pulled yet</span>;
|
||||
return <span className="text-xs text-muted-foreground">Not checked yet</span>;
|
||||
}
|
||||
|
||||
function RuntimeRow({
|
||||
runtime: r,
|
||||
dockerReady,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
}: {
|
||||
runtime: Runtime;
|
||||
dockerReady: boolean;
|
||||
onEdit: () => void;
|
||||
onDuplicate: () => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const pulling = r.imageState === "pulling";
|
||||
const envCount = Object.keys(r.env).length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-lg px-4 py-3 ring-1 ring-foreground/10">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{r.name}</span>
|
||||
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">{r.engine === "vllm" ? "vLLM" : "llama.cpp"}</span>
|
||||
{r.accelerator !== "cpu" && (
|
||||
<span className="rounded-md border border-emerald-500/30 px-1.5 text-xs text-emerald-700 dark:text-emerald-300">{ACCELERATOR_LABEL[r.accelerator]}</span>
|
||||
)}
|
||||
{r.numaTuning && <span className="rounded-md border border-amber-500/30 px-1.5 text-xs text-amber-700 dark:text-amber-300">NUMA tuning</span>}
|
||||
</div>
|
||||
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
|
||||
{r.description && <p className="text-xs text-muted-foreground">{r.description}</p>}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant={r.imageState === "present" ? "ghost" : "outline"}
|
||||
disabled={!dockerReady || pulling}
|
||||
title={!dockerReady ? "Docker isn't connected" : r.imageState === "present" ? "Pull again to update the tag" : undefined}
|
||||
onClick={async () => {
|
||||
if (await send(`/api/runtimes/${r.id}/pull`, "POST")) router.refresh();
|
||||
}}
|
||||
>
|
||||
<DownloadCloudIcon />
|
||||
{r.imageState === "present" ? "Update" : "Pull"}
|
||||
</Button>
|
||||
<Button size="icon-sm" variant="ghost" onClick={onEdit} aria-label={`Edit ${r.name}`}>
|
||||
<PencilIcon />
|
||||
</Button>
|
||||
<Button size="icon-sm" variant="ghost" onClick={onDuplicate} aria-label={`Duplicate ${r.name}`}>
|
||||
<CopyIcon />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button size="icon-sm" variant="ghost" aria-label={`Delete ${r.name}`} />}>
|
||||
<Trash2Icon />
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete runtime “{r.name}”?</AlertDialogTitle>
|
||||
<AlertDialogDescription>The pulled image stays in Docker; remove it there if you need the space.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1 text-xs text-muted-foreground">
|
||||
<ImageState r={r} />
|
||||
<span>
|
||||
{envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
|
||||
{r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
|
||||
{r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
|
||||
{r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { cn } from "@/lib/utils";
|
||||
export function SettingsNav({ sections }: { sections: { href: string; label: string; icon: React.ReactNode }[] }) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<nav className="flex gap-1 rounded-xl bg-card p-2 ring-1 ring-foreground/10 md:flex-col">
|
||||
<nav className="flex gap-1 rounded-xl bg-card/55 p-2 ring-1 ring-foreground/10 backdrop-blur-md md:flex-col">
|
||||
{sections.map((s) => (
|
||||
<Link
|
||||
key={s.href}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** The key's value ("show key" in Settings). */
|
||||
export const GET = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
|
||||
/** Remove a key; running deployments keep accepting it until they restart. */
|
||||
export const DELETE = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await deleteApiKey(id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Keys without their values (only the last characters). */
|
||||
export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
|
||||
|
||||
/** Add a key (generated when `key` is missing); the response carries the full key once. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { deleteToken, revokeToken, TokenError, updateTokenScopes } from "@/lib/api-tokens";
|
||||
|
||||
/** Revoke a token: it stops working immediately. */
|
||||
export const POST = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
|
||||
try {
|
||||
await revokeToken((await params).id);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
/** Change an active token's scopes. */
|
||||
export const PATCH = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (req, { params }) => {
|
||||
try {
|
||||
const { scopes } = z.object({ scopes: z.array(z.string()).max(20) }).parse(await req.json());
|
||||
await updateTokenScopes((await params).id, scopes);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
|
||||
if (err instanceof z.ZodError) return apiError(400, "invalid_request", "scopes must be a list of scope names.");
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
/** Delete a revoked token (frees its name). */
|
||||
export const DELETE = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
|
||||
try {
|
||||
await deleteToken((await params).id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { createToken, listTokens, TokenError } from "@/lib/api-tokens";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** API tokens for machine clients (Settings → API tokens). Never includes the tokens themselves. */
|
||||
export const GET = withAuth(async () => NextResponse.json(await listTokens()));
|
||||
|
||||
const Body = z.object({ name: z.string().max(40), scopes: z.array(z.string()).min(1).max(10) });
|
||||
|
||||
/** Create a token. The response is the only time the token is shown. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json(await createToken(body.name, body.scopes), { status: 201, headers: { "Cache-Control": "no-store" } });
|
||||
} catch (err) {
|
||||
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user