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
|
||||
+154
@@ -4,6 +4,160 @@ 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.22.0] - 2026-11-11
|
||||
|
||||
The API for AI agents is back, for models: a token-authenticated `/api/v1` lets an agent look up
|
||||
models, download, verify, repair and tag them, within guardrails you set and, by default, only
|
||||
after you approve each download or repair.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. If Kaname is behind a forward-auth proxy, let `/api/v1/`
|
||||
through without forward auth (example in [docs/api.md](docs/api.md)). The new tables and columns are
|
||||
added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), last
|
||||
used, change scopes, revoke, delete. Scopes: `models:read`, `downloads:create`, `models:verify`,
|
||||
`tags:write`. Sent as `Authorization: Bearer kn_…`; only `/api/v1` accepts them, and it accepts
|
||||
nothing else (the rest of Kaname stays OIDC-only). No token can delete models or files, update a
|
||||
model, change settings or manage tokens.
|
||||
- **`/api/v1`** ([docs/api.md](docs/api.md)), compact JSON with error messages that say what to do:
|
||||
- `GET /api/v1/hub/lookup`, `GET /api/v1/models` (the library's search and filters, including
|
||||
"requested by"), `GET /api/v1/models/{id}`, `GET /api/v1/tags`, `GET /api/v1/disk`.
|
||||
- `POST /api/v1/downloads`: repo + pinned commit + a quant (with the recommended companion files,
|
||||
as in Add model) or include globs, optional tags. Repeating a request returns the existing job.
|
||||
- `POST /api/v1/models/{id}/repair`: downloads only the missing or broken files.
|
||||
- `POST /api/v1/models/{id}/verify` (`{"deep": true}` hashes): never needs approval; the finished
|
||||
job lists what's broken.
|
||||
- `POST /api/v1/models/{id}/tags`, `DELETE /api/v1/models/{id}/tags/{name}`.
|
||||
- `GET /api/v1/jobs/{id}?wait=900` holds the request until the job is done instead of polling;
|
||||
`POST /api/v1/jobs/{id}/cancel` cancels or withdraws a job the token requested.
|
||||
- **Guardrails for API downloads and repairs**: approval (default: ask me), max size per request
|
||||
(60 GB), free space to keep, counting what open downloads still need (100 GB), agent jobs at once
|
||||
(2), an optional author allowlist (new downloads only).
|
||||
- **Approval**: an Approve / Reject bar on the model and job pages, "awaiting approval" in the
|
||||
library. Rejecting removes a model the request added, or restores the previous file selection.
|
||||
- **Requested by <token>** on models and jobs, with a "Requested by" filter in the library, and an
|
||||
**activity log** per token that lists every request, including refusals with their error code.
|
||||
- **Agent skill** ([docs/agent/SKILL.md](docs/agent/SKILL.md)) and the `kaname` curl helper
|
||||
([docs/agent/kaname](docs/agent/kaname)): how to check the library, look up, request, follow,
|
||||
verify, repair and tag, and to wait for approval instead of retrying.
|
||||
|
||||
## [0.21.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Reload a local model** (Files tab → **Reload**): reads the folder again, so files you added,
|
||||
changed or removed and README.md edits show up right away. Every scan of the models folder (on its
|
||||
schedule, or Rescan) now also brings local models' file lists up to date, not only their README.
|
||||
|
||||
## [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
|
||||
|
||||
+42
-28
@@ -9,46 +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
|
||||
|
||||
# --- 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} /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 /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 /downloads/l80/arm64.tar.gz
|
||||
RUN mkdir -p /opt/l80 \
|
||||
&& 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
|
||||
# BetterBench (Apache-2.0), the benchmark run against endpoints. Not on PyPI: the release
|
||||
# archive is pinned by checksum; flags used by src/worker/betterbench.ts are verified per version.
|
||||
ARG BETTERBENCH_VERSION=0.6.1
|
||||
ADD --checksum=sha256:f0a9d7fcc411c809ff87a0a22e2d76f6662b426431d2ae9fa273bc2644464db7 \
|
||||
https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /tmp/betterbench.tar.gz
|
||||
# L80 CLI (launch80.com): publishes a BetterBench run as a shareable page. Release archives pinned
|
||||
# by checksum (from the release's checksums.txt); the per-architecture one is installed.
|
||||
ARG L80_VERSION=0.4.0
|
||||
ARG TARGETARCH
|
||||
ADD --checksum=sha256:cde6b67dfb67b0ffddd56dfd384b8b24610573199287c59597359145310d9d23 \
|
||||
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /tmp/l80/amd64.tar.gz
|
||||
ADD --checksum=sha256:bbd7c6cf35bcba2bf9a651f348581b691b36d5f7cdca9c8a11e8a1ac2fc3f5bc \
|
||||
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /tmp/l80/arm64.tar.gz
|
||||
RUN mkdir -p /opt/l80 \
|
||||
&& tar -xzf "/tmp/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
|
||||
&& chmod 0755 /opt/l80/L80 \
|
||||
&& rm -rf /tmp/l80
|
||||
RUN python -m venv /opt/hf \
|
||||
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 /sandbox \
|
||||
&& chown app:app /data /models /sandbox
|
||||
&& chown app:app /data /models \
|
||||
&& chmod 0777 /sandbox
|
||||
|
||||
ARG APP_VERSION=dev
|
||||
ENV PATH=/opt/hf/bin:$PATH \
|
||||
@@ -64,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,5 +1,5 @@
|
||||
<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 local LLMs from Hugging Face
|
||||
@@ -17,12 +17,16 @@ their speed and answer quality with [BetterBench](https://github.com/GGZ14/Bette
|
||||
- **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.
|
||||
- **Let AI agents fetch models:** a token-authenticated API (`/api/v1`) to look up, download,
|
||||
verify, repair and tag models, within guardrails you set and, by default, only after you approve
|
||||
each download. A ready-made [agent skill](docs/agent/SKILL.md) explains it to the agent.
|
||||
- **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**
|
||||
|
||||
@@ -33,31 +37,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).
|
||||
@@ -73,6 +107,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.
|
||||
@@ -81,18 +117,31 @@ 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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **Agents and scripts:** create a token under Settings → API tokens (pick its scopes), set the
|
||||
guardrails (approval, max size per request, free space to keep, jobs at once, allowed authors),
|
||||
and hand the agent [docs/agent/SKILL.md](docs/agent/SKILL.md) with `KANAME_URL` and
|
||||
`KANAME_TOKEN`. Its requests show up as **requested by <token>** with an Approve / Reject bar;
|
||||
every request and refusal is in the token's activity log. Reference: [docs/api.md](docs/api.md).
|
||||
Behind forward auth, let `/api/v1/` through (Kaname checks the token itself; example in the doc).
|
||||
- **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
|
||||
@@ -103,13 +152,15 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
|
||||
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; runs benchmarks against endpoints (BetterBench, the quality
|
||||
eval). Only one worker runs at a time.
|
||||
- **sandbox:** runs the quality eval's coding answers (Python written by the model under test) with
|
||||
no network, a read-only filesystem, no capabilities and small limits. It shares only an exchange
|
||||
folder with the worker. Optional: without it the eval skips the coding section.
|
||||
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):
|
||||
|
||||
|
||||
+4
-2
@@ -29,11 +29,13 @@ services:
|
||||
volumes: [data:/data]
|
||||
|
||||
# Runs the quality eval's coding answers (Python written by the model under test) with no
|
||||
# network, a read-only root, no capabilities and small limits. It shares only the exchange folder
|
||||
# with the worker. Optional: without it the quality eval skips the coding section.
|
||||
# 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"]
|
||||
|
||||
+22
-18
@@ -1,35 +1,40 @@
|
||||
# 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
|
||||
|
||||
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:
|
||||
<<: *kaname
|
||||
env_file: .env
|
||||
ports: ["${WEB_PORT:-3000}:3000"]
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data # SQLite database and results, shared with the worker (local disk, not NFS)
|
||||
|
||||
worker:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
<<: *kaname
|
||||
command: worker
|
||||
env_file: .env
|
||||
environment:
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
|
||||
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
|
||||
- sandbox:/sandbox # exchange folder with the code sandbox
|
||||
restart: unless-stopped
|
||||
|
||||
web:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
env_file: .env
|
||||
ports: ["${WEB_PORT:-3000}:3000"]
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data
|
||||
restart: unless-stopped
|
||||
- ${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) with no
|
||||
# network, a read-only root, no capabilities and small limits. It shares only the exchange folder
|
||||
# with the worker. Optional: without it the quality eval skips the coding section.
|
||||
# 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:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
<<: *kaname
|
||||
command: sandbox
|
||||
user: "65534:65534"
|
||||
depends_on: [worker]
|
||||
network_mode: none
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=64m,mode=1777"]
|
||||
@@ -39,7 +44,6 @@ services:
|
||||
pids_limit: 64
|
||||
cpus: 1
|
||||
volumes: [sandbox:/sandbox]
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
sandbox:
|
||||
+40
-3
@@ -1,12 +1,38 @@
|
||||
#!/bin/sh
|
||||
# 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,16 +42,27 @@ 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
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
---
|
||||
name: kaname-models
|
||||
description: Find, download, verify, repair and tag local LLMs (Hugging Face models, GGUF quants) on the user's Kaname server. Use when the user asks to get, download, add, check, fix or tag a model, asks which models are available locally, or how much disk space is left for models.
|
||||
required_environment_variables:
|
||||
- name: KANAME_URL
|
||||
prompt: Kaname base URL, e.g. https://models.example.com (no trailing slash)
|
||||
- name: KANAME_TOKEN
|
||||
prompt: Kaname API token (kn_…), from Settings → API tokens
|
||||
---
|
||||
|
||||
# Kaname: the user's local model library
|
||||
|
||||
Kaname downloads models from Hugging Face onto the user's server, pinned to an exact commit. With
|
||||
this skill you can:
|
||||
|
||||
- see what is already downloaded, and how much disk space is left
|
||||
- look up a Hugging Face repo (its commit, quants and sizes)
|
||||
- request a download, and follow it until it's done
|
||||
- verify a model's files, and repair the ones that are missing or broken
|
||||
- add and remove tags on models
|
||||
- cancel jobs that **you** requested
|
||||
|
||||
You **cannot** delete models or files, update a model to a newer commit, change settings, or touch
|
||||
jobs someone else started. When the user needs one of those, tell them to do it in Kaname's web UI.
|
||||
|
||||
## Setup
|
||||
|
||||
You need two environment variables:
|
||||
|
||||
- `KANAME_URL`: e.g. `https://models.example.com` (no trailing slash)
|
||||
- `KANAME_TOKEN`: the API token (`kn_…`). **Never print it, log it or put it in a URL.**
|
||||
|
||||
The examples use `kaname`, a two-line wrapper around `curl` that adds the token and JSON headers.
|
||||
Install 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` isn't available, write the full command every time instead:
|
||||
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …`.
|
||||
Every command may run in a fresh shell, so don't rely on a shell function or alias.
|
||||
|
||||
Every answer is JSON. Errors look like `{"error": {"code": "…", "message": "…"}}`, and the message
|
||||
says what to do next. Read it before you do anything else.
|
||||
|
||||
## 0. Check who you are and your limits
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1"
|
||||
```
|
||||
|
||||
This returns your token name, your **scopes** (what you're allowed to do) and the **guardrails**:
|
||||
|
||||
| Field | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `approvalMode` | `approve` | Your downloads and repairs wait until the user approves them. That's normal, not an error. |
|
||||
| `maxRequestSize` | 60 GB | One request may download at most this much. |
|
||||
| `minFreeSize` | 100 GB | This much must stay free on disk after your download. |
|
||||
| `maxOpenAgentJobs` | 2 | At most this many agent downloads may be pending or running at once. |
|
||||
| `allowedAuthors` | `[]` (any) | If not empty, new downloads must come from these Hugging Face authors. |
|
||||
|
||||
| Scope | Lets you |
|
||||
| --- | --- |
|
||||
| `models:read` | look up repos, list models and tags, read jobs and disk space |
|
||||
| `downloads:create` | request downloads and repairs, cancel your own downloads |
|
||||
| `models:verify` | start verify and deep verify, cancel your own verify jobs |
|
||||
| `tags:write` | add and remove tags on models |
|
||||
|
||||
If a call answers `403 forbidden`, you lack the scope. Tell the user which one is missing; don't
|
||||
try another way around it.
|
||||
|
||||
## 1. Is the model already here?
|
||||
|
||||
Always check before you download.
|
||||
|
||||
```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` (every word must match the repo, author, family, quant or tags), `author`, `family`,
|
||||
`quant`, `tag`, `status`, `requested_by`. You can repeat a filter or separate values with commas
|
||||
(OR within a filter, AND across filters).
|
||||
|
||||
The `status` values are `pending`, `downloading`, `ready`, `incomplete`, `failed`, `deleting`,
|
||||
`pending_approval`, `update_available`, `repo_missing` and `commit_missing`.
|
||||
|
||||
If the model is there with `status: "ready"`, you're done. Don't request it again. For details on
|
||||
one model (its files and their state, tags, latest job):
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/models/<modelId>"
|
||||
```
|
||||
|
||||
`source: "local"` means a folder the user put there by hand, with no Hugging Face repo. Kaname
|
||||
can't download into a local model or repair it, but it can verify it and tag it.
|
||||
|
||||
## 2. Look up the repo on Hugging Face
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"
|
||||
```
|
||||
|
||||
`repo` can also be a pasted Hugging Face URL. From the answer, note:
|
||||
|
||||
- `sha`: the exact commit. You need it to request the download.
|
||||
- `quants`: one entry per GGUF quant, with `size`. Pick one that fits what the user asked for and
|
||||
is no bigger than `maxRequestSize`. If the user didn't say, `Q4_K_M` is a sensible default.
|
||||
- `inLibrary`: not `null` if the repo is already in Kaname (see step 1).
|
||||
- `gated`: if it isn't `false`, the download only works when the user's Hugging Face account has
|
||||
accepted the model's terms.
|
||||
|
||||
Check the free space before a big download:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/disk" # availableForRequests = what one request may still use
|
||||
```
|
||||
|
||||
## 3. Request the download
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/downloads" \
|
||||
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"<sha from the lookup>","quant":"Q4_K_M"}'
|
||||
```
|
||||
|
||||
- `quant` downloads that quant's weight files (every split part), plus the companion files the user
|
||||
picked in Kaname's settings (chat template, vision projector, …).
|
||||
- For repos without GGUF quants (safetensors), send `"include": ["*.safetensors", "*.json"]` instead
|
||||
of `quant`. Send exactly one of the two.
|
||||
- Optional: `"tags": ["coding"]`. Run `GET /api/v1/tags` first and reuse the tags that already
|
||||
exist.
|
||||
|
||||
Kaname answers with one of these:
|
||||
|
||||
| Answer | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `201`, `state: "pending_approval"` | Waits for the user. | Tell the user what you requested (repo, quant, size) and that they need to approve it in Kaname. **Stop there. Don't retry and don't poll.** |
|
||||
| `201`, `state: "queued"` | Starts on its own. | Follow it (step 4). |
|
||||
| `200`, `created: false` | Exactly this was already requested. | You get the existing job back. Don't request it again. |
|
||||
|
||||
If the repo is already in the library at the same commit, the request adds only the missing files
|
||||
(for example another quant). A repo that's in the library at a different commit is refused: only
|
||||
the user can update it.
|
||||
|
||||
## 4. Follow a job
|
||||
|
||||
```bash
|
||||
kaname -m 960 "$KANAME_URL/api/v1/jobs/<jobId>?wait=900"
|
||||
```
|
||||
|
||||
With `?wait=900`, Kaname holds the request open until the job is finished, or up to 900 seconds.
|
||||
One such call replaces a whole polling loop. Keep curl's `-m` a bit above the wait. Each call costs
|
||||
you context, so make few of them:
|
||||
|
||||
| `state` | What you do |
|
||||
| --- | --- |
|
||||
| `pending_approval` | Don't poll. Tell the user it waits for their approval and stop. Check again only when the user says they approved it (or, if they ask for it, once later from a scheduled task). |
|
||||
| `queued`, `downloading`, `verifying` | One call with `?wait=900`. If it comes back with `timedOut: true`, tell the user the progress and the ETA (`progress.etaSeconds`) instead of waiting again and again. |
|
||||
| `completed` | Tell the user it's ready. For a verify job, also read `verify` (see step 5). |
|
||||
| `cancelled` | The user rejected or cancelled it. Don't ask again unless they tell you to. |
|
||||
| `failed` | Report `error.message` to the user. Don't retry in a loop. |
|
||||
| `interrupted` | Kaname restarted. Tell the user; they can resume it. |
|
||||
|
||||
Add `&log=20` only when you need to explain a failure (the last lines of the download log).
|
||||
|
||||
## 5. Verify and repair
|
||||
|
||||
Run a verify when the user asks whether a model is intact, or after something went wrong:
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/models/<modelId>/verify" # presence and size, takes seconds
|
||||
kaname -X POST "$KANAME_URL/api/v1/models/<modelId>/verify" -d '{"deep":true}' # hashes every byte: slow, but thorough
|
||||
```
|
||||
|
||||
A verify starts right away; it never needs approval. Follow it like any other job. When it has
|
||||
finished, the job has a `verify` block:
|
||||
|
||||
```json
|
||||
"verify": { "ok": false, "missing": ["…gguf"], "sizeMismatch": [], "hashMismatch": [], "next": "POST /api/v1/models/…/repair …" }
|
||||
```
|
||||
|
||||
If `ok` is `false`, repair it. That downloads only the files that are missing or broken:
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/models/<modelId>/repair"
|
||||
```
|
||||
|
||||
A repair counts as a download: same guardrails, and by default it waits for the user's approval
|
||||
just like step 3. If nothing is broken, Kaname answers `409 nothing_to_repair`. Then don't repair;
|
||||
run a deep verify if you suspect damage. Deep verify and repair aren't possible for local models.
|
||||
|
||||
## 6. Tags
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/tags" # existing tags, with how many models use each
|
||||
kaname -X POST "$KANAME_URL/api/v1/models/<modelId>/tags" -d '{"name":"coding"}' # add (creates the tag if it's new)
|
||||
kaname -X DELETE "$KANAME_URL/api/v1/models/<modelId>/tags/coding" # remove (by name, case-insensitive)
|
||||
```
|
||||
|
||||
Reuse existing tags instead of inventing near-duplicates (`code` vs `coding`). Removing a tag from a
|
||||
model doesn't delete the tag itself. Tag only what the user asked for, or what clearly fits their
|
||||
existing scheme.
|
||||
|
||||
## 7. Cancel your own job
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/jobs/<jobId>/cancel"
|
||||
```
|
||||
|
||||
This works only for jobs your token requested:
|
||||
|
||||
- A job that's still `pending_approval` is withdrawn. If it was a brand-new model, the model leaves
|
||||
the library again (`removedModel: true`).
|
||||
- A queued or running job is stopped. Files that are already downloaded stay.
|
||||
|
||||
For anything else you get `403 not_own_job`: tell the user they can cancel it in Kaname.
|
||||
|
||||
## 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` | Your earlier downloads are still pending or running. Tell the user and stop. Don't wait in a loop. |
|
||||
| `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 already has a job pending or running. Tell the user and stop. |
|
||||
| `nothing_to_repair` | Every file is present. Run a deep verify first if you suspect damage. |
|
||||
| `local_model` | A local folder: nothing to download, and no hashes to compare against. Use a plain verify. |
|
||||
| `not_own_job` | Only the user can cancel this job. |
|
||||
| `gated_no_access`, `gated_no_token` | The user must accept the model's terms on Hugging Face (and Kaname needs a token). |
|
||||
| `disk_unknown` | Kaname's worker is offline. Tell the user and stop. |
|
||||
| `rate_limited` | Hugging Face is rate limiting. Try once more later, not in a loop. |
|
||||
| `unauthorized`, `forbidden` | Your token is wrong or revoked, or it lacks a scope. Tell the user. |
|
||||
| `invalid_request`, `invalid_json` | Fix the request as the message says. |
|
||||
|
||||
Never work around a guardrail, for example by splitting one big download into several requests, or
|
||||
by repairing a model to fetch files it never had. Everything you do is listed under your token's
|
||||
name in Kaname, refusals included.
|
||||
|
||||
## A complete example
|
||||
|
||||
> User: "Get me Qwen3 8B, something that fits in about 6 GB."
|
||||
|
||||
1. `kaname "$KANAME_URL/api/v1/models?q=qwen3%208b"`: nothing ready yet.
|
||||
2. `kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"`: `Q4_K_M` is 5.0 GB; note `sha`.
|
||||
3. `kaname -X POST "$KANAME_URL/api/v1/downloads" -d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"…","quant":"Q4_K_M"}'`
|
||||
answers `pending_approval`.
|
||||
4. Tell the user: "I've requested unsloth/Qwen3-8B-GGUF Q4_K_M (5.0 GB). It's waiting for your
|
||||
approval in Kaname." Then stop.
|
||||
5. When the user says it's approved: `kaname -m 960 "$KANAME_URL/api/v1/jobs/<jobId>?wait=900"`, then
|
||||
report that it's done, or the progress and ETA.
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
# curl with the Kaname API token and JSON headers. Usage: kaname [curl options] URL
|
||||
exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
# Kaname API (`/api/v1`)
|
||||
|
||||
A small JSON API for programs and AI agents: look up Hugging Face repos, list the library, request
|
||||
downloads and follow them, verify and repair models, and tag them. Everything a token can do is
|
||||
bounded by [guardrails](#guardrails). No token can delete models or files, update a model to
|
||||
another commit, change settings, manage tokens, or touch jobs it didn't request.
|
||||
|
||||
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.
|
||||
|
||||
For agents there's a ready-made skill: [docs/agent/SKILL.md](agent/SKILL.md). Give it to the agent
|
||||
together with `KANAME_URL` and `KANAME_TOKEN`.
|
||||
|
||||
- [Authentication](#authentication)
|
||||
- [Errors](#errors)
|
||||
- [Endpoints](#endpoints)
|
||||
- [Waiting instead of polling](#waiting-instead-of-polling)
|
||||
- [Guardrails](#guardrails) and [approval](#approval)
|
||||
- [Activity](#activity)
|
||||
- [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 and tags, read jobs (and their log), disk space |
|
||||
| `downloads:create` | Request downloads and repairs (within the guardrails); cancel its own downloads |
|
||||
| `models:verify` | Start verify and deep verify; cancel its own verify jobs |
|
||||
| `tags:write` | Add and remove tags on models (a new tag is created on first use) |
|
||||
|
||||
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. **Scopes** changes what a token may do (from its
|
||||
next request on); **Revoke** stops it immediately; a revoked token can be deleted to free its name.
|
||||
|
||||
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 (**Requested by**).
|
||||
|
||||
## 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` (the quant or globs match nothing), `invalid_repo_id`, `invalid` (e.g. an empty tag name) |
|
||||
| 401 / 403 | `unauthorized`, `forbidden` (scope), `not_own_job`, `author_not_allowed`, `gated_no_token`, `gated_no_access` |
|
||||
| 404 | `not_found`, `repo_not_found`, `revision_not_found` |
|
||||
| 409 | `already_exists` (the repo is in the library at another commit), `busy` (the model has a pending, queued or running job), `nothing_to_repair`, `local_model`, `not_cancellable`, `hub_missing` |
|
||||
| 422 | `too_large` |
|
||||
| 429 | `too_many_jobs`, `rate_limited` (Hugging Face) |
|
||||
| 503 / 507 | `disk_unknown` (worker offline), `disk_space` |
|
||||
|
||||
Sizes come as bytes plus a readable `"… GB"` field (decimal GB, like the Hub).
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Method and path | Scope |
|
||||
| --- | --- |
|
||||
| [`GET /api/v1`](#get-apiv1) | any token |
|
||||
| [`GET /api/v1/hub/lookup?repo=`](#get-apiv1hublookup) | `models:read` |
|
||||
| [`GET /api/v1/models`](#get-apiv1models), [`GET /api/v1/models/{id}`](#get-apiv1modelsid) | `models:read` |
|
||||
| [`GET /api/v1/tags`](#tags) | `models:read` |
|
||||
| [`GET /api/v1/jobs/{id}`](#get-apiv1jobsid) | `models:read` |
|
||||
| [`GET /api/v1/disk`](#get-apiv1disk) | `models:read` |
|
||||
| [`POST /api/v1/downloads`](#post-apiv1downloads) | `downloads:create` |
|
||||
| [`POST /api/v1/models/{id}/repair`](#post-apiv1modelsidrepair) | `downloads:create` |
|
||||
| [`POST /api/v1/models/{id}/verify`](#post-apiv1modelsidverify) | `models:verify` |
|
||||
| [`POST /api/v1/jobs/{id}/cancel`](#post-apiv1jobsidcancel) | `downloads:create` or `models:verify` (own jobs only) |
|
||||
| [`POST /api/v1/models/{id}/tags`, `DELETE /api/v1/models/{id}/tags/{name}`](#tags) | `tags:write` |
|
||||
|
||||
### `GET /api/v1`
|
||||
|
||||
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]`. 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`
|
||||
|
||||
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", "source": "hub", "status": "ready",
|
||||
"pendingApproval": false, "pinnedSha": "9e68…", "quants": ["Q4_K_M"], "tags": ["agent"], "selectedFiles": 2,
|
||||
"selectedBytes": 5027783488, "onDiskBytes": 5027783488, "onDisk": "5.0 GB", "updateAvailable": false,
|
||||
"hubState": "available", "requestedBy": "hermes", "createdAt": "…", "downloadedAt": "…" }] }
|
||||
```
|
||||
|
||||
`source` is `local` for folders imported without a Hub repo; they have no `pinnedSha`.
|
||||
|
||||
### `GET /api/v1/models/{id}`
|
||||
|
||||
One model: status, pinned commit, tags, folder (`localPath`, relative to the models folder), the
|
||||
selected files with their state (`pending`, `present`, `missing`, `size_mismatch`, `hash_mismatch`,
|
||||
`verified`), the last verify time and the latest job.
|
||||
|
||||
### `POST /api/v1/downloads`
|
||||
|
||||
Request a download of a repo **at a pinned commit**: take `sha` from the lookup.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `repoId` | `"org/name"` |
|
||||
| `sha` | The 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", "template"],
|
||||
"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 *Ask me*) or `queued` (*Automatic*).
|
||||
- **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 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. A local model with the same name is refused too.
|
||||
|
||||
It uses the same code as the Add model dialog: the file list is fetched again from the Hub at that
|
||||
commit (the client's list isn't trusted).
|
||||
|
||||
### `POST /api/v1/models/{id}/repair`
|
||||
|
||||
Downloads again the selected files that aren't `present` or `verified` (after a verify found them
|
||||
missing or broken, or after a failed download). The guardrails and approval apply as for a download;
|
||||
only the author allowlist doesn't (the model is already in the library). `409 nothing_to_repair` if
|
||||
every file is present; `409 local_model` for a local model.
|
||||
|
||||
```json
|
||||
{ "modelId": "01M…", "jobId": "01M…", "state": "pending_approval", "requestedBytes": 8000000000,
|
||||
"requestedSize": "8.0 GB", "files": ["Qwen3-8B-Q8_0.gguf"], "message": "…" }
|
||||
```
|
||||
|
||||
### `POST /api/v1/models/{id}/verify`
|
||||
|
||||
Body optional: `{"deep": true}` hashes every file against the Hub (slow); without it, Kaname checks
|
||||
each selected file's presence and size (seconds). Verify only reads files, so it never waits for
|
||||
approval and doesn't count against the guardrails. Deep verify isn't possible for a local model.
|
||||
Answers `201` with the `jobId`; the finished job carries a [`verify`](#get-apiv1jobsid) block.
|
||||
|
||||
### `GET /api/v1/jobs/{id}`
|
||||
|
||||
`[?wait=S][&log=N]`. 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; GET with ?wait=900 instead of polling." }
|
||||
```
|
||||
|
||||
- `kind`: `download`, `verify`, `deep_verify` or `delete`. `purpose` (downloads): `initial`, `add`,
|
||||
`import`, `repair`, `update`.
|
||||
- `state`: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `failed`,
|
||||
`cancelled` (also when the user rejected the request), `interrupted`.
|
||||
- A finished verify adds
|
||||
`"verify": { "checked": 2, "missing": [], "sizeMismatch": [], "hashMismatch": [], "ok": true, "next": "…" }`.
|
||||
- The `hf` log only with `?log=N` (the last N lines, at most 200). For `?wait=S` see
|
||||
[Waiting instead of polling](#waiting-instead-of-polling).
|
||||
|
||||
### `POST /api/v1/jobs/{id}/cancel`
|
||||
|
||||
Only for jobs this token requested (`403 not_own_job` otherwise); download jobs need
|
||||
`downloads:create`, verify jobs `models:verify`.
|
||||
|
||||
- A job that waits for approval is **withdrawn**, exactly like a rejection: a model that only this
|
||||
request added leaves the library again (`"removedModel": true`), and added files leave the
|
||||
selection again.
|
||||
- A queued or running job is stopped by the worker (`"state": "cancelling"`). Files already on disk
|
||||
stay.
|
||||
|
||||
### Tags
|
||||
|
||||
- `GET /api/v1/tags`: every tag with the number of models using it:
|
||||
`{ "count": 2, "tags": [{ "name": "coding", "models": 3 }, …] }`.
|
||||
- `POST /api/v1/models/{id}/tags` with `{"name": "coding"}`: attaches the tag, creating it if no
|
||||
tag of that name exists (names match case-insensitively). Answers with the model's tags.
|
||||
- `DELETE /api/v1/models/{id}/tags/{name}`: detaches the tag (by name, case-insensitive; URL-encode
|
||||
it). The tag itself stays; delete or rename tags in Settings → Tags.
|
||||
|
||||
### `GET /api/v1/disk`
|
||||
|
||||
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 it hits the minimum-free guardrail.
|
||||
|
||||
## Waiting instead of polling
|
||||
|
||||
Every status call costs an agent a round of its context. `GET /api/v1/jobs/{id}` takes `?wait=S`
|
||||
(seconds, at most 900): the request is held until the job is settled (finished, failed, cancelled,
|
||||
interrupted) or the time is up, then answers with the current state plus `waitedSeconds` and
|
||||
`timedOut`. A job that waits for the user's approval answers right away: there's 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
|
||||
|
||||
Settings → API tokens → **Guardrails for API downloads**. They apply to every token together and to
|
||||
downloads and repairs; downloads you start in the UI aren't affected.
|
||||
|
||||
| Setting | Default | Rejection |
|
||||
| --- | --- | --- |
|
||||
| Approval | **Ask me**: requests wait as *pending approval* until you approve or reject them | (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 downloads or repairs (pending approval, queued or running) | `429 too_many_jobs` |
|
||||
| Allowed authors | empty = any; e.g. `unsloth, ggml-org, Qwen` (case-insensitive). New downloads only | `403 author_not_allowed` |
|
||||
|
||||
Verify, deep verify and tags never need approval and don't count against these limits; a model can
|
||||
have only one job at a time either way (`409 busy`).
|
||||
|
||||
### Approval
|
||||
|
||||
A pending request shows an **Approve / Reject** bar on the model page and the job page, and
|
||||
*awaiting approval* in the library (filter Status → awaiting approval). Approving queues it.
|
||||
Rejecting cancels the 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.
|
||||
|
||||
## Activity
|
||||
|
||||
Settings → API tokens → **Activity** next to each token lists what it did: every request that
|
||||
creates or changes something (downloads, repairs, verifies, tags, cancels), whether it waits for
|
||||
approval, and every refusal with its 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
|
||||
```
|
||||
|
||||
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.
|
||||
- `?wait=` holds a request open for up to 15 minutes; raise the proxy's response timeout, or ask
|
||||
agents to use a shorter wait.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 705 KiB |
@@ -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;
|
||||
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE `agent_activity` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`token_id` text NOT NULL,
|
||||
`token_name` text NOT NULL,
|
||||
`action` text NOT NULL,
|
||||
`target_type` text,
|
||||
`target_id` text,
|
||||
`outcome` text NOT NULL,
|
||||
`code` text,
|
||||
`message` text,
|
||||
`created_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `agent_activity_token_idx` ON `agent_activity` (`token_id`,`created_at`);--> statement-breakpoint
|
||||
CREATE TABLE `api_tokens` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`prefix` text NOT NULL,
|
||||
`hash` text NOT NULL,
|
||||
`scopes` text NOT NULL,
|
||||
`last_used_at` integer,
|
||||
`revoked_at` integer,
|
||||
`created_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_tokens_hash_unique` ON `api_tokens` (`hash`);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_tokens_name_uq` ON `api_tokens` (`name`);--> statement-breakpoint
|
||||
ALTER TABLE `jobs` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `jobs` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `requested_by` text;
|
||||
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
@@ -169,6 +169,34 @@
|
||||
"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
|
||||
},
|
||||
{
|
||||
"idx": 27,
|
||||
"version": "6",
|
||||
"when": 1794429640033,
|
||||
"tag": "0027_api_tokens",
|
||||
"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.15.1",
|
||||
"version": "0.22.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 && esbuild src/sandbox/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/sandbox.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"
|
||||
}
|
||||
}
|
||||
@@ -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,7 +2,9 @@
|
||||
|
||||
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { ApprovalBar } from "@/components/approval-bar";
|
||||
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
|
||||
import { JobProgress, JobStateBadge } from "@/components/job-progress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -22,17 +24,22 @@ 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");
|
||||
@@ -58,15 +65,17 @@ export function DownloadCard({
|
||||
: latest?.state === "failed" && latest.kind === "download"
|
||||
? "Retry"
|
||||
: "Download missing";
|
||||
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
const canDownload = !open && !pending && !local && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !pending && (!neverRan || local) && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !pending && !local && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
|
||||
let hint = "Downloads the selected files at the pinned commit.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
let hint = local ? "A local folder: Kaname keeps its files as they are." : "Downloads the selected files at the pinned commit.";
|
||||
if (pending) hint = "Requested through the API; waits for your approval.";
|
||||
else if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
else if (open) hint = "Runs in the background; you can close this page.";
|
||||
else if (status === "deleting") hint = "Deleting…";
|
||||
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
else if (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 =
|
||||
@@ -77,13 +86,15 @@ 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>
|
||||
|
||||
{showProgress && <JobProgress job={latest} compact />}
|
||||
{pending && <ApprovalBar job={pending} onRemoved={() => router.push("/")} />}
|
||||
|
||||
{showProgress && !pending && <JobProgress job={latest} compact />}
|
||||
|
||||
{latest?.state === "failed" && latest.errorMessage && (
|
||||
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
|
||||
@@ -145,15 +156,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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useRecommended } from "@/hooks/use-recommended";
|
||||
import { groupSplitFiles } from "@/lib/file-groups";
|
||||
import { formatBytes, percent, shortSha } from "@/lib/format";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { ReloadButton } from "./reload-button";
|
||||
|
||||
type Candidate = { path: string; size: number };
|
||||
|
||||
@@ -32,6 +33,7 @@ export function FilesHeader({
|
||||
freeBytes,
|
||||
busy,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
sha: string;
|
||||
@@ -47,6 +49,8 @@ export function FilesHeader({
|
||||
busy: boolean;
|
||||
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
|
||||
hubMissing: boolean;
|
||||
/** A local model: "Reload" reads the folder again instead of "Download more". */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -121,14 +125,15 @@ 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">
|
||||
<span className="text-muted-foreground">
|
||||
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
|
||||
</span>
|
||||
{candidates.length > 0 && !hubMissing && (
|
||||
{local && <ReloadButton />}
|
||||
{!local && candidates.length > 0 && !hubMissing && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={open ? "outline" : "default"}
|
||||
|
||||
@@ -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}`;
|
||||
};
|
||||
@@ -159,11 +165,27 @@ export function FilesTab({
|
||||
freeBytes={freeBytes}
|
||||
busy={busy}
|
||||
hubMissing={hubMissing}
|
||||
local={local}
|
||||
/>
|
||||
|
||||
<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, or right away with Reload on the Files tab.
|
||||
</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,7 +2,6 @@ import {
|
||||
ArrowDownIcon,
|
||||
BoxIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FileTextIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
@@ -17,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 { 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 { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { headline, targetName } from "@/lib/benchmark-view";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
import { targetName } from "@/lib/benchmark-view";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
import { getModelByRepo, relatedModels } from "@/lib/library";
|
||||
@@ -39,9 +38,10 @@ 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 { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -94,6 +94,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}`;
|
||||
@@ -101,13 +103,13 @@ 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, runs] = 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),
|
||||
listBenchmarks({ modelId: model.id }),
|
||||
listBenchmarks({ modelId: model.id }, { limit: 5 }), // the sidebar shows 5 and links to all
|
||||
]);
|
||||
const update =
|
||||
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
|
||||
@@ -129,35 +131,49 @@ 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} />
|
||||
<RequestedByBadge name={model.requestedBy} />
|
||||
{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} />
|
||||
{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">
|
||||
<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>
|
||||
@@ -180,11 +196,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">
|
||||
@@ -239,32 +256,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>
|
||||
)}
|
||||
@@ -278,6 +285,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" && (
|
||||
@@ -289,20 +297,20 @@ 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>
|
||||
|
||||
{runs.length > 0 && (
|
||||
<SideCard title="Benchmarks" icon={GaugeIcon}>
|
||||
<div className="flex flex-col gap-1">
|
||||
{runs.slice(0, 5).map((r) => {
|
||||
const h = headline(r.summary);
|
||||
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">{r.label ?? targetName(r.snapshot)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
|
||||
{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>
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
@@ -322,6 +330,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}>
|
||||
@@ -334,6 +349,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}`}>
|
||||
@@ -353,6 +370,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")}>
|
||||
@@ -374,6 +393,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} />
|
||||
@@ -381,6 +402,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</dl>
|
||||
</SideCard>
|
||||
|
||||
{!local && (
|
||||
<SideCard title="Model tree" icon={SparklesIcon}>
|
||||
<ModelTree
|
||||
repoId={model.repoId}
|
||||
@@ -400,9 +422,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
</SideCard>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -432,9 +455,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" />}
|
||||
@@ -443,18 +467,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,54 @@
|
||||
"use client";
|
||||
|
||||
import { RefreshCwIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** The worker picks a scan request up with its next heartbeat (every 5 s); a big models folder takes longer. */
|
||||
const TIMEOUT_MS = 90_000;
|
||||
const POLL_MS = 1_500;
|
||||
|
||||
/**
|
||||
* Local models: read the folder again (files and README). Asks the worker for a scan of the models
|
||||
* folder and waits until it has finished, then reloads the page.
|
||||
*/
|
||||
export function ReloadButton() {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function reload() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/local-folders/scan", { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok || typeof body.requestedAt !== "number") {
|
||||
toast.error(body.error?.message ?? `Could not start a scan (${res.status})`);
|
||||
return;
|
||||
}
|
||||
const deadline = Date.now() + TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise((r) => setTimeout(r, POLL_MS));
|
||||
const state = await fetch("/api/local-folders/scan", { cache: "no-store" })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.catch(() => null);
|
||||
if (state?.lastScanAt != null && state.lastScanAt >= body.requestedAt) {
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
}
|
||||
toast.error("The worker hasn't scanned the folder yet. Is it running?");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Button size="sm" variant="outline" onClick={() => void reload()} disabled={busy} title="Read the folder again: files and README.md">
|
||||
<RefreshCwIcon className={cn(busy && "animate-spin")} />
|
||||
{busy ? "Reloading…" : "Reload"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
))}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib
|
||||
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)}%`;
|
||||
|
||||
@@ -56,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;
|
||||
@@ -69,7 +69,7 @@ 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
|
||||
|
||||
@@ -31,10 +31,23 @@ import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
|
||||
import { CONFIG_ROWS, describeSettings, engineName, isEndpointSnapshot, modelName, targetName } from "@/lib/benchmark-view";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
import {
|
||||
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";
|
||||
@@ -55,7 +68,7 @@ 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());
|
||||
@@ -104,7 +117,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
// 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 ? (
|
||||
legacy ? (
|
||||
name
|
||||
) : id ? (
|
||||
<Link href={`/endpoints/${id}`} className="hover:underline">
|
||||
{name}
|
||||
</Link>
|
||||
@@ -114,136 +129,141 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
const took = duration(r.startedAt, r.finishedAt, now);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardContent className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="text-xl font-semibold">
|
||||
{r.label ?? (r.kind === "ab" && sB ? `${targetName(s)} vs ${targetName(sB)}` : targetName(s))}
|
||||
</h1>
|
||||
{r.kind === "ab" && (
|
||||
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">
|
||||
A/B
|
||||
</span>
|
||||
)}
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{endpointLink(r.endpointId, targetName(s))} ·{" "}
|
||||
{r.modelId ? (
|
||||
<Link href={`/models/${r.modelId}`} className="hover:underline">
|
||||
{modelName(s)}
|
||||
</Link>
|
||||
) : (
|
||||
modelName(s)
|
||||
)}{" "}
|
||||
· {engineName(s)}
|
||||
{r.kind === "ab" && sB && (
|
||||
<>
|
||||
{" "}
|
||||
· B: {endpointLink(r.endpointBId, targetName(sB))} ({engineName(sB)})
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
|
||||
{r.kind === "ab"
|
||||
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
|
||||
: describeSettings(r.settings)}{" "}
|
||||
· created <LocalTime value={r.createdAt} />
|
||||
{took &&
|
||||
` · ${r.state === "running" ? "running for" : "took"} ${took}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{r.hasReport && (
|
||||
<a
|
||||
href={`/api/benchmarks/${r.id}/report`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={buttonVariants({ variant: "outline" })}
|
||||
>
|
||||
<ExternalLinkIcon />
|
||||
Full report
|
||||
</a>
|
||||
<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.endpointId &&
|
||||
(r.kind !== "ab" || r.endpointBId) && (
|
||||
)
|
||||
)}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={again}
|
||||
title="Queue a new run with the same settings against the same endpoint"
|
||||
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>
|
||||
|
||||
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" />
|
||||
@@ -263,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} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <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"
|
||||
@@ -275,7 +301,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
{r.kind === "run" && r.state === "completed" && r.summary && (
|
||||
<PublishCard
|
||||
runId={r.id}
|
||||
defaultTitle={r.label ?? `${modelName(s).split("/").pop()} ${weightsLabel(s)}`}
|
||||
defaultTitle={
|
||||
r.label ?? `${modelName(s).split("/").pop()} ${weightsLabel(s)}`
|
||||
}
|
||||
defaultSummary={reportSummary(r)}
|
||||
/>
|
||||
)}
|
||||
@@ -319,7 +347,8 @@ 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>
|
||||
@@ -353,7 +382,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
</div>
|
||||
)}
|
||||
{isEndpointSnapshot(s) && s.hardware.description && (
|
||||
<p className="text-xs whitespace-pre-wrap text-muted-foreground">{s.hardware.description}</p>
|
||||
<p className="text-xs whitespace-pre-wrap text-muted-foreground">
|
||||
{s.hardware.description}
|
||||
</p>
|
||||
)}
|
||||
{sum && (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
@@ -366,6 +397,6 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportS
|
||||
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 (
|
||||
@@ -54,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;
|
||||
@@ -72,7 +72,7 @@ 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)}
|
||||
|
||||
@@ -17,20 +17,23 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { BenchmarkRow } from "@/lib/benchmarks";
|
||||
import { configChips, describeSettings, engineName, headline, modelName, targetName } 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);
|
||||
@@ -165,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
|
||||
@@ -214,7 +217,7 @@ export function BenchmarkList({
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">
|
||||
{r.kind === "eval" ? (
|
||||
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
|
||||
<span title="Quality eval score">{r.qualityScore != null ? `${r.qualityScore}% quality` : "–"}</span>
|
||||
) : (
|
||||
fmt(h.decode)
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -117,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>
|
||||
@@ -193,7 +196,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
@@ -12,10 +13,11 @@ export default async function BenchmarksPage({ searchParams }: PageProps<"/bench
|
||||
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">
|
||||
<PageHero
|
||||
title="Benchmarks"
|
||||
painting={{ view: 0.6, focus: [0.25, 0.6], anchor: [0.65, 0.4] }}
|
||||
description={
|
||||
<>
|
||||
{model ? (
|
||||
<>
|
||||
Runs of{" "}
|
||||
@@ -36,9 +38,10 @@ export default async function BenchmarksPage({ searchParams }: PageProps<"/bench
|
||||
. Start one from an endpoint; select runs to compare their settings and numbers.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} filter={{ model: model?.model.id }} />
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
|
||||
import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/enums";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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";
|
||||
@@ -10,9 +11,8 @@ export default async function EditEndpointPage({ params }: PageProps<"/endpoints
|
||||
const endpoint = await getEndpoint((await params).id);
|
||||
if (!endpoint) notFound();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">Edit {endpoint.name}</h1>
|
||||
<PageHero title={`Edit ${endpoint.name}`} painting={{ view: 0.55, focus: [0.75, 0.35], anchor: [0.65, 0.35] }}>
|
||||
<EndpointForm initial={endpoint} />
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -17,13 +17,21 @@ import {
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import type { EndpointView } from "@/lib/endpoints";
|
||||
import { ProbeResult } from "../endpoint-form";
|
||||
import { EndpointStatus } from "../endpoint-status";
|
||||
|
||||
/** Name, URL, connection test, edit and delete. */
|
||||
export function EndpointHeader({ endpoint, runCount }: { endpoint: EndpointView; runCount: number }) {
|
||||
/** 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);
|
||||
@@ -31,9 +39,14 @@ export function EndpointHeader({ endpoint, runCount }: { endpoint: EndpointView;
|
||||
async function test() {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/endpoints/${endpoint.id}/test`, { method: "POST" });
|
||||
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})`);
|
||||
if (!res.ok)
|
||||
return toast.error(
|
||||
json.error?.message ?? `Test failed (${res.status})`,
|
||||
);
|
||||
setProbe(json);
|
||||
router.refresh();
|
||||
} finally {
|
||||
@@ -42,60 +55,82 @@ export function EndpointHeader({ endpoint, runCount }: { endpoint: EndpointView;
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const res = await fetch(`/api/endpoints/${endpoint.id}`, { method: "DELETE" });
|
||||
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})`);
|
||||
return toast.error(
|
||||
json.error?.message ?? `Could not delete (${res.status})`,
|
||||
);
|
||||
}
|
||||
router.push("/endpoints");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">{endpoint.name}</h1>
|
||||
<p className="text-sm break-all text-muted-foreground">
|
||||
{endpoint.baseUrl}
|
||||
{endpoint.hasApiKey ? " · API key set" : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EndpointStatus probe={probe} />
|
||||
<Button variant="outline" onClick={test} disabled={testing}>
|
||||
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
|
||||
Test connection
|
||||
</Button>
|
||||
<Link href={`/endpoints/${endpoint.id}/edit`} className={buttonVariants({ variant: "outline" })}>
|
||||
<PencilIcon />
|
||||
Edit
|
||||
</Link>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {endpoint.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The endpoint and its stored API key are removed.{runCount > 0 ? ` Its ${runCount} run${runCount === 1 ? "" : "s"} stay, with what they recorded.` : ""}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
{probe && <ProbeResult probe={probe} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -35,8 +35,7 @@ export default async function EndpointPage({ params }: PageProps<"/endpoints/[id
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<EndpointHeader endpoint={endpoint} runCount={runs.length} />
|
||||
<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
|
||||
@@ -48,10 +47,10 @@ export default async function EndpointPage({ params }: PageProps<"/endpoints/[id
|
||||
<aside className="flex flex-col gap-4">
|
||||
<RunMetaCard meta={preview} system={endpointSystem(endpoint.hardware, kanameVersion())} />
|
||||
{endpoint.hardware.description && (
|
||||
<p className="rounded-xl bg-card px-4 py-3 text-xs whitespace-pre-wrap text-muted-foreground ring-1 ring-foreground/10">{endpoint.hardware.description}</p>
|
||||
<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>
|
||||
</div>
|
||||
</EndpointHeader>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,8 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
|
||||
import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema";
|
||||
import { 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 };
|
||||
|
||||
@@ -1,13 +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 (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">New endpoint</h1>
|
||||
<PageHero title="New endpoint" painting={{ view: 0.55, focus: [0.75, 0.35], anchor: [0.65, 0.35] }}>
|
||||
<EndpointForm />
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -5,9 +5,9 @@ import { buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { listEndpoints } from "@/lib/endpoints";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { EndpointStatus } from "./endpoint-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -20,23 +20,23 @@ export default async function EndpointsPage() {
|
||||
for (const r of runs) {
|
||||
if (!r.endpointId || r.state !== "completed") continue;
|
||||
const cur = latest.get(r.endpointId) ?? { decode: null, quality: null };
|
||||
if (r.kind === "run" && cur.decode == null) cur.decode = headline(r.summary).decode;
|
||||
if (r.kind === "eval" && cur.quality == null) cur.quality = r.quality?.score ?? null;
|
||||
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 (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-end justify-between gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">Endpoints</h1>
|
||||
<p className="text-sm text-muted-foreground">OpenAI-compatible servers to benchmark. They run elsewhere; Kaname only sends them requests.</p>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
|
||||
{endpoints.length === 0 ? (
|
||||
<Card className="items-center gap-3 py-10 text-center">
|
||||
@@ -89,6 +89,6 @@ export default async function EndpointsPage() {
|
||||
</Table>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</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,10 +1,14 @@
|
||||
"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 { PageHero } from "@/components/hero/page-hero";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
@@ -21,6 +25,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
const files = snapshot?.files ?? [];
|
||||
const open = OPEN.includes(job.state);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const logRef = useRef<HTMLDivElement>(null);
|
||||
const [follow, setFollow] = useState(true);
|
||||
@@ -38,17 +43,20 @@ 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>
|
||||
{open && (
|
||||
</Link>{" "}
|
||||
<RequestedByBadge name={job.requestedBy} className="align-middle" />
|
||||
</>
|
||||
}
|
||||
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}
|
||||
@@ -60,8 +68,11 @@ 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">
|
||||
@@ -78,6 +89,12 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
<dd><LocalTime value={job.finishedAt} /></dd>
|
||||
<dt className="text-muted-foreground">Duration</dt>
|
||||
<dd>{formatDuration(duration)}</dd>
|
||||
{job.requestedBy && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Requested by</dt>
|
||||
<dd>{job.requestedBy} (API token)</dd>
|
||||
</>
|
||||
)}
|
||||
{job.exitCode != null && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Exit code</dt>
|
||||
@@ -144,6 +161,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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+155
-76
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { 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,11 +8,12 @@ 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 } from "@/components/ui/button";
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
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";
|
||||
@@ -27,11 +28,15 @@ 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 PAGE_SIZES = [10, 25, 50, 100];
|
||||
|
||||
const FACET_LABEL: Record<Facet, string> = {
|
||||
author: "Author",
|
||||
@@ -39,12 +44,13 @@ const FACET_LABEL: Record<Facet, string> = {
|
||||
quant: "Quant",
|
||||
tag: "Tag",
|
||||
status: "Status",
|
||||
requester: "Requested by",
|
||||
};
|
||||
|
||||
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
|
||||
const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (MODEL_STATUS[v as ModelStatus]?.label ?? v));
|
||||
|
||||
function toSearchable(r: LibraryRow): SearchableModel {
|
||||
return {
|
||||
const m: SearchableModel = {
|
||||
repoId: r.repoId,
|
||||
author: r.author,
|
||||
families: r.families,
|
||||
@@ -62,7 +68,10 @@ 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. */
|
||||
@@ -71,6 +80,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);
|
||||
@@ -84,25 +95,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>();
|
||||
@@ -111,90 +139,81 @@ 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-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">
|
||||
{base && base !== r.repoId && <span>base {base}</span>}
|
||||
{r.architecture && <span>{r.architecture}</span>}
|
||||
<RequestedByBadge name={r.requestedBy} className="h-4 text-[10px]" />
|
||||
{r.tags.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
@@ -206,23 +225,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" && <JobProgress job={job} compact />}
|
||||
{job.state !== "queued" && job.state !== "pending_approval" && <JobProgress job={job} compact />}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="flex flex-wrap gap-1">
|
||||
@@ -241,8 +278,50 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
})}
|
||||
</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>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { ShieldCheckIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { type ApprovalMode, type Guardrails, parseAuthorList } from "@/lib/agent-guardrails";
|
||||
|
||||
const GB = 1_000_000_000;
|
||||
const toGb = (b: number) => String(Math.round((b / GB) * 1000) / 1000);
|
||||
|
||||
/** Limits for downloads requested through the API. Saved together with one button. */
|
||||
export function GuardrailSettings({ initial }: { initial: Guardrails }) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
|
||||
const [maxGb, setMaxGb] = useState(toGb(initial.maxRequestBytes));
|
||||
const [minFreeGb, setMinFreeGb] = useState(toGb(initial.minFreeBytes));
|
||||
const [maxJobs, setMaxJobs] = useState(String(initial.maxOpenJobs));
|
||||
const [authors, setAuthors] = useState(initial.allowedAuthors.join(", "));
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
let authorError: string | null = null;
|
||||
let authorList: string[] = [];
|
||||
try {
|
||||
authorList = parseAuthorList(authors);
|
||||
} catch (err) {
|
||||
authorError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
const num = (s: string) => Number(s.replace(",", "."));
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (authorError) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/agent", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
approvalMode: mode,
|
||||
maxRequestBytes: Math.round(num(maxGb) * GB),
|
||||
minFreeBytes: Math.round(num(minFreeGb) * GB),
|
||||
maxOpenJobs: Math.round(num(maxJobs)),
|
||||
allowedAuthors: authorList,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
|
||||
toast.success("Guardrails saved");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<ShieldCheckIcon className="size-4 text-muted-foreground" />
|
||||
Guardrails for API downloads
|
||||
</CardTitle>
|
||||
<CardDescription>Apply to every download and repair requested with a token, across all tokens. Downloads you start in the UI are not affected. Verify and tags never need approval.</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. Applies to new downloads, not to repairs of models already in the library."}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
“Agent jobs at once” counts downloads and repairs that are pending approval, queued or downloading. The free-space check also subtracts what other open
|
||||
downloads still need.
|
||||
</p>
|
||||
<Button type="submit" className="self-start" disabled={busy || !!authorError}>
|
||||
Save guardrails
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listActivity } from "@/lib/agent-activity";
|
||||
import { listTokens } from "@/lib/api-tokens";
|
||||
import { getGuardrails } from "@/lib/settings";
|
||||
import { GuardrailSettings } from "./guardrail-settings";
|
||||
import { TokenSettings } from "./token-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "API tokens · Settings" };
|
||||
|
||||
export default async function ApiTokenSettingsPage() {
|
||||
const [tokens, guardrails] = await Promise.all([listTokens(), getGuardrails()]);
|
||||
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} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
"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/enums";
|
||||
|
||||
/** 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
|
||||
tokens. The guide for agents is in{" "}
|
||||
<code className="font-mono text-xs">docs/agent/SKILL.md</code>.
|
||||
</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> = {
|
||||
model: (id) => `/models/${id}`,
|
||||
job: (id) => `/jobs/${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>
|
||||
);
|
||||
}
|
||||
@@ -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()} />;
|
||||
}
|
||||
@@ -65,7 +65,7 @@ export function ScanSettings({ initial }: { initial: ScanStatus }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Card id="scan" className="scroll-mt-24">
|
||||
<CardHeader>
|
||||
<CardTitle>Models folder scan</CardTitle>
|
||||
<CardDescription>
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { BotIcon, 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/appearance", label: "Appearance", icon: <PaletteIcon className="size-4" /> },
|
||||
{ href: "/settings/api-tokens", label: "API tokens", icon: <BotIcon 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, the background picture, and API tokens for agents."
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
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;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { createToken, listTokens, TokenError } from "@/lib/api-tokens";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** API tokens for machine clients (Settings → API tokens). Never includes the tokens themselves. */
|
||||
export const GET = withAuth(async () => NextResponse.json(await listTokens()));
|
||||
|
||||
const Body = z.object({ name: z.string().max(40), scopes: z.array(z.string()).min(1).max(10) });
|
||||
|
||||
/** Create a token. The response is the only time the token is shown. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json(await createToken(body.name, body.scopes), { status: 201, headers: { "Cache-Control": "no-store" } });
|
||||
} catch (err) {
|
||||
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { approveJob } from "@/lib/agent-downloads";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError } from "@/lib/jobs";
|
||||
|
||||
/** Let a download requested through the API start. */
|
||||
export const POST = withAuth<RouteContext<"/api/jobs/[id]/approve">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await approveJob(id);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { rejectJob } from "@/lib/agent-downloads";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError } from "@/lib/jobs";
|
||||
|
||||
/** Turn down a download requested through the API (a model only it added leaves the library). */
|
||||
export const POST = withAuth<RouteContext<"/api/jobs/[id]/reject">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await rejectJob(id));
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
|
||||
import { liveBody, type LiveSnapshot } from "@/lib/live-protocol";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Live job state, polled by the browser about once per second while the tab is visible (one poller
|
||||
* per query and tab, see src/lib/live-store.ts). Short requests instead of a stream per component:
|
||||
* over HTTP/1.1 a browser allows 6 connections per host, and open streams used them up.
|
||||
* ?model=<id> jobs of one model (+ files of its newest job)
|
||||
* ?job=<id> one job with per-file progress; with &logAfter=<id> also the log lines after
|
||||
* that id (0: the last 1000)
|
||||
* (none) open and recently finished jobs (library view)
|
||||
* &v=<version> the snapshot version the client has; an unchanged snapshot is left out
|
||||
*/
|
||||
export const GET = withAuth(async (req) => {
|
||||
const sp = new URL(req.url).searchParams;
|
||||
const modelId = sp.get("model");
|
||||
const jobId = sp.get("job");
|
||||
const json = JSON.stringify(await buildSnapshot(modelId, jobId));
|
||||
const version = createHash("sha1").update(json).digest("base64url").slice(0, 16);
|
||||
const logs = jobId && sp.has("logAfter") ? await listJobLogs(jobId, Number(sp.get("logAfter")) || 0) : undefined;
|
||||
return new Response(liveBody(json, version, sp.get("v"), logs), {
|
||||
headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" },
|
||||
});
|
||||
});
|
||||
|
||||
async function buildSnapshot(modelId: string | null, jobId: string | null): Promise<LiveSnapshot> {
|
||||
const worker = await getWorkerStatus();
|
||||
if (jobId) {
|
||||
const job = await getJob(jobId);
|
||||
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
|
||||
}
|
||||
if (modelId) {
|
||||
const jobs = await listModelJobs(modelId);
|
||||
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
|
||||
return { worker, jobs, files };
|
||||
}
|
||||
return { worker, jobs: await listLiveJobs(), files: [] };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { getLocalFolder } from "@/lib/local-folders";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** One folder the scan found, with its files (`?path=<org>/<name>`): what the Import form needs. */
|
||||
export const GET = withAuth(async (req) => {
|
||||
const path = new URL(req.url).searchParams.get("path");
|
||||
const folder = path ? await getLocalFolder(path) : undefined;
|
||||
if (!folder) return apiError(404, "not_found", "This folder is no longer in the models folder. Rescan and try again.");
|
||||
return NextResponse.json({
|
||||
path: folder.path,
|
||||
commit: folder.commit,
|
||||
files: folder.files,
|
||||
fileCount: folder.fileCount,
|
||||
totalBytes: folder.totalBytes,
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { requestFolderScan } from "@/lib/local-folders";
|
||||
import { getScanState, requestFolderScan } from "@/lib/local-folders";
|
||||
|
||||
/** Ask the worker to rescan the models folder for importable folders. */
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Ask the worker to rescan the models folder (importable folders, and local models' files). */
|
||||
export const POST = withAuth(async () => {
|
||||
await requestFolderScan();
|
||||
return new NextResponse(null, { status: 202 });
|
||||
const requestedAt = await requestFolderScan();
|
||||
return NextResponse.json({ requestedAt: requestedAt.getTime() }, { status: 202 });
|
||||
});
|
||||
|
||||
/** When the worker last finished a scan, so a client can wait for the one it asked for. */
|
||||
export const GET = withAuth(async () => {
|
||||
return NextResponse.json(await getScanState());
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { addFilesToModel, ModelError } from "@/lib/models";
|
||||
import { addFilesToModel, ModelError, removeFilesFromModel } from "@/lib/models";
|
||||
|
||||
const Body = z.object({ add: z.array(z.string().min(1).max(1024)).min(1).max(10_000) });
|
||||
|
||||
@@ -17,3 +17,17 @@ export const POST = withAuth<RouteContext<"/api/models/[id]/files">>(async (req,
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
|
||||
const RemoveBody = z.object({ remove: z.array(z.string().min(1).max(1024)).min(1).max(10_000) });
|
||||
|
||||
/** Remove files from a model's selection and queue deleting them from disk. */
|
||||
export const DELETE = withAuth<RouteContext<"/api/models/[id]/files">>(async (req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const { remove } = RemoveBody.parse(await req.json());
|
||||
return NextResponse.json(await removeFilesFromModel(id, remove), { status: 202 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -8,5 +8,6 @@ export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (
|
||||
const { id } = await params;
|
||||
const model = await getCheckedModel(id);
|
||||
if (!model) return apiError(404, "not_found", "Model not found.");
|
||||
if (model.source === "local") return apiError(409, "local_model", "This is a local model without a Hugging Face repo.");
|
||||
return NextResponse.json(await checkHub(model));
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { addModel, ModelError } from "@/lib/models";
|
||||
import { addLocalModel, addModel, ModelError } from "@/lib/models";
|
||||
import { addTag, normalizeTagName, TagError } from "@/lib/tags";
|
||||
|
||||
const Body = z.object({
|
||||
@@ -19,10 +19,28 @@ const Body = z.object({
|
||||
localPath: z.string().min(1).max(512).optional(),
|
||||
});
|
||||
|
||||
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
|
||||
/** A folder from the models folder without a Hub repo, added as it is. */
|
||||
const LocalBody = z.object({
|
||||
source: z.literal("local"),
|
||||
localPath: z.string().min(1).max(512),
|
||||
tags: z.array(z.string()).max(50).default([]),
|
||||
});
|
||||
|
||||
/**
|
||||
* Add a model to the library, pinned to the SHA the user reviewed, and queue its download. With
|
||||
* `source: "local"`, add a folder from the models folder that has no Hub repo instead (nothing queued).
|
||||
*/
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
const json = await req.json();
|
||||
if (json?.source === "local") {
|
||||
const body = LocalBody.parse(json);
|
||||
body.tags.forEach(normalizeTagName);
|
||||
const { id } = await addLocalModel({ localPath: body.localPath });
|
||||
for (const tag of body.tags) await addTag(id, tag);
|
||||
return NextResponse.json({ id, jobId: null }, { status: 201 });
|
||||
}
|
||||
const body = Body.parse(json);
|
||||
body.tags.forEach(normalizeTagName); // validate before anything is written
|
||||
const { id } = await addModel({
|
||||
repoId: body.repoId,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { modelName, targetName } from "@/lib/benchmark-view";
|
||||
import { listEndpoints } from "@/lib/endpoints";
|
||||
import { listLibrary } from "@/lib/library";
|
||||
import { listTags } from "@/lib/tags";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Everything the ⌘K palette can jump to, compact (it filters in the browser). */
|
||||
export const GET = withAuth(async () => {
|
||||
const [models, endpoints, runs, tags] = await Promise.all([listLibrary(), listEndpoints(), listBenchmarks({}, { limit: 300 }), listTags()]);
|
||||
return NextResponse.json({
|
||||
models: models.map((m) => ({ id: m.id, repoId: m.repoId, quants: m.quants, status: m.status, tags: m.tags.map((t) => t.name) })),
|
||||
endpoints: endpoints.map((e) => ({ id: e.id, name: e.name, model: e.model, engine: e.engine ?? e.probe?.engine ?? null })),
|
||||
benchmarks: runs.map((r) => ({
|
||||
id: r.id,
|
||||
label: r.label,
|
||||
kind: r.kind,
|
||||
state: r.state,
|
||||
target: targetName(r.snapshot),
|
||||
model: modelName(r.snapshot),
|
||||
createdAt: r.createdAt.getTime(),
|
||||
})),
|
||||
tags: tags.map((t) => t.name),
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { APPROVAL_MODES } from "@/lib/agent-guardrails";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { getGuardrails, saveGuardrails, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Guardrails for downloads requested through the API. */
|
||||
export const GET = withAuth(async () => NextResponse.json(await getGuardrails()));
|
||||
|
||||
const Body = z
|
||||
.object({
|
||||
approvalMode: z.enum(APPROVAL_MODES),
|
||||
maxRequestBytes: z.number(),
|
||||
minFreeBytes: z.number(),
|
||||
maxOpenJobs: z.number().int(),
|
||||
allowedAuthors: z.array(z.string()).max(100),
|
||||
})
|
||||
.partial();
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await saveGuardrails(Body.parse(await req.json())));
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { getBackdrop, saveBackdrop, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Appearance: the custom picture behind the page headers (null for the built-in painting). */
|
||||
export const GET = withAuth(async () => NextResponse.json({ backdrop: await getBackdrop() }));
|
||||
|
||||
const Body = z.object({ backdrop: z.unknown() });
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json({ backdrop: await saveBackdrop(body.backdrop ?? null) });
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const INTERVAL_MS = 1_000;
|
||||
const KEEPALIVE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Server-Sent Events with live job state, polled from the DB once per second.
|
||||
* ?model=<id> jobs of one model (+ files of its newest job)
|
||||
* ?job=<id> one job with per-file progress and incremental log lines
|
||||
* (none) open and recently finished jobs (library view)
|
||||
* Events: "snapshot" (only when something changed) and "logs" (new lines).
|
||||
*/
|
||||
export const GET = withAuth(async (req) => {
|
||||
const url = new URL(req.url);
|
||||
const modelId = url.searchParams.get("model");
|
||||
const jobId = url.searchParams.get("job");
|
||||
let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0;
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const signal = req.signal;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
let last = "";
|
||||
let lastWrite = Date.now();
|
||||
const write = (chunk: string) => {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
lastWrite = Date.now();
|
||||
};
|
||||
const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
|
||||
try {
|
||||
write("retry: 3000\n\n");
|
||||
while (!signal.aborted) {
|
||||
const snapshot = await buildSnapshot(modelId, jobId);
|
||||
const serialized = JSON.stringify(snapshot);
|
||||
if (serialized !== last) {
|
||||
send("snapshot", snapshot);
|
||||
last = serialized;
|
||||
}
|
||||
if (jobId) {
|
||||
const lines = await listJobLogs(jobId, logCursor);
|
||||
if (lines.length > 0) {
|
||||
logCursor = lines[lines.length - 1].id;
|
||||
send("logs", lines);
|
||||
}
|
||||
}
|
||||
if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n");
|
||||
await sleep(INTERVAL_MS, signal);
|
||||
}
|
||||
} catch {
|
||||
// client went away or the stream was closed
|
||||
} finally {
|
||||
try {
|
||||
controller.close();
|
||||
} catch {}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
async function buildSnapshot(modelId: string | null, jobId: string | null) {
|
||||
const worker = await getWorkerStatus();
|
||||
if (jobId) {
|
||||
const job = await getJob(jobId);
|
||||
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
|
||||
}
|
||||
if (modelId) {
|
||||
const jobs = await listModelJobs(modelId);
|
||||
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
|
||||
return { worker, jobs, files };
|
||||
}
|
||||
return { worker, jobs: await listLiveJobs(), files: [] };
|
||||
}
|
||||
|
||||
function sleep(ms: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const t = setTimeout(resolve, ms);
|
||||
signal.addEventListener("abort", () => {
|
||||
clearTimeout(t);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { reservedBytes } from "@/lib/agent-downloads";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { getGuardrails } from "@/lib/settings";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Space on the models folder (reported by the worker every few seconds), what open downloads
|
||||
* still need, and how much an agent request may use before hitting the minimum-free guardrail.
|
||||
*/
|
||||
export const GET = withToken("models:read", async () => {
|
||||
try {
|
||||
const [w, reserved, g] = await Promise.all([getWorkerStatus(), reservedBytes(), getGuardrails()]);
|
||||
const free = w.online ? w.modelsDirFreeBytes : null;
|
||||
const total = w.online ? w.modelsDirTotalBytes : null;
|
||||
const available = free == null ? null : Math.max(0, free - reserved - g.minFreeBytes);
|
||||
return v1Json({
|
||||
workerOnline: w.online,
|
||||
freeBytes: free,
|
||||
totalBytes: total,
|
||||
usedBytes: free != null && total != null ? total - free : null,
|
||||
reservedBytes: reserved,
|
||||
minFreeBytes: g.minFreeBytes,
|
||||
availableForRequestsBytes: available,
|
||||
free: size(free),
|
||||
total: size(total),
|
||||
availableForRequests: size(available),
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { z } from "zod";
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { requestDownload } from "@/lib/agent-downloads";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const Body = z
|
||||
.object({
|
||||
repoId: z.string().trim().regex(REPO_ID_RE, 'must be "org/name"'),
|
||||
sha: z.string().trim().regex(SHA_RE, "must be the full 40-character commit SHA from GET /api/v1/hub/lookup"),
|
||||
revision: z.string().trim().min(1).max(255).optional(),
|
||||
quant: z.string().trim().min(1).max(64).optional(),
|
||||
include: z.array(z.string().trim().min(1).max(1024)).min(1).max(100).optional(),
|
||||
tags: z.array(z.string()).max(20).optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine((b) => !!b.quant !== !!b.include, { message: 'pass exactly one of "quant" (e.g. "Q4_K_M") or "include" (globs)' });
|
||||
|
||||
/**
|
||||
* Request a download, within the guardrails. 201: queued or waiting for approval; 200: the same
|
||||
* repo + commit + files was requested before, nothing new was queued.
|
||||
*/
|
||||
export const POST = withToken("downloads:create", async (req, { token }) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
const r = await act(token, "download.request", { type: "model" }, async () => {
|
||||
const out = await requestDownload(token, body);
|
||||
return { ...out, id: out.modelId };
|
||||
});
|
||||
return v1Json(
|
||||
{
|
||||
created: r.created,
|
||||
modelId: r.modelId,
|
||||
jobId: r.jobId,
|
||||
state: r.state,
|
||||
requestedBytes: r.requestedBytes,
|
||||
requestedSize: size(r.requestedBytes),
|
||||
files: r.files,
|
||||
message: r.message.replace("{jobId}", r.jobId ?? "{jobId}"),
|
||||
},
|
||||
r.created ? 201 : 200,
|
||||
);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { quantSummary } from "@/lib/agent-selection";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models } from "@/lib/db/schema";
|
||||
import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Files listed inline up to this count; more with ?files=all. */
|
||||
const FILE_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* Resolve a Hub repo (+ revision, default main) to its commit SHA, with the quants and files and
|
||||
* their sizes: what a download request needs. The same lookup the Add model dialog uses.
|
||||
*/
|
||||
export const GET = withToken("models:read", async (req) => {
|
||||
try {
|
||||
const url = new URL(req.url);
|
||||
const repo = url.searchParams.get("repo")?.trim();
|
||||
if (!repo) return v1Error(400, "invalid_request", 'Pass the repo as ?repo=org/name, e.g. ?repo=unsloth/Qwen3-8B-GGUF.');
|
||||
const { repoId, revision: urlRevision } = normalizeRepoInput(repo);
|
||||
const revision = url.searchParams.get("revision")?.trim() || urlRevision || "main";
|
||||
const r = await lookupRepo(repoId, revision);
|
||||
const all = url.searchParams.get("files") === "all";
|
||||
const model = r.existingModelId
|
||||
? await db().query.models.findFirst({ columns: { id: true, pinnedSha: true, status: true }, where: eq(models.id, r.existingModelId) })
|
||||
: null;
|
||||
return v1Json({
|
||||
repoId: r.repoId,
|
||||
revision: r.revision,
|
||||
sha: r.sha,
|
||||
gated: r.gated,
|
||||
lastModified: r.lastModified,
|
||||
inLibrary: model ? { modelId: model.id, pinnedSha: model.pinnedSha, status: model.status } : null,
|
||||
quants: quantSummary(r.files).map((q) => ({ ...q, size: size(q.bytes) })),
|
||||
fileCount: r.files.length,
|
||||
totalBytes: r.files.reduce((s, f) => s + f.size, 0),
|
||||
files: (all ? r.files : r.files.slice(0, FILE_LIMIT)).map((f) => ({ path: f.path, bytes: f.size })),
|
||||
filesTruncated: !all && r.files.length > FILE_LIMIT,
|
||||
next: 'POST /api/v1/downloads with {"repoId", "sha", "quant"} (or "include": [globs]).',
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { cancelOwnJob } from "@/lib/agent-downloads";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Cancel a job this token requested (a pending request is withdrawn). Other jobs are the user's. */
|
||||
export const POST = withToken<RouteContext<"/api/v1/jobs/[id]/cancel">>(["downloads:create", "models:verify"], async (_req, { params, token }) => {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const r = await act(token, "job.cancel", { type: "job", id }, () => cancelOwnJob(token, id));
|
||||
return v1Json(r, 202);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { getJob, listJobFiles, listJobLogs } from "@/lib/jobs";
|
||||
import { parseWait, waitFor } from "@/lib/wait";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const MAX_LOG = 200;
|
||||
|
||||
const NEXT: Record<string, string> = {
|
||||
pending_approval: "Waiting for the user to approve it. Don't retry or poll; tell the user and stop.",
|
||||
queued: "Waiting for a free slot; GET with ?wait=900 instead of polling.",
|
||||
downloading: "Downloading; GET with ?wait=900 instead of polling.",
|
||||
verifying: "Checking the files; GET with ?wait=900 instead of polling.",
|
||||
completed: "Done.",
|
||||
failed: "Failed; see error. Tell the user; retrying the same request returns this job.",
|
||||
cancelled: "Cancelled or rejected. Don't request it again unless the user asks.",
|
||||
interrupted: "Interrupted by a Kaname restart; the user can resume it.",
|
||||
};
|
||||
|
||||
const SETTLED = new Set(["pending_approval", "completed", "failed", "cancelled", "interrupted"]);
|
||||
|
||||
/** What a finished verify found, and what to do about it. */
|
||||
function verifyResult(job: NonNullable<Awaited<ReturnType<typeof getJob>>>) {
|
||||
if ((job.kind !== "verify" && job.kind !== "deep_verify") || job.state !== "completed" || !job.result) return undefined;
|
||||
const r = job.result;
|
||||
const problems = (r.missing?.length ?? 0) + (r.sizeMismatch?.length ?? 0) + (r.hashMismatch?.length ?? 0);
|
||||
return {
|
||||
checked: r.checked ?? null,
|
||||
missing: r.missing ?? [],
|
||||
sizeMismatch: r.sizeMismatch ?? [],
|
||||
hashMismatch: r.hashMismatch ?? [],
|
||||
ok: problems === 0,
|
||||
next: problems === 0 ? "All files are fine." : `POST /api/v1/models/${job.modelId}/repair downloads the ${problems} broken file(s) again.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Job state with per-file progress. ?wait=<s> (max 900) blocks until it is finished or waits for
|
||||
* approval. The hf log only with ?log=N (last N lines, max 200).
|
||||
*/
|
||||
export const GET = withToken<RouteContext<"/api/v1/jobs/[id]">>("models:read", async (req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const q = new URL(req.url).searchParams;
|
||||
const { value: job, waitedS, timedOut } = await waitFor(() => getJob(id), (j) => !j || SETTLED.has(j.state), parseWait(q), { signal: req.signal });
|
||||
if (!job) return v1Error(404, "not_found", "No job with this id.");
|
||||
const n = Math.min(MAX_LOG, Math.max(0, Number(q.get("log")) || 0));
|
||||
const files = await listJobFiles(id);
|
||||
const log = n > 0 ? (await listJobLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined;
|
||||
const verify = verifyResult(job);
|
||||
return v1Json({
|
||||
id: job.id,
|
||||
modelId: job.modelId,
|
||||
repoId: job.repoId,
|
||||
kind: job.kind,
|
||||
purpose: job.purpose,
|
||||
state: job.state,
|
||||
cancelRequested: job.cancelRequested,
|
||||
requestedBy: job.requestedBy,
|
||||
progress: {
|
||||
doneBytes: job.doneBytes,
|
||||
totalBytes: job.totalBytes,
|
||||
percent: job.totalBytes > 0 ? Math.round((job.doneBytes / job.totalBytes) * 1000) / 10 : 0,
|
||||
done: size(job.doneBytes),
|
||||
total: size(job.totalBytes),
|
||||
speedBytesPerSecond: job.speedBps,
|
||||
etaSeconds: job.etaSeconds,
|
||||
},
|
||||
error: job.errorCode || job.errorMessage ? { code: job.errorCode, message: job.errorMessage } : null,
|
||||
...(verify ? { verify } : {}),
|
||||
files: files.map((f) => ({ path: f.path, state: f.state, doneBytes: f.doneBytes, totalBytes: f.expectedBytes })),
|
||||
createdAt: new Date(job.createdAt).toISOString(),
|
||||
startedAt: job.startedAt ? new Date(job.startedAt).toISOString() : null,
|
||||
finishedAt: job.finishedAt ? new Date(job.finishedAt).toISOString() : null,
|
||||
next: verify?.next ?? NEXT[job.state] ?? null,
|
||||
...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}),
|
||||
...(log ? { log } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { requestRepair } from "@/lib/agent-downloads";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Download again the selected files that are missing or broken, within the guardrails (and, by
|
||||
* default, after the user approves it). Run verify first to find out what's broken.
|
||||
*/
|
||||
export const POST = withToken<RouteContext<"/api/v1/models/[id]/repair">>("downloads:create", async (_req, { params, token }) => {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const r = await act(token, "model.repair", { type: "model", id }, () => requestRepair(token, id));
|
||||
return v1Json({ ...r, requestedSize: size(r.requestedBytes), message: r.message.replace("{jobId}", r.jobId) }, 201);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
import { getModel } from "@/lib/library";
|
||||
import { modelTagList } from "@/lib/tags";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** One model: status, pinned commit, selected files with their state, tags and its latest job. */
|
||||
export const GET = withToken<RouteContext<"/api/v1/models/[id]">>("models:read", async (_req, { params }) => {
|
||||
try {
|
||||
const data = await getModel((await params).id);
|
||||
if (!data) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models.");
|
||||
const { model, files } = data;
|
||||
const selected = files.filter((f) => f.selected);
|
||||
const onDisk = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
|
||||
const [[job], tags] = await Promise.all([listModelJobs(model.id, 1), modelTagList(model.id)]);
|
||||
return v1Json({
|
||||
id: model.id,
|
||||
repoId: model.repoId,
|
||||
source: model.source,
|
||||
status: model.status,
|
||||
trackedRevision: model.source === "local" ? null : model.trackedRevision,
|
||||
pinnedSha: model.source === "local" ? null : model.pinnedSha,
|
||||
hubState: model.hubState,
|
||||
localPath: model.localPath,
|
||||
requestedBy: model.requestedBy,
|
||||
tags: tags.map((t) => t.name),
|
||||
onDiskBytes: onDisk,
|
||||
onDisk: size(onDisk),
|
||||
files: selected.map((f) => ({ path: f.path, bytes: f.size, state: f.state })),
|
||||
latestJob: job ? { id: job.id, kind: job.kind, purpose: job.purpose, state: job.state, requestedBy: job.requestedBy } : null,
|
||||
lastVerifiedAt: model.lastVerifiedAt?.toISOString() ?? null,
|
||||
createdAt: model.createdAt.toISOString(),
|
||||
downloadedAt: model.downloadedAt?.toISOString() ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { getModel } from "@/lib/library";
|
||||
import { modelTagList, normalizeTagName, removeTag } from "@/lib/tags";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Detach a tag (by name, case-insensitive) from a model. The tag itself stays. */
|
||||
export const DELETE = withToken<RouteContext<"/api/v1/models/[id]/tags/[name]">>("tags:write", async (_req, { params, token }) => {
|
||||
try {
|
||||
const { id, name } = await params;
|
||||
if (!(await getModel(id))) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models.");
|
||||
const { slug } = normalizeTagName(decodeURIComponent(name));
|
||||
const tag = (await modelTagList(id)).find((t) => t.name.toLowerCase() === slug);
|
||||
if (!tag) return v1Error(404, "not_found", `This model has no tag "${decodeURIComponent(name)}".`);
|
||||
await act(token, "tag.remove", { type: "model", id }, async () => {
|
||||
await removeTag(id, tag.id);
|
||||
return { id };
|
||||
});
|
||||
return v1Json({ modelId: id, removed: tag.name, tags: (await modelTagList(id)).map((t) => t.name) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from "zod";
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { addTag, modelTagList } from "@/lib/tags";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const Body = z.object({ name: z.string() }).strict();
|
||||
|
||||
/** Attach a tag to a model; a tag that doesn't exist yet is created (names match case-insensitively). */
|
||||
export const POST = withToken<RouteContext<"/api/v1/models/[id]/tags">>("tags:write", async (req, { params, token }) => {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const { name } = Body.parse(await req.json());
|
||||
const tag = await act(token, "tag.add", { type: "model", id }, () => addTag(id, name));
|
||||
return v1Json({ modelId: id, tag: tag.name, tags: (await modelTagList(id)).map((t) => t.name) }, 201);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from "zod";
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { requestVerify } from "@/lib/agent-downloads";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { optionalJson, v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const Body = z.object({ deep: z.boolean().optional() }).strict();
|
||||
|
||||
/** Check the model's selected files: presence and size, or with {"deep": true} their hashes. */
|
||||
export const POST = withToken<RouteContext<"/api/v1/models/[id]/verify">>("models:verify", async (req, { params, token }) => {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const { deep = false } = Body.parse(await optionalJson(req));
|
||||
const r = await act(token, deep ? "model.deep_verify" : "model.verify", { type: "model", id }, () => requestVerify(token, id, deep));
|
||||
return v1Json(r, 201);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { parseModelFilters } from "@/lib/api-v1-filters";
|
||||
import { size, v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { listLibrary } from "@/lib/library";
|
||||
import { matchesFilters, matchesQuery, type SearchableModel } from "@/lib/search";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* The local library, filtered like the library page: ?q= (all terms must match) and facets
|
||||
* author, family, quant, tag, status, requested_by (repeat or comma-separate values).
|
||||
* Status values: pending, downloading, ready, incomplete, failed, deleting, pending_approval,
|
||||
* update_available, repo_missing, commit_missing.
|
||||
*/
|
||||
export const GET = withToken("models:read", async (req) => {
|
||||
try {
|
||||
const { query, filters } = parseModelFilters(new URL(req.url).searchParams);
|
||||
const rows = await listLibrary();
|
||||
const out = rows
|
||||
.filter((r) => {
|
||||
const m: SearchableModel = {
|
||||
repoId: r.repoId,
|
||||
author: r.author,
|
||||
families: r.families,
|
||||
baseModels: r.baseModels,
|
||||
architecture: r.architecture,
|
||||
quants: r.quants,
|
||||
tags: r.tags.map((t) => t.name),
|
||||
hubTags: r.hubTags,
|
||||
pipelineTag: r.pipelineTag,
|
||||
license: r.license,
|
||||
status: r.status,
|
||||
hubStatus: r.hubState && r.hubState !== "available" ? r.hubState : r.updateAvailable ? "update_available" : null,
|
||||
requestedBy: r.requestedBy,
|
||||
pendingApproval: r.pendingApproval,
|
||||
};
|
||||
return matchesQuery(m, query) && matchesFilters(m, filters);
|
||||
})
|
||||
.map((r) => ({
|
||||
id: r.id,
|
||||
repoId: r.repoId,
|
||||
source: r.source,
|
||||
status: r.status,
|
||||
pendingApproval: r.pendingApproval,
|
||||
pinnedSha: r.source === "local" ? null : r.pinnedSha,
|
||||
quants: r.quants,
|
||||
tags: r.tags.map((t) => t.name),
|
||||
selectedFiles: r.fileCount,
|
||||
selectedBytes: r.totalBytes,
|
||||
onDiskBytes: r.presentBytes,
|
||||
onDisk: size(r.presentBytes),
|
||||
updateAvailable: r.updateAvailable,
|
||||
hubState: r.hubState,
|
||||
requestedBy: r.requestedBy,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
downloadedAt: r.downloadedAt?.toISOString() ?? null,
|
||||
}));
|
||||
return v1Json({ count: out.length, models: out });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Json } from "@/lib/api-v1";
|
||||
import { getGuardrails } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Who am I, what may I do, and within which limits. Any valid token. */
|
||||
export const GET = withToken(null, async (_req, { token }) => {
|
||||
const g = await getGuardrails();
|
||||
return v1Json({
|
||||
token: { name: token.name, scopes: token.scopes },
|
||||
guardrails: {
|
||||
approvalMode: g.approvalMode,
|
||||
maxRequestBytes: g.maxRequestBytes,
|
||||
maxRequestSize: size(g.maxRequestBytes),
|
||||
minFreeBytes: g.minFreeBytes,
|
||||
minFreeSize: size(g.minFreeBytes),
|
||||
maxOpenAgentJobs: g.maxOpenJobs,
|
||||
allowedAuthors: g.allowedAuthors,
|
||||
},
|
||||
endpoints: [
|
||||
"GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all] models:read",
|
||||
"GET /api/v1/models[?q=&author=&family=&quant=&tag=&status=&requested_by=] models:read",
|
||||
"GET /api/v1/models/{id} models:read",
|
||||
"GET /api/v1/tags models:read",
|
||||
"GET /api/v1/jobs/{id}[?wait=900][&log=50] models:read",
|
||||
"GET /api/v1/disk models:read",
|
||||
"POST /api/v1/downloads {repoId, sha, quant | include[], tags?, revision?} downloads:create",
|
||||
"POST /api/v1/models/{id}/repair downloads:create",
|
||||
"POST /api/v1/models/{id}/verify {deep?} models:verify",
|
||||
"POST /api/v1/jobs/{id}/cancel (jobs of this token only) downloads:create | models:verify",
|
||||
"POST /api/v1/models/{id}/tags {name} tags:write",
|
||||
"DELETE /api/v1/models/{id}/tags/{name} tags:write",
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { listTags } from "@/lib/tags";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Every tag with how many models use it, so an agent reuses existing tags instead of inventing near-duplicates. */
|
||||
export const GET = withToken("models:read", async () => {
|
||||
try {
|
||||
const tags = await listTags();
|
||||
return v1Json({ count: tags.length, tags: tags.map((t) => ({ name: t.name, models: Number(t.count) })) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#7c5cff"/>
|
||||
<stop offset="1" stop-color="#14b8a6"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="14" fill="url(#g)"/>
|
||||
<text x="32" y="45" text-anchor="middle" font-size="38" font-weight="700" fill="#fff"
|
||||
font-family="'Yu Gothic','Meiryo','Noto Sans JP','Hiragino Sans',sans-serif">要</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 497 B |
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { BotIcon, CheckIcon, XIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { approveJob, rejectJob } from "@/components/job-actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
|
||||
const WHAT: Record<string, string> = {
|
||||
add: " of additional files",
|
||||
repair: " to repair missing or broken files",
|
||||
};
|
||||
|
||||
/** A download requested through the API that waits for approval: who asked, how much, approve/reject. */
|
||||
export function ApprovalBar({ job, onRemoved }: { job: { id: string; requestedBy: string | null; totalBytes: number; purpose: string | null }; onRemoved?: () => void }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function run(fn: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2.5 text-sm">
|
||||
<p className="flex items-center gap-1.5">
|
||||
<BotIcon className="size-4 shrink-0 text-amber-700 dark:text-amber-300" />
|
||||
<span>
|
||||
<strong>{job.requestedBy ?? "An API token"}</strong> asks to download {job.purpose === "repair" ? "up to " : ""}
|
||||
{formatBytes(job.totalBytes)}
|
||||
{WHAT[job.purpose ?? ""] ?? ""}. It starts once you approve it.
|
||||
</span>
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => approveJob(job.id))}>
|
||||
<CheckIcon />
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
run(async () => {
|
||||
const r = await rejectJob(job.id);
|
||||
if (r?.removedModel) onRemoved?.();
|
||||
})
|
||||
}
|
||||
>
|
||||
<XIcon />
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
"use client";
|
||||
|
||||
import { Dialog } from "@base-ui/react/dialog";
|
||||
import {
|
||||
BotIcon,
|
||||
BoxIcon,
|
||||
CornerDownLeftIcon,
|
||||
DownloadIcon,
|
||||
GaugeIcon,
|
||||
LibraryIcon,
|
||||
MonitorIcon,
|
||||
MoonIcon,
|
||||
PaletteIcon,
|
||||
PlusIcon,
|
||||
ScanSearchIcon,
|
||||
SearchIcon,
|
||||
ServerIcon,
|
||||
SunIcon,
|
||||
TagIcon,
|
||||
TagsIcon,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Index = {
|
||||
models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[];
|
||||
endpoints: { id: string; name: string; model: string | null; engine: string | null }[];
|
||||
benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[];
|
||||
tags: string[];
|
||||
};
|
||||
|
||||
type Item = {
|
||||
id: string;
|
||||
group: string;
|
||||
title: string;
|
||||
hint?: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
/** Extra words that match (not shown). */
|
||||
keywords?: string;
|
||||
run: () => void;
|
||||
};
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { run: "speed run", ab: "A/B", eval: "quality eval" };
|
||||
|
||||
/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */
|
||||
function score(item: Item, terms: string[]): number {
|
||||
if (terms.length === 0) return 1;
|
||||
const title = item.title.toLowerCase();
|
||||
const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase();
|
||||
let s = 0;
|
||||
for (const t of terms) {
|
||||
const i = all.indexOf(t);
|
||||
if (i < 0) return 0;
|
||||
s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** The palette itself: loaded on first use (see command-palette.tsx), then kept mounted. */
|
||||
export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen: (open: boolean) => void }) {
|
||||
const router = useRouter();
|
||||
const { setTheme } = useTheme();
|
||||
const [query, setQuery] = useState("");
|
||||
const [index, setIndex] = useState<Index | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const list = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Fresh data every time it opens (the library changes while you use it).
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let stop = false;
|
||||
void fetch("/api/search-index", { cache: "no-store" })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((d: Index | null) => !stop && d && setIndex(d));
|
||||
return () => {
|
||||
stop = true;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const go = (href: string) => () => {
|
||||
setOpen(false);
|
||||
router.push(href);
|
||||
};
|
||||
|
||||
const items = useMemo<Item[]>(() => {
|
||||
const out: Item[] = [
|
||||
{ id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") },
|
||||
{ id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") },
|
||||
{ id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") },
|
||||
{ id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") },
|
||||
{ id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") },
|
||||
{ id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") },
|
||||
{ id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) },
|
||||
{ id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) },
|
||||
{ id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) },
|
||||
{ id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") },
|
||||
{ id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") },
|
||||
{ id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") },
|
||||
{ id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") },
|
||||
{ id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") },
|
||||
{ id: "s:tokens", group: "Settings", title: "API tokens", icon: BotIcon, keywords: "agent api token guardrails approval bearer", run: go("/settings/api-tokens") },
|
||||
{ id: "s:backdrop", group: "Settings", title: "Background picture", icon: PaletteIcon, hint: "Appearance", keywords: "image upload dot matrix painting header wallpaper", run: go("/settings/appearance") },
|
||||
];
|
||||
for (const m of index?.models ?? []) {
|
||||
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
|
||||
}
|
||||
for (const e of index?.endpoints ?? []) {
|
||||
out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) });
|
||||
}
|
||||
for (const b of index?.benchmarks ?? []) {
|
||||
out.push({
|
||||
id: `b:${b.id}`,
|
||||
group: "Benchmarks",
|
||||
title: b.label ?? `${b.target} · ${b.model}`,
|
||||
hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`,
|
||||
icon: GaugeIcon,
|
||||
keywords: `${b.target} ${b.model}`,
|
||||
run: go(`/benchmarks/${b.id}`),
|
||||
});
|
||||
}
|
||||
for (const t of index?.tags ?? []) {
|
||||
out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) });
|
||||
}
|
||||
return out;
|
||||
// `go` only closes over router and setOpen (the shell's state setter), which are stable.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [index, setTheme]);
|
||||
|
||||
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const groups = useMemo(() => {
|
||||
const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0);
|
||||
const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"];
|
||||
// Without a query: pages, actions and settings, plus the newest few of the rest.
|
||||
const per = terms.length ? 8 : 4;
|
||||
return order
|
||||
.map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) }))
|
||||
.filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g)));
|
||||
// terms is derived from query
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [items, query]);
|
||||
const flat = groups.flatMap((g) => g.rows);
|
||||
const current = Math.min(active, Math.max(0, flat.length - 1));
|
||||
|
||||
useEffect(() => {
|
||||
list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" });
|
||||
}, [current]);
|
||||
|
||||
function onKeyDown(e: React.KeyboardEvent) {
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setActive((current + 1) % Math.max(1, flat.length));
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setActive((current - 1 + flat.length) % Math.max(1, flat.length));
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
flat[current]?.run();
|
||||
}
|
||||
}
|
||||
|
||||
let n = -1;
|
||||
return (
|
||||
<Dialog.Root
|
||||
open={open}
|
||||
onOpenChange={(o) => {
|
||||
setOpen(o);
|
||||
if (!o) {
|
||||
setQuery("");
|
||||
setActive(0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
|
||||
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
|
||||
<Dialog.Title className="sr-only">Search</Dialog.Title>
|
||||
<div className="flex items-center gap-2 border-b px-4">
|
||||
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setActive(0);
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Search models, endpoints, benchmarks, settings…"
|
||||
className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
|
||||
aria-label="Search"
|
||||
/>
|
||||
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
|
||||
</div>
|
||||
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
|
||||
{flat.length === 0 ? (
|
||||
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
|
||||
) : (
|
||||
groups.map(({ g, rows }) => (
|
||||
<div key={g} className="mb-1">
|
||||
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
|
||||
{rows.map((it) => {
|
||||
n++;
|
||||
const i = n;
|
||||
return (
|
||||
<button
|
||||
key={it.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === current}
|
||||
data-index={i}
|
||||
onMouseMove={() => setActive(i)}
|
||||
onClick={it.run}
|
||||
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
|
||||
>
|
||||
<it.icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate">{it.title}</span>
|
||||
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
|
||||
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Dialog.Popup>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// The dialog (base-ui Dialog, all items and icons) is its own chunk, kept out of every page's first
|
||||
// load: most page views never open it. It starts loading when you reach for it (hovering or focusing
|
||||
// the Search button, pressing ⌘ or Ctrl) and renders on the first open.
|
||||
const loadDialog = () => import("./command-palette-dialog");
|
||||
const CommandPaletteDialog = dynamic(() => loadDialog().then((m) => m.CommandPaletteDialog), { ssr: false });
|
||||
const preload = () => void loadDialog();
|
||||
|
||||
const OPEN_EVENT = "kaname:command-palette";
|
||||
|
||||
/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */
|
||||
export function CommandPalette() {
|
||||
const [open, setOpen] = useState(false);
|
||||
// Mounted from the first open on, so it keeps its state like before.
|
||||
const [used, setUsed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Meta" || e.key === "Control") preload();
|
||||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
|
||||
e.preventDefault();
|
||||
setUsed(true);
|
||||
setOpen((o) => !o);
|
||||
}
|
||||
};
|
||||
const onOpen = () => {
|
||||
setUsed(true);
|
||||
setOpen(true);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
window.addEventListener(OPEN_EVENT, onOpen);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
window.removeEventListener(OPEN_EVENT, onOpen);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return used ? <CommandPaletteDialog open={open} setOpen={setOpen} /> : null;
|
||||
}
|
||||
|
||||
const isMac = () => /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent);
|
||||
const noSubscribe = () => () => {};
|
||||
|
||||
/** The menu button that opens the palette, showing its shortcut. */
|
||||
export function CommandPaletteButton({ className }: { className?: string }) {
|
||||
const mac = useSyncExternalStore(noSubscribe, isMac, () => false);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.dispatchEvent(new Event(OPEN_EVENT))}
|
||||
onPointerEnter={preload}
|
||||
onFocus={preload}
|
||||
className={cn("flex h-8 items-center gap-2 rounded-lg px-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground", className)}
|
||||
aria-label="Search"
|
||||
>
|
||||
<SearchIcon className="size-4" />
|
||||
<span className="hidden lg:inline">Search</span>
|
||||
<kbd className="hidden rounded-full border border-foreground/15 px-2 font-sans text-[10px] leading-4 lg:inline">{mac ? "⌘K" : "Ctrl K"}</kbd>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Michelangelo, "The Creation of Adam" (c. 1512, public domain; Wikimedia Commons, cropped), as a
|
||||
// 240×109 grid of brightness levels 0–f, contrast-stretched. Generated once; the photo isn't shipped.
|
||||
|
||||
export const ADAM_W = 240;
|
||||
export const ADAM_H = 109;
|
||||
export const ADAM_DOTS = [
|
||||
"c9dca910bbcdddddcedddcbcbdccccbbbbaccbbbcbccaccddcccccdddccdddbceddcbcccbdedeacbbbccaabcb7a898899899babadeacdcbbcdcccbabdbcbbcbbbaccccdddeeeeecdcddcddccccddcccdcdcccccccccdddcdddcbddccccbbccccbbbbbccbbbbbcbbbbbcbbccbbbbbaabaabbbddb3972248aa",
|
||||
"cdccdbc9dbdcdcdceddddcbbbbdcdcccccbabccccccbcbbccbbcccddcddcddddeedbbcdeecccdcddddcccbcccdcbdcccccbddccccccccdcccccddddddddcdddddccccdddddeddddeedddcccdeedcdcdeccccbbbbbcbcccabccdbddcbbbbbabccb9999998999899abbcbbbbbbbbababaccbbcceb375039bd9",
|
||||
"ccbccdabcdddcddbdccbddccdccccbbcccccccbbbcbccbcccbcbddccddcddccedddccdccddccccbdccdcccccedccccccccdedccccccbdccccddccdcddcddddddccccccdddddddcddddcdddddcbbcccccccbbcbbbbbbbba98776566677666666776665467998999a9a9aabaabbbaaaabbaaaccea2726cbbcc",
|
||||
"ecccdddcdcedcddccddcdccbbcccccbbbbbbbbabbcbbbbccccccdcddcbdddddddeeeabddcdcccbcccccbcdbcccdcddcccccdcecddcccbccccddbcccdcdddddccdcbcccddccccccdcdccdddccccccbcbcbbbcbbaa7655667755657766666655566656667788757676999999abbbabaabcabaccea23abbbbbc",
|
||||
"cfdcbccbccddcdcdeddcddddccbcccccccbbbbccccbaccdddddddcccccccdddeeffefdccdcccdcccccccbcccddcccdcccbcdacdddccbcccccdcdbccccfdddddcccccddddcdcdddcdcccdddbcccbcbbbbba865576676555454333243443444343332445666777788879999999bcbbcbbababebf80bbbaabbb",
|
||||
"cbcbceccddddddddddccddcdddcccbbcdccbbccdcccccbcccccddcdcddddcddeeffebeddcdccbdddcccccccccccccccccdbbbdcccccbccccbcbbdccccdddddddcddbdddcdcddddccccddcbcbbccbd865556676533333333321222221110001012223443334577777989999aacbbbcbbb9ab97127baaabaab",
|
||||
"eeedcddcdceddddddecccccceddddccbbbcc7bbccccccdbccccdcddddddeeffeddbddddecdcccdccccccbcdcccccccbccdddcddccbcccccccddcdbdddddcddddcdccccccbcdddcddccccccbbbc86435665532222222322222121110110000101000002345554335667898abcbbbbb999aa67212221349aab",
|
||||
"bccbddeeeeeeddeeceedcddddccedccdcdcacdccdccccdddccceededdddeeddedee9dedddcccdcccdcddddddcddcddddddddccccccccdcbccbccdddcdddddccdddddedcdddcdddddccdcccc96765476310000012222111110111110221221000000000011224565445778a9999988899879922211221248a",
|
||||
"bccccdedddeebeeddeeddcddddcddcddddc8ccccdddddccdccdeeedddcddeddcddebedecbddccdcedddddddccdddcceddccadcdccccbbccbbcbbdcddceeedddccddcdcdcccdddcddccdca8765558512200000122110111111112010001111110000000000000224543556689a98999a5778731222232347b",
|
||||
"bdceeddeaddeeedeeeddddddedeeeeecdccbccccdeebccddddedddeeeedeffeddefeedeedcbcccdcceddddcdddcdddcedccabccbccccbccbccccddddddddcdddddcdcbdcccccbccccbb666657852023223422211100001100110121111001111100101001000001334334567a9899b56678713022122558a",
|
||||
"bccdedecdddddeeeedcddeeeeeedddddccdbddcdccdcddeddcdeccdeeecddedddddfededccdccdcbdccdddddcdddccccccddbccccccbccccbcccbdedddddddcdccccccdddcdcdcbbb766567841112352452412101110001221222121121000000111232222100100224343556a9aa45677742221113557aa",
|
||||
"accddcddedddeeeeeecbceddcddeecddcdaccdcccdcdddcedefdcdddeeedcddcccdeddedecbdcbdcddddeeeeedddddcccddcdccccbcccccccddcededddcdccccdccddccbcccdcbb976579952111067544334323120001110000000001000000013444321001200011014543367aba36676222265123569aa",
|
||||
"bcbcdcddedddedddeeddefdeeeeeedddddcccccdccccddccddddddddedccdddcd9cddddeccdccccdddcdddccddccddddccedcccbcbbccbccccccdddddedcbccdccdcccbccccbca7786a973312211585665243212000345655410455655500010166574321101000001112442258a44676213342133a9b9a9",
|
||||
"9abbabacdcdcdddedddcdedddcccddddccbbccdccccdccddeedddeeeeeddddddcbdeddcbccbbdccddcddcccccccdcdddcdccccccccccdddccccdcdeedddddccccddddccccbb99baa998332213434466a74445433134556555365665343352110457675431110000000110244416a3566312221112112337a",
|
||||
"cba9aabdacabbbbbccaabccccbdcdddddcdcccecccccddcdccdddddeeedeeeeedeeedccccccbccccdbddddddcdcddcccccdcccdccccbdcdddccbdeeedddddcdddcdddbcc9bb88a77763132114544353975542230345666425655655242220100245865442220000100011122351435742232001111212335",
|
||||
"a8aabbba9bbdccbcbaadccaabacddddddaddddddcdddeddddcdcdddedeedeefddeddeddddddcdcdddccdddeddddddccccbecdddddddddddddccceddddedcccddbdddbcc8a8888666621112125754465986654463357676655545433972021000265343422110000110011211103225631221111111211134",
|
||||
"cab8bdbbbacabbbbbb9bccabbacddddedaeedddcdecdddedddddeeeeeeeddddd8eeeddeddddccdddddddddddcdccccccdbbdcddcddcdddedededdcdeecdeddcdbcccca9a8688b865642034113455475656a655554589777676449aaa93315302255442112111000000001111221235422112111100101123",
|
||||
"89aabbbaaa9bcaabbcbcbbcdccddcdeedbdddeeedeeeeeddddeeefeeffeeeeffeeffeeedddddddddddddddddddddddccdadcccdccdcdddddeebddddddddcdccccdddb987788ba74622143310023544477aa74445348b9a86654287885210432254543323211000000000112442a236322112111111011135",
|
||||
"99aa99babaaaa9acbbbbbbcabbabcddddeededeeedeeedddecdeeddeeefeefffeeefffeedddeedddddccdcddddddcdcdcbccdddcdddeeeddedcdddeedcccdccdcdcb8789c7dba8555434322202455448788655554579ba8654367bc8423312023532222111100000111102653021342222222101011113ab",
|
||||
"a99989aacbbaaabcccdbbccbbbbbdcdddcdedeeeffefdddddcdeeeeeefdeffffeffeeeddddcdddddddddddcdcddcccdddcedcdddddeeeeedcdcddeeecdddddccdcc8aada799ba6636542111011335443555555554669aa75343299a8542221132534431122101000000002551121521224442221100029ab",
|
||||
"9889999aaaabbaabccbbbcbbcbabbeeddededdefeeeeeedddcdedeeeefeeeefffeeeefeddddeddddedcdddddedddddcddcccdcdddeededdddedbdeeedcccdecc8a799dc696451521222322110112353264544743457887589ba329a4333112012333331232100111000001532211223532222112221136bb",
|
||||
"9abbba89bbbbababbcccbaccaccbbaccdededdddeeeeeeddeeeeeefeeeeeeeeeedeeeddcdddcdddcdddddddddddcddcdeccddeddeeddeeeeddeeffedddddcddda8a86d8aa552237322231122111138a9879bba99a8cbaba78776235443420100123322233223211110000025532245311124554566656337",
|
||||
"aaabccbbbccddccccccccdcbcccccdddddddeeeffeefeeededdddeefeeeedeeddeeeeeddccdddddedddddddbcccddcedeeeddefeeeedddeeeeededcdcdeeedda8a887adbc857562633320001127689aba8988999a998a98887666a4468432154011114544352321010000001364441124441111112111263",
|
||||
"bcccabcbddddddddddccecdccecdcdbcddedeeeefffffdeeeeeeeeeedcdefdeeddedecddddddbddddeeeeddddcdddddedeedeeeeeeedeeeeeedeeeeeddeddca8984773c763544372233342014317bccedcdcaa99998889888865ad3396332040533104455566632210000000021112620011000131010226",
|
||||
"cdcdcdeeeddeeefddcddedeeeeddfaeedddddeeedffffeeeedddeddddddcdddedddddddccbddccddedeeddddceeeedcffdeeeeeedcdfeeeeeededeeededdcc976535447e539556297553433223699dbdeffeda98988778878764ad3454340313543232533556533211000000000000012322221101052123",
|
||||
"adeeeddeedefdeffeeefeefffeeedddeeededdddedeeeefdedddddddddeeddeeeeddededdddddedddedededddedddedeeedeeeeedeedeeeddeeefeeeedecd978433995636884488785543434533b79deffffca88887777765321014344433335574333325555543211000000000101101111211100011631",
|
||||
"bdddeefedfeffeeeedddfedfeeedeedeeedeffeeddeeedddddddbcddddddedcddeddddccdddddddddedeeddeddddddedfdeeefeedeeefeededcfeeeedee8984666738929ab6646676766684336358ddfffffba87777776535654579444413436588714446444444311100000000000000000000000000044",
|
||||
"9cccededeeeeddecbcefeffcbbbdeeedfededddeeeddeddcddddddeedcdccddddddddddddcdeddcdedddddddddedddeededeededdddddddedecfeeeedceaa7655865543a9a785a6cb6a9c9978658dbceefeca96888675ab97732694333323333588893333343354420000000000000000000000000000016",
|
||||
"6677879bdabbbaa9abaaaab8a989fffedeeeddecddddccddcddeeeeeeededdccdccdddedcdddddcdcdeeccdccddddefeedeeeeeeedddeddddddeddeedbb97258a86a943d2a7667bbb8a96734659ddbbbbbbb988777749bcc7433599833123444688886622533464342000000000000000001100000000012",
|
||||
"646687a88887667679786aa99798eeedefeeddcddcccccdeddddeefffeeeedccddecdceeddddddddddcdccdddddcecddddddeeedededeeedeededdddeca96553a97885412266aaebec9b555657ddcbbca9aa98766727aabaa545365432222344357ba9652442343536436000000011000001000100000011",
|
||||
"836677788668896865978598a7a8cdeedeeeefecdccccdddcdbdeeeedeeeeccdddcccccdeeeeddbcdddeefdcdbedcceccedeeddefeeededeeceddedcc9977895a7db9654282efbcaba3655368acddcedcbba87321149aa9774454334523212104684b8341324446534424300000001000000001100000011",
|
||||
"7546777878966777a887a86747989beeeeeeeeeeeeefdededdeeddeeedddeccbcdddccccddccbedddddceededcdddd8eddedededeeeffeddefeddedea9778644187a854bb6dde8e84434445abbedeeeedbb874431459986543554444333422110119a9330233244449b96530000000000000011000000012",
|
||||
"567665768776776897786467779678bffeeddeededcddcdddeefeedcddedebdddcccddddedccdeddcdddcdcededddfedeeeedeeefedddeddedefefea9967887410b836bddaca99693554356bdeefffeddcb864454456774434544445444333321019994431331467aa965120000000000000100000000012",
|
||||
"65568667546679865769a778777678888deefdedeffeededdddddeedcddddddcddcddddddddcdedcddeddbdddeedececdededeefefeeedeeedeefed9a77885500139badbfcbbba948433456dcedfffeddca85336345676435554434544423444228989533001349865354310001000000012100000000121",
|
||||
"66667666766777776897987465287799977dedccdddeecccedccdeceeddddecdccdedcededdecddeddddedddfeed9dedfddddedefeeeeedfffffeed8967978100049a9ccdeda64285665568fefffffdecb87543444665433764444444402344432a88b8334006aa994364311001000000111011000001121",
|
||||
"6768778876655965887742355435388988799dedccdeffeedccedddedddccececccdddddedcdddcdcdeddedeeddeddddeeeedddedfeddeefeeeefe878789732101899dccceeefceb477679cfffffffffdc96556424544336764445444202233331974a9731007aba68922300010001011110100000012222",
|
||||
"656778767756768788751334744456479a7887ddeeeeedeedededddfdcdecdcdededddcddecdddcddddecceeeddfdeeedeeddcceeeefffffeeeefb97779830110177cdabbeeefaffbcebdabffffffffffc97655655444447974455344000232213392197ab0189a866620000000000011101000000113223",
|
||||
"578767779786766878732966542133319688858bcbdedefdddeeeeeddeeddeeeeeddeedecddeddddddeeedfeedbcfddeddeffeeeedeeeefeeeedeb8868961111019cccaeeeeefefefeeffdcffeeffffefb9aa9899877ddccbb3445443000111132241226b950876437420000000001111011100101234233",
|
||||
"68888a787a896869654453032459ba63086788889cddddddedcdefeceeddedffeefeedefeecdddddcdededdeecdddedddceedeedeefefeeeeedfd94768811125bccccbdd9ccdeffffddedfdcfffffeefe99abedbb9898644567ac4420000110021193189a79287658333000000000110011100002233323a",
|
||||
"78b7986b988785787516363339bbda432887786987cddfefeedefeeedeeeeeedeeddcbdeddddddddcceeeeddeededdedeffeefdfeeeeeeeeede9c786892016cccdcccbcad6dadefffeffcdecddeedccccb9888776652223544667530002331000007789997687755342000000001110110001112224225aa",
|
||||
"89ab99baa877695573331c485dca86553578889779bddddeceddeddddedeecefecdddeeeeddddcdeddddeeeedfefddeeeeeeefeefeeeffeeedeea7548812cdddccca986d9e675effffeeedddcedcdcdccbaa97743847686668554741036012485526678aaba94542122000000001100011121212342069aa",
|
||||
"8a9aaaaabab97a86623114c79cea8938479a887a778cccccdccceeefeeeddeeddfdedcdeeddedddddcddeffefedecfddeeeffeeeeddeefefddfea455732cfeddba9865543a6b75ffffefffdddccccddddcc8766aa96866667786777247635aa9aaa37599aa78574574332000001000001212222140299999",
|
||||
"69b89bbaa9a9a8873121389dbcdb7469296488778788bccddcdeddeddabddcdcddbddeddeeddffeedeceeeedeeeddeedfedeeeeeedeeeeeeffee8ecbcdcdfdca8755655655a555ffffdefeedbaaccededddab8a784657775888766666337bbaabda6469aa999aab977ba410000000101113322202688a79a",
|
||||
"49a9999a9aa8998772307b9ccbca768a584a78677778beeedddcdccddcbdddddddedfeedefddcfecdfedfffcfcceefeefffffffeefeefffffddfecbb9bbed98755566654566b978ffefdfedbabefddccba8988795787676688a87777654abb9bab964399999ba989abb973000000001222221035888b8999",
|
||||
"89aa9989a99a88867033bdbbcbaa86cab877768655768bcdccdcecddcdddddccadddffeeff7edaaaa79afeffdeffeeeffffffeeffffffffceeeecdc9bbcb755567666619987856abffededcccefeccccca86788567867566799987787775ac8a9c95336897aa8789aaa85310000101121201229789899764",
|
||||
"97888a9a989898877415ccccaaaaa5c32858978655756edccdcddbbcaddfededcddddcdffdbbbbdbedcba9efefffffffefffefffffdfedddcedcdccbcde85556676550a978765436fcedcddccddcbabbba998457778667668aaa9988888874569aa54366679dcbaa98865200000011121022759874546536",
|
||||
"6787778879a87787768addbc889a887497787755755687bbecbcddeedddcdddfeeeddfddb94666ceccaada84ceceffffffeffcedcddcbcccdeefffdccbb75566551002889658787744eeecddcdcaaaaaa9a56aba988777667aabaa98998887648665335655cbbbca86534000110102002423444544644478",
|
||||
"6767767666677677657aceba8756763876688586675586a9cefdedee9cd9decd7dcbbcba977566bdea47c59b6ffdeefeefffdecbc889acddedfeeeda88754552011212aa8788889998a2ffeddedbba9a9755ccdca9897777799aa99a998999865325cbcbaaabaaa985410000100000122342333345457989",
|
||||
"6776566766566556666bcdb9765449378959768876756678dccdcdcaedcbddcbbbcbcbaa75742d98bd7c4434b3eb9ecdcfa9ccc7579babbb9ccddc975554542011001288788989abbbabaefeeeccbb98855c8bdcbbaa8877789aaaa9988898887758bbaa8a9a88754423000006578b8111112125438a8978",
|
||||
"7666566344542aba756bbdbabb6330a7769886aa977567649bccdedbcbfccbbbbabbbb976544cbcd9ecb2a45d9e862843ccfcbb556666a9877899865565220121021008777899aabbbccdeeecccbcaa967cdccccccccb98877889abbb88887888865789a99965454223200046889bb74322334444a99a988",
|
||||
"456644347cc99a976528adaab7432768886a9a99aba94557795cb87dbcbbaaabbabba765443ddedecec873b53deeffded6da555656f2867666666555221111111011110666789ababbcdc9decbaaa9578bccbcbcbbccbaccccd7999aabb97788878654777853425443444026889aaa875022245376786899",
|
||||
"3536511ddcbbba744288cda98443423168ccbaaaabb97bccabbbbab97aa99a8abba9755436deeeeeeded49d22efffeef9e6ca4558ffefffdfff7976701111121102433376677789a99abca6fcb9968589abbbcbbbabdcbb9879cbacc899bbaa7887876454443445434333136899a9aba650445357677a989",
|
||||
"234232ceccb89ac64589db97644423333ccccbaa96abbcbbcbbbbba9777599bbbba86444bededeeeefdedbdfceffffefd6b439bffffffffffff7857422121121112553227766677886aaab953866a99aaabccccccbbb95688776369babba8a89bb77866513344335443333368889aa998762235467aa9998",
|
||||
"34543bbcdca88dc86abcab75454443545cccba876dbbabbabbabbbaa977bcbbbba8654fddedeeefeeededfeffffffffed46b6fffffeffffffff9866412110121524443421664556654689999755679abaaabcab988866a9a9acc9876465689aabbb9a8751334423454433346779699899a96233365989989",
|
||||
"24445abab987aaa999bbad6554345756accbca67baa989aaaaaa99997779aa9775664dddededdeeefeeeeffffffffffecb6a6ffffffffffffffb8674110112214456523220002032111189aa9864899abcba9a87745defecccdcbcbb844545668888555893235555434333356475445aaaa9587766656b89",
|
||||
"45647bda8889babaaaab8b65867788abbcccc95455655677778877754479a8555559efdcededdeeeeededeffffffffffaaffbefefffffffffffc875512102110532443326322212402125babaa874888a998bc845dddfdeedddccd98dccbb9997445556776534555433432334432119aaba955345545799a",
|
||||
"56766bcaa8bcccba9aaa9c5acabbaaabbccdc73254677565566664543454554349ccdeeeeddeeededdeeefffffffffffffffffffffeffdfffffd8753121111113413333434143321322268aa9a9a796889abb735cddcfeedeefbbecec499987332334898678644443433432333322289a75545333433899a",
|
||||
"4566bbcbbdcbcbaabcab97acacaaaababccc952123677666344554478b875eeebb9bbdedfcceeddeeeddefffffffffffffffffffffffffffffff8844210000221012134454154213312133388899a9779abb875dcddffeffefadefed7aaaa9999aa759996687778774443402221355658535434432a9aaaa",
|
||||
"56657acbcdcccaaadcbaa98bcbbaabbcccc9532221344455444188aaa885dcfecacdccedfeeeeededdddefffffffffffffffffffffffffffffff8744211100011131014433234443110113210667ba65baa958aadeeffefeebeeefdbababccc98aa8876b977777988875068776443584267775323199a9ba",
|
||||
"55555ab9bcddcbbcccaaba9ccccaacdccb944433247568698898988866cbabdecbedebcefedeedfeddcddffffeffffffffeffffffffffffffefe7863131000001111114421135532221212212310027319aaab9cdffffffefffffedccbbcdcbba85688754accccbabb866444678655453484445765661999",
|
||||
"455469979accbbbaaaa9999acbaaacccb976433345675777786998876ababacdcbbeca7cecfeeeeeedddcffffffeffffffffffffffdffffeffff588321200000001100023127763142242231251225232018a89aedffeffeeffdfadddccccdcdec7557754568bbbabbba9654123244434455444534556777",
|
||||
"4567658639bdccbbbbaaa99bcabbbcca976544333776676777775777bbbaccdedcbaa998edeeeeeeedecdffefffffffffffffffffffcffffffffc88421101000000000113678533132333232133353321144528acdfefffdfeececccdccdccdeecb855544455789aabba9999991112112001225653112245",
|
||||
"555546755dcddcbbbaab999ccdbbcbaa8764343467787668777877cbccbcc9ceeca8769899bbadddededffffffffffffffffffffeeedfeeffffff886311000000000013542774322223433452433254326125217beeefecceffebcbcdccbbbcddcb866555655678999aaaaa99a9987678877a41366872989",
|
||||
"5555567547edcbaba9aa98acccccaa9976544336867777887877dbabcccc9abccc98668a989977cdfddfffffefefffffeefffffffefcfefffffef8883221000000001445688542342234343502323577267933224cce101efffb6bbbbbcb88bcda86566855656677888998a9999999998acbaaa988aba7ab",
|
||||
"5555588544bb9aa9999987accccca9975654434557557778886cccbccbb96cbbabb866aa988b9899aaffffffeffffffffffeeffeefffffefffffff88422200000001434658322222433233296577a857748734007559cb83fbfb7999aaa86678a9655654455555665566777777877755767a99a988695aa9",
|
||||
"55555875432899998887768acbbba875444344474755676795cdddcccb964bbbbca76679aa97a99a999affefefefefffffffeffdfffdffffffffef7873112010000124361522132233233232747a7b9652a5944449bbdca7bbbf678787765567675454445545555445554555455554467889aaa9876ab79b",
|
||||
"544458753336888878776469aaba986544343435567576676cdccdccb964cbcbcca767a777777eabaaab9ddfffeeffffffeffffffeffffffffdffff67322310000014425105121123342112176abbbd6146124366abccbb8adbd89a8526222221124665566544434344433444344544545486458898878aa",
|
||||
"44566755333b776776876678abcba9654443232454544636ccddcdccb73cdcbddb9658888a9779baba8a998cedeefffeefefffffffedeeeefefffffc6532341000013425301111121322233416a3b4a0ba346446999ba9989dbc79acba14333323332325565544333333233332442222441444567994a9aa",
|
||||
"45476564334b877989898abceddcba84455442322234244cccdcdccb95cdcbbeec9768899899999baaba9a88cfeeeffffffffefffffeefffeffffffd362224320002543530111012223343249446b6a542451545789a89888997e9aaa77564443333331115665332333222212222322120000024645aaabb",
|
||||
"56677894334c89aabacccdcccccdbbb6544544112221223cb8cccbba5beedcbeeba6699888888979a8a88aa98ceeeeefeffffffeeddddfeefffefffff55232530112524242112112211344432365a57512134355899867743588cab68888743344332222211000000011222232222332210110000008abbb",
|
||||
"5567dba4533ab9abbbcdccbaabddcb9753443421201121acccbca9984cdddcbddb9659999897889a99a989a998dffeffffefffefefcddeffdffffffffe35453310145145242211102223254322298525a134455688865554433155655566444444111232210100000000112233323433222000000000019b",
|
||||
"46679aba423ab9aaabcbcddcbabbba9754445445210122accbbaaaa73cccbaaeec754888899988977ab8aa89998fefffdefffffffeeedefeefeeeffffdd744441536314553621221222335532112383085554445756455455433333333443333322223331210011001000101223333333433200000000011",
|
||||
"34a997868539a8999abadedbba99998845343335441199aaabbbaa978cddbaaedb654775689998977879a8888a89fffeffefffffffddfeefeffeeeffffeca4255435482445232101263344443222887465555544656555554433343334454443322122331321511001000000001233334343330000000013",
|
||||
"37bbcba7994799a9aa9acdcba988a9975453556654779aabccbbaa96acdca9cdc9652545577889888987878888889ffeeeffffeefffeffefefcdffeffffdee443563db34677342211133333333113588316568555576665514444444444555443210124210334432201000000000013344342223000001ab",
|
||||
"079bcddca077599a9989aaaaa9abacdcdb666776554898cddbba9984bcb9a9ddb75523455567666789668679897a9cfeeefffeefffeeffffffeeffefeffeefdeccdfefa4435553211242212232334368920776666555544444444343443555433011114658254343202113100000002234443343323002ab",
|
||||
"2769bcdcbcc3469b9789a9aaaaccda87eba7778754378cdddcb98979bcb99bcc965434333334666786877666a99978beeeffffffffffefeffffffffcffffdfffefeeded844435552324444323233431748169777764444443333334444444322212121175b85456474301223100001002343343332312abb",
|
||||
"56689bce66bb3459867999aacdddcdb9ab9887666547cdddcbb8897bbba9addb7563233443344666767555655898867aeeeeefeffffefffeeeedeeeefeffffffffeffeec86654646666655432224556281966767665554443343344555455432222322211deb2647245342222300000013344444334425bc",
|
||||
"54577abb92089245568999abbcdddcb9899987766557ddddcb87776aa999adca646232332345454444544444437998797eeeeffffffffffffeeffffdeffeffffffeefdfdd8576656776565541021666527717743565544433333345665555532223433322219a624244517211332100014b33543354432bc",
|
||||
"441668b23531001568aaa99b9bcccba9988888766554bcbcb86677699aa9ccb855223223333453445454455433469a8798ffeeeffffefeffffdeeefeefffffffffffffeeedc5663656654387655454463227611774568622658334566655554322344322222111145564649013346001109dc3443343442b",
|
||||
"4355563212400012678aaba9abbbaaa89788986767659baa87567657ababcc965532222332244544344555553433689789bffffffffefeffffefedeeeffffffedfffffeffeccc9a88777668767766566634343785368635542340355554555432335443332222333cbbabcc71222cb514addddb34432332c",
|
||||
"44445110001110101678abbaaaa9a987889a97778765577664566659aa9ccb755344323323333544534455665534468b978eddeffefeefffffffedffeffddfefffffffeefffeefa998897567776664427765454473684783452436455544443223445443332234443bbccccc72122ddcdedfdddd35173528",
|
||||
"234356312411111000889abbaa99987888987678986594555555553aaacbc9643333323433243444444555555443444aba77eeeffeeffefefffffefeffdfefffffffffffecffffa8897786566565533116545645555454476566465c22244431223344332222344332bcddecca224dddeeeeedeca34403bb",
|
||||
"12223443343431210009abbbba98888778867798864827444444439b9bcca655234443343344445554545555554453469999befffefffeffffffefffffffefffefffefffdefffff68455444555533091376522201856765557627657c69bce2422332333222345544443eccddc925dddededddcddec413cc",
|
||||
"1011112322332200000aaabaa8764566778abcabccb94bd3444432aaaccb85584345543343434455445545555443623389a99feffffeffffffffeeeffeffefeffffefffdefefffff775543332226799777653222207897687987356677987989ceefe41232143455554544eedcc97ccdcdeeeddccdccdccc",
|
||||
"10002332221211000000798976579abbbabbeeedecc84bdbc242129acdb954444335365544543445555555554423333799979affefeeeffeefffeedefeeffdfffffffdfeffffedffbfffefb9cecbe98a9a4432232265799987887657678886bcbcb9cbdecbede4466655545deeddd7ccdddddddddddeddde",
|
||||
"1001132112211100000107577abbcbcbccddefddededccbbbbb126bbbca64566655334334444444345554454433332259998688ffeeeefffffefffeeefedeeeceeefefeffffffffeffdfffffffcbcb9799ab22212227388aa988b78777688787668bbccbeeddcd55676665441deeedddeeededcddecdedcd",
|
||||
"113355454332210001233149aabcbbccccddddbddecddcbbbabb5aabcb854666565654444332233334344433333322149aa88688fdfffffffeeeffeefeeeefceefffeffffdeeeefebeeeeefefee9accd98c92333322d6569b989ac988777698978897acedeedddd55567565444cdeedceddcedeedcdddcdd",
|
||||
"123333433342222132233435aaaabbbcbcddddcddedeedddbccdedbdc75574566565554466434333343333332322221378998988b9efffeffefffffffedfeedceeeefeeefefefefecdfffefeeedcbdcdd689b2333222c977759aaaccd98666789898877dededddde55665555554cdddddeeeddeddcdddddc",
|
||||
"22233334344534544545545479ab9aa99bcdddddddeeeeeeeeeeeeeeefdb5666665556555433333343323333343212223877aba8babffffeffeffffeeefeefeeefeedcdddfeefeeeedeedfdedeeeccecaa8aac133323eddecdeeeeeededcd99999a87876ceddddedd35565445544459dedddedededddddcc",
|
||||
"122212233344354554443535489999799aabc7ddddcdeeeeeefffffffeeca8656566555466433333232322334433222223568abaa999beffeedfffefeeeeeddfeeddcededefeeeecdeefeeddddeeeccebbb9bcc72322ccdeedeeeeeededaa7787979ba7779cdcdddddd665555545444535dddddddcddbedd",
|
||||
"02232232234545444444444542788878899bcbbcccddeeeeeffffefeeffddc9b8576665665544223323233233343333211136679aa989aefeefeefeedeeeeeeeeeedddeeeeeeeefddeedeededdedeedcd8cfd89de3333deedddeeeedcac878888a9bb869a79dddddddddcde25555445665dcdddddddddddd",
|
||||
"122222123134343444344455453566777889aabbbcccddddeeeefdddefffeda9b964545556732322323233343343333333112447aa99aaaffffffffeeefeeefeeeeeeeeeebeeeffdcdedddeeedeededdddaeeeede732245cedeeedea98b667879acca899789cdeeeefedddcdcccc464475ddddcccddddddd",
|
||||
"0101111111223433444554443655454567788999aabbbccdddedeccbdeefdca9899322234533112132223334334343433333222469998ba8fefefffedeefebeededddeeeeeeeeedecbddddddeedeeedededdeeeece244448cdeeeebeda7789766879ceddc97aeeeeddefdddeddddde454ceddedddddcddcc",
|
||||
"0010001012323444444444443555545245667778899aaabbbbccbaaabccdbabaaa98231344211112122122333445444444433232447999a99beeefeeeedfeeeeeddddefeedeeeeddecdeeeeedddededdeeddeeeeeec13337ddcddccdc9977667776776869bcededeedeeededdeddbdc35ccdddccdedccddc",
|
||||
"000000010112444443223344433322333144667787888999a9aa9988889b9aaa9998789952311223111122223445555554335443345499a99baeeeeeddeededefeedeeeedeeeeeddcccddddededdddedededdddededd4233eccdaccdb9aa7667879899a88768edeeeedeeeeddededdddadcdccddddcddcdd",
|
||||
"00000000012333343232222232111000011114556676787888988767677899a9aaaa9999aa95132211222354453555655432323332236889aaabfeecdeeeedddedecdeeeeeeeeeeeddedddddddddeddcddeddeeedefdc3deccdbeeedebca8877699a9b8878a778ddddeedeedddececdddeddddddcdddccdd",
|
||||
"000000000012222322222210000000002233301323445555666776665677898899abdbaaaaa88733343334344465655655434233323357988a9a9acdddeeadeeeeeededddedeeeddedddcddddddddddbdccddddeedeedeeeedddbcddcbcb99aaaba7979998aa9779ddeeddeeeeeeededdededdedddddcddc",
|
||||
"000000000000000010110000000004232244630011434543214333111355688799bcdddccbbba88565555564555565355565433223325659988998aedeebededddaedddddeeebeceedddcadcdcdcecdccdccdddddedeeeeeeddeeccdbbbdca9bc778789978998bb8a8bedddeddddeedeeeededddddddddde",
|
||||
"000000000000000000000000022322434553552210002243432144153202578889bcdddccddcaa98455645554455544535454542422336678888aa9adcdddedddeeeededeedbdddedddddddcdddbdddccdccccccddddedeedededdddacddddcbbcd998787778989c88baddcabddedeedeedddedddddddddd",
|
||||
"0000000000000000000000013454554455534553310011122111221322121157899abcccdddccc9a98845544555554454444344333445455a8b9a9b989dddddeebeecdedcdedeeedebedddddddedddccddcccccdcddddeedecdeddeedeedddeeddcd9aa8979888b9b99bcccccceeeeeddedeeeeddddddddd",
|
||||
"00000000000000000200002400005323555224554332000133343314443211157999aaabcddcccbbbaa9744539445554434544433354356499a79aa898aeddedbdeeeedcdddeeedeeedddccdddddcdcdddccddcdceddcdededddeedededdddeeedcdcbaa9abb97889ab789dbddcdddcdeddddddddeddddee",
|
||||
"00000000000000001000114002330124661222555544343012122212222233225678899abbbcbcdcdbbbcabccdac465448b233334334544678898999987baddcdeedddededddeefeedcddddddddddcccdcdcdccccdddcdcdcdddddddeeecdcddedccddb9999baba8c89a87abcccbedbabaededddeeeeddde",
|
||||
"000000000000001213221127213420465001223555554444011212222122232223568888999aaacccbcccccbcccbcdbccbbbc224324254547a9baaa99b99aaecdddeeddcddddeeeddeddddcdddddddcccdcdccdddddcddcccdddddddcddccddddcddddd99a89caac7888a7b8689bc8cdddedceedefedeeee",
|
||||
"00000000000000201025234003252363541321245565454342011212223222222335567788888899aa9aabbbbbbcbcccba98ab122333333557999799a999989edeeeedcccdddeeeedddcdcdddedddcccbdcccccccddddccccdcddeeddcdbcdddeddccddc88eea9abcd978b67c9eeddeeeddddddddcdeedff",
|
||||
"0000003070000211110023000134352044250112236565542430100212112222332323466766667777788879acdcbcbbbaa22322322233444368988a89987979adeeeeecccdefededddddddedddccbcccccddcddcdcddbccccccdddddeddddeeecddeeddedeeed89ccefceeefefeeeeededddefdeeedeeee",
|
||||
"00000213900010312112111540536765531730111336555534220000001001221112132213545455556566666677a9abcccaa212332223344446888889797887abdeeeedecdeecddddddcddddeddddccdcccdccdddddcccccdccdddddedddddddcbdeddeeeeedeeeeefeedddddddedeeeededffedffeefef",
|
||||
"00000453a00100001231255231135165429200021234555443210000011211111012222323353411001224115458a9899ad8a4134243123434558aa7ab898a99877deeeddcddceddddccdedddddccccdcccccccddddcdddccccccdcddddedddeddcdceeeeeeeedefcceeeeedeeeeeeedddeeeedeedfeeeed",
|
||||
"01103773a000013213143662111653262824222101324554321111100000011100012121320244533332434443323798a89864454333333324566878888999899a8beeedeeddddeedededeedddeddddcddccdcdddeecdddddcddcdddddddcddddddeedeeeeeefefeddecedededddddedceeeddfeeededfee",
|
||||
"97915673a401212200011410242567949252262641233543211100101000022300010013122133343311232121122335474577644123343544454578877888899779ceddeeecdcddddddddeeedddccdddddddcdddedbddcccccdcddddddddddddcededdeeeeeeeeeeeeedddddddddddeeedfed771ceeeeee",
|
||||
].join("");
|
||||
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useMemo, useRef } from "react";
|
||||
import type { Backdrop } from "@/lib/backdrop";
|
||||
|
||||
const SPACING = 6; // CSS px between dot centres
|
||||
|
||||
type Grid = { w: number; h: number; levels: Uint8Array };
|
||||
const parse = (dots: string) => Uint8Array.from(dots, (c) => parseInt(c, 16));
|
||||
|
||||
// The brightness grid (26 KB of text) is its own chunk, shared by every page and parsed once per
|
||||
// tab. Imported statically, it was copied into each page's chunk.
|
||||
let grid: Promise<Grid> | null = null;
|
||||
const loadGrid = () =>
|
||||
(grid ??= import("./adam-dots").then(({ ADAM_DOTS, ADAM_H, ADAM_W }) => ({
|
||||
w: ADAM_W,
|
||||
h: ADAM_H,
|
||||
levels: parse(ADAM_DOTS),
|
||||
})));
|
||||
|
||||
const BackdropContext = createContext<Backdrop | null>(null);
|
||||
|
||||
/** Provides the custom picture from Settings → Appearance (null for the built-in painting). */
|
||||
export function BackdropProvider({ backdrop, children }: { backdrop: Backdrop | null; children: React.ReactNode }) {
|
||||
return <BackdropContext.Provider value={backdrop}>{children}</BackdropContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that
|
||||
* fills the box (at least covering it), placed so `focus` (the hands) lands at `anchor` (x, y as
|
||||
* fractions of the box) as far as the painting's edges allow. Dots use the element's text color; bright parts of the painting get big dots in
|
||||
* dark mode, dark parts in light mode, so it reads as the painting either way.
|
||||
*
|
||||
* With a custom picture (Settings → Appearance, or `source`), that picture covers the box instead,
|
||||
* with its own focus point at `anchor`; `view` and `focus` only apply to the built-in painting.
|
||||
*/
|
||||
export function DotPainting({
|
||||
className,
|
||||
view = 0.7,
|
||||
focus = [0.48, 0.42],
|
||||
anchor = [0.68, 0.5],
|
||||
source,
|
||||
}: {
|
||||
className?: string;
|
||||
view?: number;
|
||||
focus?: [number, number];
|
||||
anchor?: [number, number];
|
||||
/** Draw this picture instead of the one from the settings (the Appearance preview). */
|
||||
source?: Backdrop | null;
|
||||
}) {
|
||||
const ref = useRef<HTMLCanvasElement>(null);
|
||||
const fromSettings = useContext(BackdropContext);
|
||||
const custom = source !== undefined ? source : fromSettings;
|
||||
const customGrid = useMemo(() => (custom ? { w: custom.w, h: custom.h, levels: parse(custom.dots) } : null), [custom]);
|
||||
|
||||
const [fx, fy] = custom ? custom.focus : focus;
|
||||
const [ax, ay] = anchor;
|
||||
const v = custom ? 1 : view;
|
||||
useEffect(() => {
|
||||
const canvas = ref.current;
|
||||
if (!canvas) return;
|
||||
let data: Grid | null = customGrid;
|
||||
let cancelled = false;
|
||||
let frame = 0;
|
||||
// What the canvas shows (size, pixel ratio, theme, color): a drawing takes tens of ms, so skip it
|
||||
// when nothing changed, e.g. for the ResizeObserver's first callback or another class on <html>.
|
||||
let drawn = "";
|
||||
const draw = () => {
|
||||
frame = 0;
|
||||
if (!data) return;
|
||||
const { width, height } = canvas.getBoundingClientRect();
|
||||
if (!width || !height) return;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const color = getComputedStyle(canvas).color;
|
||||
const dark = document.documentElement.classList.contains("dark");
|
||||
const key = `${width}x${height}@${dpr} ${dark} ${color}`;
|
||||
if (key === drawn) return;
|
||||
drawn = key;
|
||||
const { w, h, levels } = data;
|
||||
canvas.width = Math.round(width * dpr);
|
||||
canvas.height = Math.round(height * dpr);
|
||||
const g = canvas.getContext("2d")!;
|
||||
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
g.clearRect(0, 0, width, height);
|
||||
g.fillStyle = color;
|
||||
// CSS px per grid cell: `view` of the painting's width fills the box (at least covering it).
|
||||
const scale = Math.max(width / (v * w), height / h);
|
||||
const offX = ax * width - fx * w * scale;
|
||||
const offY = ay * height - fy * h * scale;
|
||||
const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o));
|
||||
const ox = clampOff(offX, width, w * scale);
|
||||
const oy = clampOff(offY, height, h * scale);
|
||||
const maxR = SPACING * 0.48;
|
||||
for (let y = SPACING / 2; y < height; y += SPACING) {
|
||||
const iy = Math.min(h - 1, Math.max(0, Math.floor((y - oy) / scale)));
|
||||
for (let x = SPACING / 2; x < width; x += SPACING) {
|
||||
const ix = Math.min(w - 1, Math.max(0, Math.floor((x - ox) / scale)));
|
||||
const level = levels[iy * w + ix] / 15;
|
||||
const r = maxR * (dark ? level : 1 - level);
|
||||
if (r < 0.35) continue;
|
||||
g.beginPath();
|
||||
g.arc(x, y, r, 0, Math.PI * 2);
|
||||
g.fill();
|
||||
}
|
||||
}
|
||||
};
|
||||
// While a window is resized, observations arrive every frame: draw at most once per frame.
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(draw);
|
||||
};
|
||||
if (data) draw();
|
||||
else
|
||||
void loadGrid().then((g) => {
|
||||
if (cancelled) return;
|
||||
data = g;
|
||||
draw();
|
||||
});
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(canvas);
|
||||
// next-themes switches the class on <html>.
|
||||
const theme = new MutationObserver(schedule);
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(frame);
|
||||
resize.disconnect();
|
||||
theme.disconnect();
|
||||
};
|
||||
}, [customGrid, v, fx, fy, ax, ay]);
|
||||
|
||||
return <canvas ref={ref} aria-hidden className={className} />;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CloudAlertIcon,
|
||||
DownloadIcon,
|
||||
HardDriveIcon,
|
||||
LibraryIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
import { formatBytes, formatDuration, formatSpeed } from "@/lib/format";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { PageHero } from "./page-hero";
|
||||
|
||||
const noSubscribe = () => () => {};
|
||||
|
||||
/** "Good morning" etc. by the browser's clock (the server renders a neutral greeting). */
|
||||
function useGreeting() {
|
||||
return useSyncExternalStore(
|
||||
noSubscribe,
|
||||
() => {
|
||||
const h = new Date().getHours();
|
||||
return h < 5
|
||||
? "Good night"
|
||||
: h < 12
|
||||
? "Good morning"
|
||||
: h < 18
|
||||
? "Good afternoon"
|
||||
: "Good evening";
|
||||
},
|
||||
() => "Welcome back",
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({
|
||||
icon: Icon,
|
||||
label,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
icon: typeof DownloadIcon;
|
||||
label: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 flex-col gap-1 rounded-lg bg-background/60 px-3 py-2 ring-1 ring-foreground/10 backdrop-blur-md",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center gap-1.5 text-[11px] font-semibold tracking-wide text-foreground/80 uppercase">
|
||||
<Icon className="size-3.5" />
|
||||
{label}
|
||||
</span>
|
||||
<div className="text-sm tabular-nums">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Library header: greeting, live download status, free space and library size, on the dot painting. */
|
||||
export function LibraryHero({
|
||||
name,
|
||||
models,
|
||||
libraryBytes,
|
||||
updates,
|
||||
goneFromHub,
|
||||
initialWorker,
|
||||
action,
|
||||
}: {
|
||||
name: string | null;
|
||||
models: number;
|
||||
libraryBytes: number;
|
||||
/** Models with a newer commit on the Hub. */
|
||||
updates: number;
|
||||
/** Models whose repo or pinned commit was deleted on the Hub. */
|
||||
goneFromHub: number;
|
||||
initialWorker: WorkerStatus;
|
||||
/** Shown next to the greeting (the "Add model" toggle). */
|
||||
action?: React.ReactNode;
|
||||
}) {
|
||||
const greeting = useGreeting();
|
||||
const { snapshot } = useLive();
|
||||
const worker = snapshot?.worker ?? initialWorker;
|
||||
const jobs = snapshot?.jobs ?? [];
|
||||
const downloading = jobs.filter(
|
||||
(j) => j.kind === "download" && j.state === "downloading",
|
||||
);
|
||||
const queued = jobs.filter(
|
||||
(j) => j.kind === "download" && j.state === "queued",
|
||||
);
|
||||
const speed = downloading.reduce((s, j) => s + (j.speedBps ?? 0), 0);
|
||||
const left = downloading.reduce(
|
||||
(s, j) => s + Math.max(0, j.totalBytes - j.doneBytes),
|
||||
0,
|
||||
);
|
||||
const eta = speed > 0 ? left / speed : null;
|
||||
const free = worker.online ? worker.modelsDirFreeBytes : null;
|
||||
const total = worker.online ? worker.modelsDirTotalBytes : null;
|
||||
const usedPct =
|
||||
free != null && total ? Math.round(((total - free) / total) * 100) : null;
|
||||
const first = name?.trim().split(/\s+/)[0];
|
||||
|
||||
return (
|
||||
<PageHero
|
||||
tall
|
||||
title={
|
||||
<>
|
||||
{greeting}
|
||||
{first ? `, ${first}` : ""}
|
||||
</>
|
||||
}
|
||||
description={
|
||||
!worker.online
|
||||
? "The worker is offline: downloads and benchmarks wait until it is back."
|
||||
: downloading.length
|
||||
? `${downloading.length} download${downloading.length === 1 ? "" : "s"} running${queued.length ? `, ${queued.length} queued` : ""}.`
|
||||
: queued.length
|
||||
? `${queued.length} download${queued.length === 1 ? "" : "s"} waiting.`
|
||||
: "Everything is downloaded. Nothing running right now."
|
||||
}
|
||||
actions={action}
|
||||
extra={
|
||||
<div className="grid max-w-3xl grid-cols-2 gap-2 lg:grid-cols-4">
|
||||
<Stat icon={DownloadIcon} label="Downloads">
|
||||
{downloading.length ? (
|
||||
<Link
|
||||
href={
|
||||
downloading.length === 1 ? `/jobs/${downloading[0].id}` : "/"
|
||||
}
|
||||
className="hover:underline"
|
||||
>
|
||||
{formatSpeed(speed)}
|
||||
{eta != null && (
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· {formatDuration(eta)} left
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
{queued.length ? `${queued.length} queued` : "idle"}
|
||||
</span>
|
||||
)}
|
||||
</Stat>
|
||||
<Stat icon={HardDriveIcon} label="Free space">
|
||||
{free != null ? (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span>
|
||||
{formatBytes(free)}
|
||||
{total ? (
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
of {formatBytes(total)}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
{usedPct != null && (
|
||||
<span
|
||||
className="h-1 overflow-hidden rounded-full bg-muted"
|
||||
title={`${usedPct}% used`}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"block h-full rounded-full",
|
||||
usedPct > 90
|
||||
? "bg-destructive"
|
||||
: usedPct > 75
|
||||
? "bg-amber-500"
|
||||
: "bg-primary",
|
||||
)}
|
||||
style={{ width: `${usedPct}%` }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
unknown (worker offline)
|
||||
</span>
|
||||
)}
|
||||
</Stat>
|
||||
<Stat icon={LibraryIcon} label="Library">
|
||||
{models} model{models === 1 ? "" : "s"}{" "}
|
||||
<span className="text-muted-foreground">
|
||||
· {formatBytes(libraryBytes)}
|
||||
</span>
|
||||
</Stat>
|
||||
<Stat icon={CloudAlertIcon} label="On Hugging Face">
|
||||
{updates === 0 && goneFromHub === 0 ? (
|
||||
<span className="text-muted-foreground">all up to date</span>
|
||||
) : (
|
||||
<span className="flex flex-wrap gap-x-2">
|
||||
{updates > 0 && (
|
||||
<Link
|
||||
href="/?status=update+available"
|
||||
className="text-sky-700 hover:underline dark:text-sky-300"
|
||||
>
|
||||
{updates} update{updates === 1 ? "" : "s"}
|
||||
</Link>
|
||||
)}
|
||||
{goneFromHub > 0 && (
|
||||
<Link
|
||||
href="/?status=deleted+on+Hub&status=commit+deleted+on+Hub"
|
||||
className="text-amber-700 hover:underline dark:text-amber-300"
|
||||
>
|
||||
{goneFromHub} deleted
|
||||
</Link>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</Stat>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { DotPainting } from "./dot-painting";
|
||||
|
||||
type Painting = { view?: number; focus?: [number, number]; anchor?: [number, number] };
|
||||
|
||||
/**
|
||||
* The page header every main page shares: the dot painting full-bleed behind the floating menu,
|
||||
* the title, a line below it, actions on the right and optional extras (stats). The painting runs on
|
||||
* below the header and fades out behind the page's first content, which is `children` (lifted above
|
||||
* the painting).
|
||||
*/
|
||||
export function PageHero({
|
||||
title,
|
||||
description,
|
||||
actions,
|
||||
extra,
|
||||
tall,
|
||||
painting,
|
||||
children,
|
||||
}: {
|
||||
title: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
actions?: React.ReactNode;
|
||||
extra?: React.ReactNode;
|
||||
/** The library's big version. */
|
||||
tall?: boolean;
|
||||
/** Which part of the painting to show (default: the hands). */
|
||||
painting?: Painting;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{/* Full-bleed and up behind the floating menu: out of <main>'s padding and width, back in for
|
||||
the content. -mt-[5.5rem] = header (h-16) + main's top padding (py-6). */}
|
||||
<section
|
||||
className={cn(
|
||||
"relative left-1/2 -mt-[5.5rem] w-screen -translate-x-1/2 overflow-hidden",
|
||||
tall ? "-mb-64 pb-64" : "-mb-40 pb-40",
|
||||
)}
|
||||
>
|
||||
<DotPainting
|
||||
className="absolute inset-0 size-full text-foreground/75"
|
||||
view={painting?.view ?? 0.65}
|
||||
anchor={painting?.anchor ?? [0.55, 0.3]}
|
||||
focus={painting?.focus ?? [0.48, 0.42]}
|
||||
/>
|
||||
{/* Fades the painting into the page towards the bottom, and a little behind the text. */}
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-transparent from-5% via-background/70 via-45% to-background" aria-hidden />
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-background/80 via-background/30 via-45% to-transparent to-75%" aria-hidden />
|
||||
<div className={cn("relative mx-auto flex w-full max-w-7xl flex-col justify-end gap-5 px-4 pt-24 pb-8", tall ? "min-h-[30rem]" : "min-h-[16rem]")}>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h1 className={cn("font-semibold tracking-tight break-words", tall ? "text-3xl" : "text-2xl")}>{title}</h1>
|
||||
{description && <div className="max-w-3xl text-sm font-medium text-foreground">{description}</div>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
|
||||
</div>
|
||||
{extra}
|
||||
</div>
|
||||
</section>
|
||||
{children != null && <div className="relative z-10 flex flex-col gap-4">{children}</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { toast } from "sonner";
|
||||
import { pokeLive } from "@/lib/live-store";
|
||||
|
||||
async function post(url: string): Promise<boolean> {
|
||||
const res = await fetch(url, { method: "POST" });
|
||||
if (res.ok) return true;
|
||||
if (res.ok) {
|
||||
pokeLive(); // show the new job state now instead of on the next poll
|
||||
return true;
|
||||
}
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return false;
|
||||
@@ -32,6 +36,7 @@ export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Let a download requested through the API start. */
|
||||
export async function approveJob(jobId: string): Promise<boolean> {
|
||||
const ok = await post(`/api/jobs/${jobId}/approve`);
|
||||
if (ok) toast.success("Approved; the download is queued");
|
||||
@@ -46,6 +51,7 @@ export async function rejectJob(jobId: string): Promise<{ removedModel: boolean
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return null;
|
||||
}
|
||||
pokeLive();
|
||||
toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected");
|
||||
return body;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { BotIcon } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** "requested by hermes": added or downloaded through the API with that token. */
|
||||
export function RequestedByBadge({ name, className }: { name: string | null | undefined; className?: string }) {
|
||||
if (!name) return null;
|
||||
return (
|
||||
<Badge variant="outline" className={cn("gap-1 font-normal", className)} title={`Requested through the API with the token "${name}"`}>
|
||||
<BotIcon className="size-3" />
|
||||
{name}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -100,7 +100,7 @@ export function TagPicker({
|
||||
<DropdownMenuTrigger
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"inline-flex h-6 items-center gap-1 rounded-full border border-dashed px-2 text-xs text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50",
|
||||
"inline-flex h-6 items-center gap-1 rounded-full border border-dashed border-foreground/25 bg-background/80 px-2 text-xs text-foreground/85 outline-none backdrop-blur-sm hover:bg-muted hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
|
||||
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user