Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90d6007b55 | ||
|
|
85d79b6f7a | ||
|
|
02756ddf90 | ||
|
|
422e46bf65 | ||
|
|
67cd0c945a | ||
|
|
6b779debf7 | ||
|
|
6f4932e04d | ||
|
|
d58bff3437 | ||
|
|
d10a491042 | ||
|
|
2e56351e96 | ||
|
|
7239ba2692 | ||
|
|
76d851896e | ||
|
|
16c3fcc113 | ||
|
|
aab48d6181 | ||
|
|
5becfc47a0 |
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
|
||||
@@ -4,6 +4,95 @@ 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.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
|
||||
@@ -22,7 +22,8 @@ their speed and answer quality with [BetterBench](https://github.com/GGZ14/Bette
|
||||
|
||||
## 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 +34,61 @@ curl -fsSLo .env https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/m
|
||||
```
|
||||
|
||||
**2. Create an OIDC client** in your identity provider with the redirect URI
|
||||
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`.
|
||||
Request the `groups` scope if you want to restrict access by group.
|
||||
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`
|
||||
(the path says `pocket-id` whatever provider you use). Request the `groups` scope if you want to
|
||||
restrict access by group.
|
||||
|
||||
**3. Fill in `.env`.** At minimum: `AUTH_URL` (the address you open in the browser), `AUTH_SECRET`
|
||||
(`openssl rand -base64 33`), `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a
|
||||
read-only `HF_TOKEN`.
|
||||
**3. Fill in `.env`:** `AUTH_URL` (the address you open in the browser), `OIDC_ISSUER`,
|
||||
`OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else has
|
||||
defaults. Models go to `./models` and the database to `./data` next to the compose file; point
|
||||
`KANAME_MODELS_DIR` at another folder (e.g. a NAS share mounted on the host) if you like.
|
||||
|
||||
**4. Create the folders and start**
|
||||
**4. Start**
|
||||
|
||||
```bash
|
||||
mkdir -p data models && sudo chown 1000:1000 data models
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open your `AUTH_URL`, sign in, click **Add model**. That's it.
|
||||
|
||||
Kaname creates and takes over `./data` itself, and an empty models folder too. It runs as uid/gid
|
||||
1000 by default; if your models folder already holds files that belong to another user (common for
|
||||
NAS shares), set `PUID`/`PGID` in `.env` to that owner (`ls -ln /path/to/models`). Kaname never
|
||||
changes the ownership of a models folder that has files in it.
|
||||
|
||||
**Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g.
|
||||
`KANAME_VERSION=0.4.0` in `.env`. The running version is shown next to the app name.
|
||||
`KANAME_VERSION=0.16.0` in `.env`. The running version is shown next to the app name. Read the
|
||||
[changelog](CHANGELOG.md) before jumping minor versions: it says when the compose file changed.
|
||||
|
||||
### The image
|
||||
|
||||
`git.linxweiler.xyz/pascallinxweiler/kaname` is public: no account or `docker login` needed.
|
||||
|
||||
| Tag | What it is |
|
||||
| --- | --- |
|
||||
| `latest` | the newest release |
|
||||
| `0.16` | the newest 0.16.x release |
|
||||
| `0.16.0` | exactly that release |
|
||||
|
||||
It is built for x86-64 (`linux/amd64`). One image serves all three services (`web`, `worker`,
|
||||
`sandbox`); the compose file picks the role. To build it yourself (e.g. for ARM) from this
|
||||
repository:
|
||||
|
||||
```bash
|
||||
git clone https://git.linxweiler.xyz/pascallinxweiler/Kaname.git && cd Kaname
|
||||
docker build -t kaname:mine --build-arg APP_VERSION=$(git describe --tags) .
|
||||
```
|
||||
|
||||
and set `KANAME_IMAGE=kaname` and `KANAME_VERSION=mine` in `.env`.
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings live in `.env`. The four steps above cover the required ones; the **[configuration
|
||||
reference in the wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration)**
|
||||
lists every option with defaults and examples (folders, ports, download tuning, OIDC groups, which
|
||||
Hugging Face token to use).
|
||||
All settings live in `.env`; [`.env.example`](.env.example) explains each one. The
|
||||
**[configuration reference in the wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration)**
|
||||
lists every option with defaults and examples (folders, ports, user, download tuning, OIDC groups,
|
||||
which Hugging Face token to use). Settings that change while Kaname runs (download speed limit,
|
||||
which files are picked with a quant, file labels, tags, how often the models folder is scanned) are
|
||||
in the web UI under Settings.
|
||||
|
||||
Models end up in `<models folder>/<org>/<repo>/`, e.g. `models/unsloth/Qwen3-8B-GGUF/`.
|
||||
More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki).
|
||||
@@ -73,6 +104,8 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
are selected along with it; choose which kinds in Settings → Downloads. You can add tags right there.
|
||||
- **Search:** type anything: `unsloth qwen`, `q4_k_m`, `gemma`, `roleplay`. Every word has to match
|
||||
somewhere (repo, author, base model family, architecture, quant, tags).
|
||||
- **Search everything:** ⌘K / Ctrl+K (or **Search** in the menu) jumps to any model, endpoint,
|
||||
benchmark run, tag or settings page, and runs actions like Add model or switching the theme.
|
||||
- **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so
|
||||
you can bookmark a view.
|
||||
- **Tags:** add or remove your own tags on a model's page; click a tag in the list to filter by it.
|
||||
@@ -81,12 +114,19 @@ 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.
|
||||
@@ -103,13 +143,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
|
||||
|
||||
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`);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -169,6 +169,13 @@
|
||||
"when": 1793115558680,
|
||||
"tag": "0023_scan_schedule",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 24,
|
||||
"version": "6",
|
||||
"when": 1793567055573,
|
||||
"tag": "0024_polling_indexes",
|
||||
"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.18.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"
|
||||
/>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -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,12 +68,12 @@ 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"
|
||||
@@ -80,7 +81,7 @@ function Row({ entry, href, muted, showState }: { entry: Entry; href: string; mu
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -163,7 +165,22 @@ export function FilesTab({
|
||||
|
||||
<ul className="divide-y">
|
||||
{selectedEntries.map((e) => (
|
||||
<Row key={e.path} entry={e} href={href(e)} showState />
|
||||
<Row
|
||||
key={e.path}
|
||||
entry={e}
|
||||
href={href(e)}
|
||||
showState
|
||||
action={
|
||||
<RemoveFileButton
|
||||
modelId={modelId}
|
||||
name={e.path.split("/").pop()!}
|
||||
paths={e.parts.map((p) => p.path)}
|
||||
size={e.size}
|
||||
disabled={busy || selectedEntries.length < 2}
|
||||
reason={busy ? "Wait until the current job has finished." : "The model's only file: delete the model instead."}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import "server-only";
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
|
||||
import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { shortSha } from "@/lib/format";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
|
||||
// Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts,
|
||||
// styles or event handlers, only the tags/attributes GitHub-style READMEs normally use.
|
||||
@@ -17,6 +22,55 @@ const schema = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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. */
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
|
||||
const base = `https://huggingface.co/${repoId}`;
|
||||
|
||||
@@ -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,7 +38,7 @@ import { DownloadCard } from "./download-card";
|
||||
import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCard } from "./model-card";
|
||||
import { ModelCardSection, ModelCardSkeleton } from "./model-card";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
@@ -101,13 +100,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,17 +128,27 @@ 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>
|
||||
<span className="font-normal text-muted-foreground">/</span>
|
||||
<span className="break-all">{name}</span>
|
||||
<CopyButton value={model.repoId} label="Copy repo ID" />
|
||||
<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} />
|
||||
<HubStateBadge state={model.hubState} />
|
||||
{update && (
|
||||
@@ -147,17 +156,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
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 +182,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,33 +242,19 @@ 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>
|
||||
</>
|
||||
) : (
|
||||
<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>
|
||||
)}
|
||||
{tab === "files" && (
|
||||
@@ -296,13 +285,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<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} />
|
||||
@@ -402,7 +391,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</SideCard>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -432,9 +421,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 +433,9 @@ function Pill({
|
||||
);
|
||||
}
|
||||
|
||||
function ExternalButton({ href, children }: { href: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<a href={href} target="_blank" rel="noreferrer" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}>
|
||||
{children}
|
||||
<ExternalLinkIcon className="opacity-60" />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
/** Card surface shared by header, content and sidebar. */
|
||||
function Panel({ className, children }: { className?: string; children: React.ReactNode }) {
|
||||
return <div className={cn("rounded-xl bg-card text-card-foreground ring-1 ring-foreground/10", className)}>{children}</div>;
|
||||
return <div className={cn("rounded-xl bg-card/55 text-card-foreground ring-1 ring-foreground/10 backdrop-blur-md", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
function SideCard({
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
|
||||
/** Remove one selected file (all parts of a split file) from the model and from disk. */
|
||||
export function RemoveFileButton({ modelId, name, paths, size, disabled, reason }: { modelId: string; name: string; paths: string[]; size: number; disabled: boolean; reason?: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`/api/models/${modelId}/files`, { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ remove: paths }) });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not remove (${res.status})`);
|
||||
toast.success(`Removing ${name}`);
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
disabled={disabled || busy}
|
||||
title={disabled ? reason : `Remove ${name}`}
|
||||
aria-label={`Remove ${name}`}
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Trash2Icon />
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove {name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{paths.length > 1 ? `All ${paths.length} parts (${formatBytes(size)})` : `The file (${formatBytes(size)})`} will be deleted from the models folder and taken out of
|
||||
this model's selection. The rest of the model stays. You can download it again later with Download more.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove}>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -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"}
|
||||
@@ -99,15 +128,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>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from "react";
|
||||
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 { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useLive } from "@/hooks/use-live";
|
||||
@@ -38,17 +39,19 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
const duration = job.startedAt != null ? ((job.finishedAt ?? now) - job.startedAt) / 1000 : null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-xl font-semibold">
|
||||
<PageHero
|
||||
title={
|
||||
<>
|
||||
{jobLabel(job)} ·{" "}
|
||||
<Link href={`/${job.repoId}`} className="hover:underline">
|
||||
{job.repoId}
|
||||
</Link>
|
||||
</h1>
|
||||
{open && (
|
||||
</>
|
||||
}
|
||||
painting={{ view: 0.5, focus: [0.3, 0.55], anchor: [0.7, 0.45] }}
|
||||
actions={
|
||||
open && (
|
||||
<Button
|
||||
className="ml-auto"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={busy || job.cancelRequested}
|
||||
@@ -60,8 +63,9 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
>
|
||||
{job.cancelRequested ? "Cancelling…" : "Cancel"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
>
|
||||
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
@@ -144,6 +148,6 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
+21
-13
@@ -2,34 +2,39 @@ import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { auth, signOut } from "@/auth";
|
||||
import { AppNav } from "@/components/app-nav";
|
||||
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
|
||||
import { BackdropProvider } from "@/components/hero/dot-painting";
|
||||
import { LabelSettingsProvider } from "@/components/labels";
|
||||
import { UserMenu } from "@/components/user-menu";
|
||||
import { WorkerIndicator } from "@/components/worker-indicator";
|
||||
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
const session = await auth();
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const [worker, fileRoles, recommendedRoles] = await Promise.all([
|
||||
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
|
||||
getWorkerStatus(),
|
||||
getFileRoleStyles(),
|
||||
getRecommendedRoles(),
|
||||
getBackdrop(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col overflow-x-clip">
|
||||
<header className="border-b">
|
||||
<div className="mx-auto flex h-14 max-w-7xl items-center gap-3 px-4 sm:gap-6">
|
||||
<Link href="/" className="flex items-center gap-2 font-semibold">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/icon.svg" alt="" className="size-6" />
|
||||
Kaname
|
||||
<span className="hidden text-xs font-normal text-muted-foreground sm:inline">{process.env.APP_VERSION ?? "dev"}</span>
|
||||
</Link>
|
||||
<AppNav />
|
||||
<div className="ml-auto flex items-center gap-3">
|
||||
{/* Floating menu: two pills (name + navigation, status + account) over the page. */}
|
||||
<header className="pointer-events-none sticky top-0 z-40">
|
||||
<div className="mx-auto flex h-16 max-w-7xl items-center justify-between gap-3 px-4 pt-3">
|
||||
<div className="pointer-events-auto flex h-12 min-w-0 items-center gap-3 rounded-2xl bg-black/80 px-3 text-white shadow-lg ring-1 ring-white/10 backdrop-blur-md sm:gap-5 dark [color-scheme:dark]">
|
||||
<Link href="/" className="flex items-center gap-2 pl-1 font-semibold">
|
||||
Kaname
|
||||
<span className="hidden text-xs font-normal text-muted-foreground sm:inline">{process.env.APP_VERSION ?? "dev"}</span>
|
||||
</Link>
|
||||
<AppNav />
|
||||
</div>
|
||||
<div className="pointer-events-auto flex h-12 items-center gap-3 rounded-2xl bg-black/80 px-3 text-white shadow-lg ring-1 ring-white/10 backdrop-blur-md dark [color-scheme:dark]">
|
||||
<CommandPaletteButton />
|
||||
<WorkerIndicator initial={worker} />
|
||||
<UserMenu
|
||||
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
|
||||
@@ -41,8 +46,11 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<CommandPalette />
|
||||
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
<BackdropProvider backdrop={backdrop}>
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
</BackdropProvider>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { LibraryHero } from "@/components/hero/library-hero";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
import { AddModelPanel, AddModelToggle } from "./add-model-panel";
|
||||
|
||||
type HeroProps = Omit<React.ComponentProps<typeof LibraryHero>, "action" | "initialWorker">;
|
||||
type PanelProps = Omit<React.ComponentProps<typeof AddModelPanel>, "open" | "setOpen">;
|
||||
|
||||
/** The hero with the "Add model" toggle, and the form it opens below. */
|
||||
export function LibraryTop({ hero, panel, worker, defaultOpen }: { hero: HeroProps; panel: PanelProps; worker: WorkerStatus; defaultOpen: boolean }) {
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
return (
|
||||
<>
|
||||
<LibraryHero {...hero} initialWorker={worker} action={<AddModelToggle open={open} onToggle={() => setOpen(!open)} />} />
|
||||
{/* Above the hero, which runs on behind what follows. */}
|
||||
<div className="relative z-10 flex flex-col gap-4 empty:hidden">
|
||||
<AddModelPanel {...panel} open={open} setOpen={setOpen} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+140
-73
@@ -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";
|
||||
@@ -9,10 +9,10 @@ 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 { 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 +27,14 @@ import {
|
||||
type Filters,
|
||||
matchesFilters,
|
||||
matchesQuery,
|
||||
queryTerms,
|
||||
type SearchableModel,
|
||||
searchText,
|
||||
} from "@/lib/search";
|
||||
import { FacetFilter } from "./facet-filter";
|
||||
|
||||
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
const PAGE_SIZES = [10, 25, 50, 100];
|
||||
|
||||
const FACET_LABEL: Record<Facet, string> = {
|
||||
author: "Author",
|
||||
@@ -44,7 +47,7 @@ const FACET_LABEL: Record<Facet, string> = {
|
||||
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
|
||||
|
||||
function toSearchable(r: LibraryRow): SearchableModel {
|
||||
return {
|
||||
const m: SearchableModel = {
|
||||
repoId: r.repoId,
|
||||
author: r.author,
|
||||
families: r.families,
|
||||
@@ -63,6 +66,7 @@ function toSearchable(r: LibraryRow): SearchableModel {
|
||||
? "update available"
|
||||
: null,
|
||||
};
|
||||
return { ...m, text: searchText(m) };
|
||||
}
|
||||
|
||||
/** Search + facet filters (kept in the URL) over the library table. */
|
||||
@@ -71,6 +75,8 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
const pathname = usePathname();
|
||||
const params = useSearchParams();
|
||||
const [query, setQuery] = useState(() => params.get("q") ?? "");
|
||||
const [page, setPage] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [filters, setFilters] = useState<Filters>(() => {
|
||||
const f = { ...EMPTY_FILTERS };
|
||||
for (const facet of FACETS) f[facet] = params.getAll(facet);
|
||||
@@ -84,25 +90,42 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
const qs = p.toString();
|
||||
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
// A new search or filter starts on the first page.
|
||||
const updateQuery = (q: string) => {
|
||||
setQuery(q);
|
||||
setPage(0);
|
||||
sync(q, filters);
|
||||
};
|
||||
const updateFilter = (facet: Facet, values: string[]) => {
|
||||
const next = { ...filters, [facet]: values };
|
||||
setFilters(next);
|
||||
setPage(0);
|
||||
sync(query, next);
|
||||
};
|
||||
const clearAll = () => {
|
||||
setQuery("");
|
||||
setFilters(EMPTY_FILTERS);
|
||||
setPage(0);
|
||||
sync("", EMPTY_FILTERS);
|
||||
};
|
||||
|
||||
// Search text and counts are computed once per change of rows, query or filters, not on every
|
||||
// render (live job progress re-renders this table while downloads run).
|
||||
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
|
||||
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
|
||||
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
|
||||
const terms = useMemo(() => queryTerms(query), [query]);
|
||||
const visible = useMemo(
|
||||
() => rows.filter((_, i) => matchesQuery(searchable[i], terms) && matchesFilters(searchable[i], filters)),
|
||||
[rows, searchable, terms, filters],
|
||||
);
|
||||
const facetOptions = useMemo(
|
||||
() => Object.fromEntries(FACETS.map((facet) => [facet, facetCounts(searchable, facet, terms, filters)])) as Record<Facet, [string, number][]>,
|
||||
[searchable, terms, filters],
|
||||
);
|
||||
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
|
||||
const pages = Math.max(1, Math.ceil(visible.length / pageSize));
|
||||
const current = Math.min(page, pages - 1);
|
||||
const shown = visible.slice(current * pageSize, (current + 1) * pageSize);
|
||||
|
||||
const { snapshot } = useLive();
|
||||
const openJobs = new Map<string, JobSnapshot>();
|
||||
@@ -111,86 +134,76 @@ 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>}
|
||||
@@ -206,19 +219,31 @@ 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}>
|
||||
<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} />
|
||||
@@ -241,8 +266,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,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,25 @@
|
||||
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { DownloadIcon, PaletteIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { SettingsNav } from "./settings-nav";
|
||||
|
||||
const SECTIONS = [
|
||||
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
|
||||
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
|
||||
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
|
||||
{ href: "/settings/appearance", label: "Appearance", icon: <PaletteIcon className="size-4" /> },
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">Settings</h1>
|
||||
<PageHero
|
||||
title="Settings"
|
||||
description="File labels, tags, how Kaname downloads and scans models, and the background picture."
|
||||
painting={{ view: 0.4, focus: [0.5, 0.43], anchor: [0.7, 0.4] }}
|
||||
>
|
||||
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
|
||||
<SettingsNav sections={SECTIONS} />
|
||||
<div className="min-w-0">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageHero>
|
||||
);
|
||||
}
|
||||
@@ -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,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,
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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,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();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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,229 @@
|
||||
"use client";
|
||||
|
||||
import { Dialog } from "@base-ui/react/dialog";
|
||||
import {
|
||||
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: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;
|
||||
@@ -31,21 +35,3 @@ export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
if (ok) toast.success("Update queued");
|
||||
return ok;
|
||||
}
|
||||
|
||||
export async function approveJob(jobId: string): Promise<boolean> {
|
||||
const ok = await post(`/api/jobs/${jobId}/approve`);
|
||||
if (ok) toast.success("Approved; the download is queued");
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Returns whether the model left the library (it was only added by this request), or null on error. */
|
||||
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> {
|
||||
const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return null;
|
||||
}
|
||||
toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected");
|
||||
return body;
|
||||
}
|
||||
@@ -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,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -9,7 +9,7 @@ const buttonVariants = cva(
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
outline:
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-background/80 dark:backdrop-blur-sm dark:hover:bg-input/60",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||
ghost:
|
||||
|
||||
@@ -11,7 +11,7 @@ function Card({
|
||||
data-slot="card"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card/55 py-(--card-spacing) backdrop-blur-md text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -22,7 +22,7 @@ function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
className={cn("bg-muted/40 [&_tr]:border-b [&_tr]:hover:bg-transparent", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
@@ -69,7 +69,7 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
||||
"h-9 px-2 text-left align-middle text-xs font-medium tracking-wide whitespace-nowrap text-muted-foreground uppercase first:pl-4 last:pr-4 [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -82,7 +82,7 @@ function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
|
||||
"p-2 align-middle whitespace-nowrap first:pl-4 last:pr-4 [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -43,10 +43,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
aria-label="Account menu"
|
||||
className="flex items-center gap-2 rounded-full p-0.5 outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 sm:pr-3"
|
||||
title={user.name ?? user.email ?? undefined}
|
||||
className="flex items-center rounded-full p-0.5 outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
>
|
||||
<UserAvatar user={user} />
|
||||
<span className="hidden max-w-40 truncate text-sm sm:inline">{user.name ?? user.email}</span>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<div className="flex items-center gap-3 px-1.5 py-2">
|
||||
|
||||
@@ -1,33 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useWorkerStatus } from "@/hooks/use-live";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
/** Polls /api/status and shows whether the background worker is alive. */
|
||||
/** Shows whether the background worker is alive (from the page's live poll, or /api/status). */
|
||||
export function WorkerIndicator({ initial }: { initial: WorkerStatus }) {
|
||||
const [status, setStatus] = useState(initial);
|
||||
|
||||
useEffect(() => {
|
||||
const tick = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/status", { cache: "no-store" });
|
||||
if (res.ok) setStatus((await res.json()).worker);
|
||||
} catch {
|
||||
// keep last known state
|
||||
}
|
||||
};
|
||||
const id = setInterval(tick, 10_000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
const status = useWorkerStatus(initial);
|
||||
|
||||
// Online: just a green dot (details on hover); offline stays spelled out.
|
||||
if (status.online) {
|
||||
return (
|
||||
<span
|
||||
role="status"
|
||||
aria-label="Worker online"
|
||||
title={`Worker online${status.hfVersion ? ` · ${status.hfVersion}` : " · hf CLI not found"}`}
|
||||
className="flex size-6 items-center justify-center"
|
||||
>
|
||||
<span className="size-2 rounded-full bg-emerald-500 shadow-[0_0_6px] shadow-emerald-500/70" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge
|
||||
variant={status.online ? "secondary" : "destructive"}
|
||||
title={status.hfVersion ?? (status.online ? "hf CLI not found" : undefined)}
|
||||
>
|
||||
<span className={`size-1.5 rounded-full ${status.online ? "bg-emerald-500" : "bg-destructive"}`} />
|
||||
Worker {status.online ? "online" : "offline"}
|
||||
<Badge variant="destructive" role="status">
|
||||
<span className="size-1.5 rounded-full bg-destructive" />
|
||||
Worker offline
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
+22
-47
@@ -1,58 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs";
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import type { LiveQuery } from "@/lib/live-protocol";
|
||||
import { EMPTY_LIVE, type LiveState, liveStore } from "@/lib/live-store";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] };
|
||||
|
||||
export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"];
|
||||
const MAX_LOG_LINES = 5000;
|
||||
|
||||
/**
|
||||
* Subscribe to /api/stream. Re-renders on every snapshot; refreshes server components
|
||||
* (model status, library) when a job reaches a terminal state.
|
||||
* Live job state for a query (see src/lib/live-store.ts). Components showing the same query share
|
||||
* one poller. When a job reaches a terminal state, server components are refreshed (model status,
|
||||
* library).
|
||||
*/
|
||||
export function useLive(query: { model?: string; job?: string } = {}, withLogs = false) {
|
||||
export function useLive(query: LiveQuery = {}, withLogs = false): LiveState {
|
||||
const router = useRouter();
|
||||
const [snapshot, setSnapshot] = useState<LiveSnapshot | null>(null);
|
||||
const [logs, setLogs] = useState<LogLine[]>([]);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const states = useRef(new Map<string, string>());
|
||||
const { model, job } = query;
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => liveStore().subscribe({ model, job }, withLogs, listener, () => router.refresh()),
|
||||
[model, job, withLogs, router],
|
||||
);
|
||||
const getSnapshot = useCallback(() => liveStore().get({ model, job }, withLogs), [model, job, withLogs]);
|
||||
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (query.model) params.set("model", query.model);
|
||||
if (query.job) params.set("job", query.job);
|
||||
const url = `/api/stream${params.size ? `?${params}` : ""}`;
|
||||
const getServerSnapshot = () => EMPTY_LIVE;
|
||||
const subscribeWorker = (listener: () => void) => liveStore().subscribeWorker(listener);
|
||||
const getWorker = () => liveStore().getWorker();
|
||||
const noWorker = () => null;
|
||||
|
||||
useEffect(() => {
|
||||
const es = new EventSource(url);
|
||||
es.onopen = () => setConnected(true);
|
||||
es.onerror = () => setConnected(false);
|
||||
es.addEventListener("snapshot", (e) => {
|
||||
const snap = JSON.parse((e as MessageEvent).data) as LiveSnapshot;
|
||||
let finished = false;
|
||||
for (const j of snap.jobs) {
|
||||
const prev = states.current.get(j.id);
|
||||
if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true;
|
||||
states.current.set(j.id, j.state);
|
||||
}
|
||||
setSnapshot(snap);
|
||||
if (finished) router.refresh();
|
||||
});
|
||||
if (withLogs) {
|
||||
es.addEventListener("logs", (e) => {
|
||||
const lines = JSON.parse((e as MessageEvent).data) as LogLine[];
|
||||
setLogs((prev) => {
|
||||
const seen = prev.length ? prev[prev.length - 1].id : 0;
|
||||
const merged = prev.concat(lines.filter((l) => l.id > seen));
|
||||
return merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged;
|
||||
});
|
||||
});
|
||||
}
|
||||
return () => es.close();
|
||||
}, [url, withLogs, router]);
|
||||
|
||||
return { snapshot, logs, connected };
|
||||
/** The worker status: from the live poll when one runs, otherwise /api/status every 10 s. */
|
||||
export function useWorkerStatus(initial: WorkerStatus): WorkerStatus {
|
||||
return useSyncExternalStore(subscribeWorker, getWorker, noWorker) ?? initial;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { parseBackdrop } from "./backdrop";
|
||||
|
||||
const valid = { w: 10, h: 8, dots: "0123456789abcdef".repeat(5), focus: [0.3, 0.7] };
|
||||
|
||||
test("parseBackdrop keeps a valid grid", () => {
|
||||
assert.deepEqual(parseBackdrop(valid), valid);
|
||||
});
|
||||
|
||||
test("parseBackdrop rejects broken grids", () => {
|
||||
assert.equal(parseBackdrop(null), null);
|
||||
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.slice(1) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.replace("a", "g") }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, w: 4, dots: "0".repeat(32) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, w: 241, dots: "0".repeat(241 * 8) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, focus: [0.5, 1.5] }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, focus: [0.5] }), null);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// A custom picture for the dot painting behind every page header (Settings → Appearance). Stored as
|
||||
// a brightness grid like the built-in painting; the uploaded photo itself is never sent or kept.
|
||||
|
||||
export const BACKDROP_KEY = "appearance.backdrop";
|
||||
/** Longest side of the grid, in cells. */
|
||||
export const BACKDROP_MAX_CELLS = 240;
|
||||
|
||||
export type Backdrop = {
|
||||
w: number;
|
||||
h: number;
|
||||
/** w×h brightness levels 0–f, row by row. */
|
||||
dots: string;
|
||||
/** The point (x, y as fractions of the picture) kept in view when the header crops it. */
|
||||
focus: [number, number];
|
||||
};
|
||||
|
||||
const fraction = (v: unknown) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
const side = (v: unknown) => Number.isInteger(v) && (v as number) >= 8 && (v as number) <= BACKDROP_MAX_CELLS;
|
||||
|
||||
/** The backdrop if `v` is a valid one, else null. */
|
||||
export function parseBackdrop(v: unknown): Backdrop | null {
|
||||
if (!v || typeof v !== "object") return null;
|
||||
const { w, h, dots, focus } = v as Record<string, unknown>;
|
||||
if (!side(w) || !side(h)) return null;
|
||||
if (typeof dots !== "string" || dots.length !== (w as number) * (h as number) || !/^[0-9a-f]*$/.test(dots)) return null;
|
||||
if (!Array.isArray(focus) || focus.length !== 2 || !focus.every(fraction)) return null;
|
||||
return { w: w as number, h: h as number, dots, focus: [focus[0], focus[1]] };
|
||||
}
|
||||
+48
-11
@@ -1,9 +1,10 @@
|
||||
import "server-only";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, gt, inArray, or, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { runDir } from "@/lib/benchmark-paths";
|
||||
import { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, endpoints, QUALITY_SECTIONS } from "@/lib/db/schema";
|
||||
import { probeEndpoint } from "@/lib/endpoint-probe";
|
||||
@@ -95,7 +96,8 @@ export async function createBenchmark(input: BenchmarkInput) {
|
||||
return row;
|
||||
}
|
||||
|
||||
const listColumns = {
|
||||
/** Everything about a run: the detail and compare pages, results downloads. */
|
||||
const runColumns = {
|
||||
id: benchmarkRuns.id,
|
||||
endpointId: benchmarkRuns.endpointId,
|
||||
modelId: benchmarkRuns.modelId,
|
||||
@@ -123,10 +125,37 @@ const listColumns = {
|
||||
createdAt: benchmarkRuns.createdAt,
|
||||
};
|
||||
|
||||
export type BenchmarkRow = Awaited<ReturnType<typeof listBenchmarks>>[number];
|
||||
/**
|
||||
* What lists show: no A/B series, eval items, hardware facts or descriptions (lists got all of it,
|
||||
* ~13× what they use, re-fetched every 3 s while a run was active). The summary is read only to
|
||||
* compute the headline numbers.
|
||||
*/
|
||||
const listColumns = {
|
||||
id: benchmarkRuns.id,
|
||||
endpointId: benchmarkRuns.endpointId,
|
||||
endpointBId: benchmarkRuns.endpointBId,
|
||||
modelId: benchmarkRuns.modelId,
|
||||
label: benchmarkRuns.label,
|
||||
kind: benchmarkRuns.kind,
|
||||
settings: benchmarkRuns.settings,
|
||||
snapshot: benchmarkRuns.snapshot,
|
||||
state: benchmarkRuns.state,
|
||||
phase: benchmarkRuns.phase,
|
||||
cancelRequestedAt: benchmarkRuns.cancelRequestedAt,
|
||||
startedAt: benchmarkRuns.startedAt,
|
||||
finishedAt: benchmarkRuns.finishedAt,
|
||||
hasReport: benchmarkRuns.hasReport,
|
||||
createdAt: benchmarkRuns.createdAt,
|
||||
summary: benchmarkRuns.summary,
|
||||
qualityScore: sql<number | null>`json_extract(${benchmarkRuns.quality}, '$.score')`,
|
||||
};
|
||||
|
||||
export async function listBenchmarks(filter: { endpointId?: string; modelId?: string } = {}) {
|
||||
return db()
|
||||
export type BenchmarkRow = NonNullable<Awaited<ReturnType<typeof getBenchmark>>>;
|
||||
export type BenchmarkListRow = Awaited<ReturnType<typeof listBenchmarks>>[number];
|
||||
|
||||
/** Runs for lists, newest first; `endpointId` matches either side of an A/B. */
|
||||
export async function listBenchmarks(filter: { endpointId?: string; modelId?: string } = {}, options: { limit?: number } = {}) {
|
||||
let query = db()
|
||||
.select(listColumns)
|
||||
.from(benchmarkRuns)
|
||||
.where(
|
||||
@@ -135,23 +164,31 @@ export async function listBenchmarks(filter: { endpointId?: string; modelId?: st
|
||||
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(benchmarkRuns.createdAt));
|
||||
.orderBy(desc(benchmarkRuns.createdAt))
|
||||
.$dynamic();
|
||||
if (options.limit) query = query.limit(options.limit);
|
||||
return (await query).map(({ summary, ...r }) => ({ ...r, headline: headline(summary) }));
|
||||
}
|
||||
|
||||
export async function getBenchmark(id: string) {
|
||||
const [row] = await db().select(listColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
|
||||
const [row] = await db().select(runColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function getBenchmarks(ids: string[]) {
|
||||
if (ids.length === 0) return [];
|
||||
const rows = await db().select(listColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
|
||||
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
|
||||
const rows = await db().select(runColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
|
||||
const byId = new Map(rows.map((r) => [r.id, r]));
|
||||
return ids.map((id) => byId.get(id)).filter((r) => r != null);
|
||||
}
|
||||
|
||||
async function runState(id: string) {
|
||||
return db().query.benchmarkRuns.findFirst({ columns: { id: true, state: true }, where: eq(benchmarkRuns.id, id) });
|
||||
}
|
||||
|
||||
/** Queued runs are cancelled right away; a running one is stopped by the worker. */
|
||||
export async function cancelBenchmark(id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
const run = await runState(id);
|
||||
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
|
||||
if (run.state === "queued") {
|
||||
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, run.state)));
|
||||
@@ -172,7 +209,7 @@ export async function updateBenchmark(id: string, patch: { label?: string | null
|
||||
|
||||
/** Deletes the run, its log and its files. Cancel a running one first. */
|
||||
export async function deleteBenchmark(id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
const run = await runState(id);
|
||||
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
|
||||
if (run.state === "running") throw new BenchmarkError("busy", "Cancel the run before deleting it.", 409);
|
||||
await db().delete(benchmarkLogs).where(eq(benchmarkLogs.runId, id));
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// Enum values stored in text columns (see schema.ts), with their types. No imports: client
|
||||
// components may use these, unlike schema.ts, whose table definitions pull in drizzle-orm.
|
||||
|
||||
// Models
|
||||
|
||||
export const MODEL_STATUSES = [
|
||||
"pending", // added, nothing downloaded yet
|
||||
"downloading",
|
||||
"ready", // all selected files present at pinned SHA
|
||||
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
|
||||
"failed", // last download failed
|
||||
"deleting",
|
||||
] as const;
|
||||
export type ModelStatus = (typeof MODEL_STATUSES)[number];
|
||||
|
||||
/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */
|
||||
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
|
||||
export type HubState = (typeof HUB_STATES)[number];
|
||||
|
||||
export const MODEL_FILE_STATES = [
|
||||
"pending", // not downloaded yet / not checked
|
||||
"present", // exists with the expected size
|
||||
"missing",
|
||||
"size_mismatch",
|
||||
"hash_mismatch",
|
||||
"verified", // deep verify: hash matches
|
||||
] as const;
|
||||
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
|
||||
|
||||
// Jobs
|
||||
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
/** Download purposes; "remove" is a delete job that removes only some files (the model stays). */
|
||||
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update", "remove"] as const;
|
||||
export type JobPurpose = (typeof JOB_PURPOSES)[number];
|
||||
|
||||
export const JOB_STATES = [
|
||||
"queued",
|
||||
"downloading",
|
||||
"verifying",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
] as const;
|
||||
export type JobState = (typeof JOB_STATES)[number];
|
||||
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
|
||||
|
||||
export const JOB_ERROR_CODES = [
|
||||
"auth", // invalid/missing token
|
||||
"gated", // gated repo, access not granted
|
||||
"repo_not_found",
|
||||
"revision_not_found",
|
||||
"disk_full",
|
||||
"network",
|
||||
"size_mismatch", // finished but files don't match expected sizes
|
||||
"unknown",
|
||||
] as const;
|
||||
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
|
||||
|
||||
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
|
||||
export type JobFileState = (typeof JOB_FILE_STATES)[number];
|
||||
|
||||
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
|
||||
export type LogStream = (typeof LOG_STREAMS)[number];
|
||||
|
||||
// Endpoints and benchmarks
|
||||
|
||||
export const ENDPOINT_ENGINES = ["llama.cpp", "vllm", "sglang", "ollama", "other"] as const;
|
||||
export type EndpointEngine = (typeof ENDPOINT_ENGINES)[number];
|
||||
|
||||
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
|
||||
|
||||
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
|
||||
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
|
||||
|
||||
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
|
||||
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
|
||||
|
||||
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
|
||||
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
|
||||
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
|
||||
|
||||
/**
|
||||
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
|
||||
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
|
||||
* published / failed.
|
||||
*/
|
||||
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
|
||||
export type PublicationState = (typeof PUBLICATION_STATES)[number];
|
||||
+38
-88
@@ -8,6 +8,28 @@ import {
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
import { ulid } from "ulid";
|
||||
import {
|
||||
BENCHMARK_KINDS,
|
||||
type BenchmarkPhase,
|
||||
BENCHMARK_STATES,
|
||||
ENDPOINT_ENGINES,
|
||||
type EndpointEngine,
|
||||
HUB_STATES,
|
||||
JOB_ERROR_CODES,
|
||||
JOB_FILE_STATES,
|
||||
JOB_KINDS,
|
||||
JOB_PURPOSES,
|
||||
JOB_STATES,
|
||||
LOG_STREAMS,
|
||||
MODEL_FILE_STATES,
|
||||
MODEL_STATUSES,
|
||||
PUBLICATION_STATES,
|
||||
type QualitySection,
|
||||
} from "./enums";
|
||||
|
||||
// The enum arrays live in ./enums (no dependencies), so client components can use them without
|
||||
// pulling drizzle-orm and every table definition into the browser bundle.
|
||||
export * from "./enums";
|
||||
|
||||
// Conventions (keep these when adding tables in later steps, they keep a Postgres port simple):
|
||||
// - Primary keys are ULID strings, generated in the app, never reused.
|
||||
@@ -36,20 +58,6 @@ const ts = (name: string) => integer(name, { mode: "timestamp_ms" });
|
||||
// Models
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const MODEL_STATUSES = [
|
||||
"pending", // added, nothing downloaded yet
|
||||
"downloading",
|
||||
"ready", // all selected files present at pinned SHA
|
||||
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
|
||||
"failed", // last download failed
|
||||
"deleting",
|
||||
] as const;
|
||||
export type ModelStatus = (typeof MODEL_STATUSES)[number];
|
||||
|
||||
/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */
|
||||
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
|
||||
export type HubState = (typeof HUB_STATES)[number];
|
||||
|
||||
export type UpdateDiffFile = { path: string; size: number; oldSize?: number };
|
||||
export type UpdateDiff = {
|
||||
/** Commit the diff was computed against (the tracked revision's head on the Hub). */
|
||||
@@ -68,8 +76,10 @@ export type JobResult = {
|
||||
hashMismatch?: string[];
|
||||
/** Files in the model folder that aren't selected repo files. */
|
||||
extra?: { path: string; size: number; inRepo: boolean }[];
|
||||
/** Update jobs: files of the old revision to delete once the download succeeded. */
|
||||
/** Update jobs: files of the old revision to delete once the download succeeded. Remove jobs: the files to delete. */
|
||||
removePaths?: string[];
|
||||
/** Remove jobs: what was actually deleted. */
|
||||
removed?: string[];
|
||||
/** Delete jobs: files that were kept because they don't belong to the repo. */
|
||||
kept?: string[];
|
||||
};
|
||||
@@ -179,16 +189,6 @@ export const modelRevisions = sqliteTable(
|
||||
(t) => [index("model_revisions_model_idx").on(t.modelId)],
|
||||
);
|
||||
|
||||
export const MODEL_FILE_STATES = [
|
||||
"pending", // not downloaded yet / not checked
|
||||
"present", // exists with the expected size
|
||||
"missing",
|
||||
"size_mismatch",
|
||||
"hash_mismatch",
|
||||
"verified", // deep verify: hash matches
|
||||
] as const;
|
||||
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
|
||||
|
||||
/** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */
|
||||
export const modelFiles = sqliteTable(
|
||||
"model_files",
|
||||
@@ -216,36 +216,6 @@ export const modelFiles = sqliteTable(
|
||||
// Jobs (executed by the worker)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const;
|
||||
export type JobPurpose = (typeof JOB_PURPOSES)[number];
|
||||
|
||||
export const JOB_STATES = [
|
||||
"queued",
|
||||
"downloading",
|
||||
"verifying",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
] as const;
|
||||
export type JobState = (typeof JOB_STATES)[number];
|
||||
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
|
||||
|
||||
export const JOB_ERROR_CODES = [
|
||||
"auth", // invalid/missing token
|
||||
"gated", // gated repo, access not granted
|
||||
"repo_not_found",
|
||||
"revision_not_found",
|
||||
"disk_full",
|
||||
"network",
|
||||
"size_mismatch", // finished but files don't match expected sizes
|
||||
"unknown",
|
||||
] as const;
|
||||
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
|
||||
|
||||
export const jobs = sqliteTable(
|
||||
"jobs",
|
||||
{
|
||||
@@ -273,12 +243,14 @@ export const jobs = sqliteTable(
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)],
|
||||
(t) => [
|
||||
index("jobs_state_idx").on(t.state),
|
||||
index("jobs_model_idx").on(t.modelId),
|
||||
// The live view polls open jobs plus recently finished ones once a second.
|
||||
index("jobs_finished_idx").on(t.finishedAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
|
||||
export type JobFileState = (typeof JOB_FILE_STATES)[number];
|
||||
|
||||
export const jobFiles = sqliteTable(
|
||||
"job_files",
|
||||
{
|
||||
@@ -296,9 +268,6 @@ export const jobFiles = sqliteTable(
|
||||
(t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })],
|
||||
);
|
||||
|
||||
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
|
||||
export type LogStream = (typeof LOG_STREAMS)[number];
|
||||
|
||||
export const jobLogs = sqliteTable(
|
||||
"job_logs",
|
||||
{
|
||||
@@ -352,7 +321,7 @@ export type PcieLink = { gen: number | null; width: number | null };
|
||||
|
||||
/**
|
||||
* Folders in MODELS_DIR (`<org>/<name>`, like `hf download --local-dir` layouts) that no model uses,
|
||||
* found by the worker's scan. Rewritten on every scan; the web app offers them for import.
|
||||
* found by the worker's scan, which writes only what changed; the web app offers them for import.
|
||||
*/
|
||||
export const localFolders = sqliteTable("local_folders", {
|
||||
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-8B-GGUF". */
|
||||
@@ -363,6 +332,7 @@ export const localFolders = sqliteTable("local_folders", {
|
||||
totalBytes: integer("total_bytes").notNull(),
|
||||
/** Commit from hf's download metadata, if the folder was written by `hf download`. */
|
||||
commit: text("commit"),
|
||||
/** When a scan last wrote this folder (found it, or found it changed). */
|
||||
scannedAt: ts("scanned_at").notNull(),
|
||||
});
|
||||
|
||||
@@ -422,9 +392,6 @@ export type DeploymentOptions = {
|
||||
// Endpoints: OpenAI-compatible servers to benchmark (llama.cpp, vLLM, SGLang, …), run elsewhere
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const ENDPOINT_ENGINES = ["llama.cpp", "vllm", "sglang", "ollama", "other"] as const;
|
||||
export type EndpointEngine = (typeof ENDPOINT_ENGINES)[number];
|
||||
|
||||
/**
|
||||
* What runs behind an endpoint, as the user describes it (Kaname can't see that machine). Copied into
|
||||
* every run; goes into BetterBench notes and launch80. Nothing here may identify the host.
|
||||
@@ -496,12 +463,6 @@ export const endpoints = sqliteTable(
|
||||
// Benchmarks (BetterBench runs against an endpoint)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
|
||||
|
||||
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
|
||||
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
|
||||
|
||||
/** What a run measures. `passes`/`warmup` null: BetterBench's defaults (20 / 3), or 5 / 1 with quick. */
|
||||
export type BenchmarkSettings = {
|
||||
quick: boolean;
|
||||
@@ -515,9 +476,6 @@ export type BenchmarkSettings = {
|
||||
evalSections?: QualitySection[];
|
||||
};
|
||||
|
||||
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
|
||||
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
|
||||
|
||||
/** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */
|
||||
export type QualityResult = {
|
||||
/** The eval set's version; only results of the same version are comparable. */
|
||||
@@ -536,10 +494,6 @@ export type QualityResult = {
|
||||
config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null };
|
||||
};
|
||||
|
||||
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
|
||||
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
|
||||
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
|
||||
|
||||
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */
|
||||
export type PairedResult = {
|
||||
metric: string;
|
||||
@@ -770,7 +724,11 @@ export const benchmarkRuns = sqliteTable(
|
||||
description: text("description"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
|
||||
(t) => [
|
||||
index("benchmark_runs_created_idx").on(t.createdAt),
|
||||
// The worker looks for the next queued run every 2 s.
|
||||
index("benchmark_runs_state_idx").on(t.state, t.createdAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const benchmarkLogs = sqliteTable(
|
||||
@@ -789,14 +747,6 @@ export const benchmarkLogs = sqliteTable(
|
||||
// launch80 publications (double opt-in: a dry-run preview, then an explicit confirmation)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
|
||||
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
|
||||
* published / failed.
|
||||
*/
|
||||
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
|
||||
export type PublicationState = (typeof PUBLICATION_STATES)[number];
|
||||
|
||||
export const benchmarkPublications = sqliteTable(
|
||||
"benchmark_publications",
|
||||
{
|
||||
|
||||
@@ -129,3 +129,38 @@ describe("queuing runs", () => {
|
||||
assert.equal(run!.snapshotB && "model" in run!.snapshotB ? run!.snapshotB.model : null, "Qwen/Qwen3-8B");
|
||||
});
|
||||
});
|
||||
|
||||
describe("listing runs", () => {
|
||||
it("lists headline numbers and the quality score, not the heavy results", async () => {
|
||||
const { benchmarkRuns } = M.schema;
|
||||
const snapshot = { type: "endpoint" as const, endpointName: "x", model: "m", engine: null, engineVersion: null, contextSize: null, hardware: {} };
|
||||
const settings = { quick: false, passes: null, warmup: null, phases: [] };
|
||||
const summary = {
|
||||
v: 2,
|
||||
combined: { decode: 42.5, ttft_p50: 120, itl_low1: null, update_p50: null, update_p99: null },
|
||||
single: [],
|
||||
prefill: [{ target_depth: 4000, skipped: false, pp_med: 900 }],
|
||||
concurrency: [{ level: 4, ok: 4, requests: 4, aggregate_tps: 150, ttft_p50: null, ttft_p99: null, decode_med: null }],
|
||||
phases: [],
|
||||
cacheHits: 0,
|
||||
betterbenchVersion: "0.6.1",
|
||||
corpusVersion: "v1",
|
||||
passes: null,
|
||||
quick: false,
|
||||
};
|
||||
const quality = { evalSet: "v1", score: 71, sections: [], items: [{ section: "tools" as const, id: "t1", pass: true }], config: { temperature: 0, seed: 1, thinking: false, contextTokens: null } };
|
||||
await M.db.db().insert(benchmarkRuns).values([
|
||||
{ kind: "run", state: "completed", settings, snapshot, summary, createdAt: new Date(Date.now() + 1000) },
|
||||
{ kind: "eval", state: "completed", settings, snapshot, quality, createdAt: new Date(Date.now() + 2000) },
|
||||
]);
|
||||
const rows = await M.benchmarks.listBenchmarks();
|
||||
const evalRow = rows.find((r) => r.kind === "eval")!;
|
||||
const runRow = rows.find((r) => r.kind === "run" && r.headline.decode != null)!;
|
||||
assert.equal(evalRow.qualityScore, 71);
|
||||
assert.deepEqual(runRow.headline, { decode: 42.5, ttftMs: 120, prefill: { tps: 900, depth: 4000 }, peak: { tps: 150, level: 4 } });
|
||||
for (const r of rows) for (const k of ["summary", "quality", "ab", "meta", "metaB", "system", "description", "snapshotB"]) assert.ok(!(k in r), k);
|
||||
const [newest] = await M.benchmarks.listBenchmarks({}, { limit: 1 });
|
||||
assert.equal(newest.id, evalRow.id, "newest first, limited");
|
||||
assert.equal((await M.benchmarks.getBenchmark(evalRow.id))!.quality?.items.length, 1, "the detail still has everything");
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import { and, asc, eq, isNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema";
|
||||
import { computeUpdateDiff } from "@/lib/update-diff";
|
||||
import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client";
|
||||
import { HubError, listFiles, resolveRevision, SHA_RE } from "./client";
|
||||
|
||||
type CheckedModel = Pick<
|
||||
typeof models.$inferSelect,
|
||||
@@ -45,7 +45,7 @@ const isGated = (err: unknown) => err instanceof HubError && (err.code === "gate
|
||||
/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */
|
||||
async function resolve(repoId: string, revision: string): Promise<string | null> {
|
||||
try {
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
return await resolveRevision(repoId, revision);
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "revision_not_found") return null;
|
||||
throw err;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Hub client: the per-commit tree cache and the SHA-only revision lookup, against a stubbed fetch.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { after, beforeEach, describe, it } from "node:test";
|
||||
import { HubError, listFiles, resolveRevision } from "./client";
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
let requests: string[] = [];
|
||||
let respond: (url: string) => Response;
|
||||
|
||||
const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });
|
||||
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = String(input instanceof Request ? input.url : input);
|
||||
requests.push(url);
|
||||
return respond(url);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
const SHA = "a".repeat(40);
|
||||
const tree = [
|
||||
{ type: "file", path: "b.gguf", size: 2, oid: "o2" },
|
||||
{ type: "directory", path: "sub", size: 0, oid: "d" },
|
||||
{ type: "file", path: "a.gguf", size: 1, oid: "o1", lfs: { oid: "f".repeat(64), size: 1 } },
|
||||
];
|
||||
|
||||
describe("listFiles", () => {
|
||||
it("downloads a commit's tree once and hands out copies", async () => {
|
||||
respond = () => json(tree);
|
||||
const first = await listFiles("org/cached", SHA);
|
||||
assert.deepEqual(first.map((f) => f.path), ["a.gguf", "b.gguf"]);
|
||||
first.pop();
|
||||
const second = await listFiles("org/cached", SHA);
|
||||
assert.equal(second.length, 2, "the cached list isn't changed by callers");
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
|
||||
it("doesn't cache a branch name (it can move)", async () => {
|
||||
respond = () => json(tree);
|
||||
await listFiles("org/branch", "main");
|
||||
await listFiles("org/branch", "main");
|
||||
assert.equal(requests.length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveRevision", () => {
|
||||
it("asks only for the SHA", async () => {
|
||||
respond = () => json({ _id: "x", id: "org/repo", sha: SHA });
|
||||
assert.equal(await resolveRevision("org/repo", "main"), SHA);
|
||||
assert.deepEqual(requests, ["https://huggingface.co/api/models/org/repo/revision/main?expand=sha"]);
|
||||
});
|
||||
|
||||
it("falls back to the full model info when the answer has no SHA", async () => {
|
||||
respond = (url) => (url.endsWith("?expand=sha") ? json({ id: "org/repo" }) : json({ id: "org/repo", sha: SHA }));
|
||||
assert.equal(await resolveRevision("org/repo", "main"), SHA);
|
||||
assert.deepEqual(requests, [
|
||||
"https://huggingface.co/api/models/org/repo/revision/main?expand=sha",
|
||||
"https://huggingface.co/api/models/org/repo/revision/main",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a missing repo or revision like the full lookup", async () => {
|
||||
respond = () => json({ error: "nope" }, 404, { "x-error-code": "RevisionNotFound" });
|
||||
await assert.rejects(resolveRevision("org/repo", "gone"), (err) => err instanceof HubError && err.code === "revision_not_found");
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
});
|
||||
+45
-2
@@ -160,9 +160,50 @@ type TreeEntry = {
|
||||
xetHash?: string;
|
||||
};
|
||||
|
||||
/** All files (recursive) at a commit. Follows the Link header for pagination. */
|
||||
/**
|
||||
* The commit a revision points to. Asks the Hub for just the SHA (`expand=sha`, as huggingface_hub's
|
||||
* model_info does): the full model info can be large (file list, card data, the Spaces using it).
|
||||
* Falls back to the full info if an answer comes without a SHA.
|
||||
*/
|
||||
export async function resolveRevision(repoId: string, revision: string): Promise<string> {
|
||||
assertRepoId(repoId);
|
||||
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}?expand=sha`);
|
||||
if (res.ok) {
|
||||
const j = (await res.json().catch(() => null)) as { sha?: unknown } | null;
|
||||
if (typeof j?.sha === "string" && SHA_RE.test(j.sha)) return j.sha;
|
||||
} else if (res.status !== 400) {
|
||||
throw await toHubError(res, repoId, revision);
|
||||
}
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
}
|
||||
|
||||
// A commit's file list never changes, so the last few are kept: adding a model right after looking
|
||||
// it up doesn't download its tree again. Capped by the number of files held.
|
||||
const treeCache = new Map<string, HubFile[]>();
|
||||
const TREE_CACHE_MAX_FILES = 50_000;
|
||||
let treeCacheFiles = 0;
|
||||
|
||||
function rememberTree(key: string, files: HubFile[]) {
|
||||
if (files.length > TREE_CACHE_MAX_FILES) return;
|
||||
treeCache.set(key, files);
|
||||
treeCacheFiles += files.length;
|
||||
for (const [k, v] of treeCache) {
|
||||
if (treeCacheFiles <= TREE_CACHE_MAX_FILES) break;
|
||||
treeCache.delete(k);
|
||||
treeCacheFiles -= v.length;
|
||||
}
|
||||
}
|
||||
|
||||
/** All files (recursive) at a commit, sorted by path. Follows the Link header for pagination. */
|
||||
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
|
||||
assertRepoId(repoId);
|
||||
const key = `${repoId}@${sha}`;
|
||||
const cached = treeCache.get(key);
|
||||
if (cached) {
|
||||
treeCache.delete(key); // most recently used last
|
||||
treeCache.set(key, cached);
|
||||
return [...cached];
|
||||
}
|
||||
const files: HubFile[] = [];
|
||||
let url: string | null =
|
||||
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
|
||||
@@ -181,7 +222,9 @@ export async function listFiles(repoId: string, sha: string): Promise<HubFile[]>
|
||||
}
|
||||
url = nextLink(res.headers.get("link"));
|
||||
}
|
||||
return files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
if (SHA_RE.test(sha)) rememberTree(key, files);
|
||||
return [...files];
|
||||
}
|
||||
|
||||
function nextLink(link: string | null): string | null {
|
||||
|
||||
@@ -12,5 +12,6 @@ const KIND: Record<string, string> = { download: "Download", verify: "Verify", d
|
||||
|
||||
export function jobLabel(job: { kind: string; purpose: string | null }): string {
|
||||
if (job.kind === "download") return DOWNLOAD_PURPOSE[job.purpose ?? "initial"] ?? "Download";
|
||||
if (job.kind === "delete" && job.purpose === "remove") return "Remove files";
|
||||
return KIND[job.kind] ?? job.kind;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// The /api/live protocol, shared by the route handler and the browser's live store. Types only and
|
||||
// pure helpers: safe to import from client components.
|
||||
|
||||
import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] };
|
||||
|
||||
/** `model`: jobs of one model; `job`: one job; neither: open and recently finished jobs. */
|
||||
export type LiveQuery = { model?: string; job?: string };
|
||||
|
||||
/** `snapshot` is left out when it is the version the client already has (`v` in the request). */
|
||||
export type LiveResponse = { v: string; snapshot?: LiveSnapshot; logs?: LogLine[] };
|
||||
|
||||
/**
|
||||
* The poll URL. `logAfter` (job queries only): log lines after that id, 0 for the last ones; leave it
|
||||
* out for no logs. `v`: the snapshot version the client has.
|
||||
*/
|
||||
export function liveUrl(query: LiveQuery, opts: { logAfter?: number | null; v?: string | null } = {}): string {
|
||||
const p = new URLSearchParams();
|
||||
if (query.model) p.set("model", query.model);
|
||||
if (query.job) p.set("job", query.job);
|
||||
if (query.job && opts.logAfter != null) p.set("logAfter", String(opts.logAfter));
|
||||
if (opts.v) p.set("v", opts.v);
|
||||
const qs = p.toString();
|
||||
return qs ? `/api/live?${qs}` : "/api/live";
|
||||
}
|
||||
|
||||
/**
|
||||
* The response body, built around the already serialized snapshot so it isn't serialized twice.
|
||||
* `version` is a hash of `snapshotJson`.
|
||||
*/
|
||||
export function liveBody(snapshotJson: string, version: string, clientVersion: string | null, logs?: LogLine[]): string {
|
||||
let body = `{"v":${JSON.stringify(version)}`;
|
||||
if (clientVersion !== version) body += `,"snapshot":${snapshotJson}`;
|
||||
if (logs) body += `,"logs":${JSON.stringify(logs)}`;
|
||||
return `${body}}`;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import type { JobSnapshot } from "./jobs";
|
||||
import type { LiveResponse } from "./live-protocol";
|
||||
import { createLiveStore, EMPTY_LIVE, KEEP_MS, type LiveEnv, POLL_MS, RETRY_MS, STATUS_POLL_MS } from "./live-store";
|
||||
|
||||
const worker = { online: true, hfVersion: null, modelsDirFreeBytes: 1, modelsDirTotalBytes: 2 };
|
||||
|
||||
function job(id: string, state: string): JobSnapshot {
|
||||
return {
|
||||
id,
|
||||
modelId: "m1",
|
||||
repoId: "org/repo",
|
||||
kind: "download",
|
||||
purpose: null,
|
||||
state,
|
||||
attempt: 1,
|
||||
totalBytes: 10,
|
||||
doneBytes: 0,
|
||||
speedBps: null,
|
||||
etaSeconds: null,
|
||||
exitCode: null,
|
||||
errorCode: null,
|
||||
errorMessage: null,
|
||||
result: null,
|
||||
cancelRequested: false,
|
||||
createdAt: 0,
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
const settle = () => new Promise((r) => setImmediate(r));
|
||||
|
||||
/** A fake browser: manual clock, scripted responses, visibility switch. */
|
||||
function fakeEnv() {
|
||||
let now = 0;
|
||||
let seq = 0;
|
||||
const timers = new Map<number, { at: number; fn: () => void }>();
|
||||
const calls: string[] = [];
|
||||
const onVisible: (() => void)[] = [];
|
||||
const state = {
|
||||
visible: true,
|
||||
fail: false,
|
||||
respond: (url: string): unknown => (url.startsWith("/api/status") ? { worker } : ({ v: "1", snapshot: { worker, jobs: [], files: [] } } satisfies LiveResponse)),
|
||||
};
|
||||
const env: LiveEnv = {
|
||||
fetch: async (url) => {
|
||||
calls.push(url);
|
||||
if (state.fail) throw new Error("offline");
|
||||
return { ok: true, json: async () => state.respond(url) };
|
||||
},
|
||||
setTimeout: (fn, ms) => {
|
||||
timers.set(++seq, { at: now + ms, fn });
|
||||
return seq;
|
||||
},
|
||||
clearTimeout: (t) => void timers.delete(t as number),
|
||||
visible: () => state.visible,
|
||||
onVisible: (fn) => void onVisible.push(fn),
|
||||
};
|
||||
return {
|
||||
env,
|
||||
calls,
|
||||
state,
|
||||
/** Runs timers that are due within `ms`, in order, letting each poll finish. */
|
||||
async advance(ms: number) {
|
||||
const end = now + ms;
|
||||
for (;;) {
|
||||
await settle(); // let running polls finish and schedule their next one
|
||||
const next = [...timers.entries()].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at)[0];
|
||||
if (!next) break;
|
||||
timers.delete(next[0]);
|
||||
now = next[1].at;
|
||||
next[1].fn();
|
||||
}
|
||||
now = end;
|
||||
},
|
||||
async show() {
|
||||
state.visible = true;
|
||||
onVisible.forEach((fn) => fn());
|
||||
await settle();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const live = (calls: string[]) => calls.filter((c) => c.startsWith("/api/live"));
|
||||
|
||||
describe("live store", () => {
|
||||
it("components showing the same query share one poller", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
let a = 0;
|
||||
let b = 0;
|
||||
store.subscribe({ model: "m1" }, false, () => a++);
|
||||
store.subscribe({ model: "m1" }, false, () => b++);
|
||||
await settle();
|
||||
assert.deepEqual(f.calls, ["/api/live?model=m1"]);
|
||||
assert.equal(a, 1);
|
||||
assert.equal(b, 1);
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls.length, 2);
|
||||
});
|
||||
|
||||
it("an unchanged snapshot keeps the same state and wakes nobody", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
let renders = 0;
|
||||
store.subscribe({}, false, () => renders++);
|
||||
await settle();
|
||||
const first = store.get({});
|
||||
f.state.respond = () => ({ v: "1" });
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls[1], "/api/live?v=1");
|
||||
assert.equal(store.get({}), first);
|
||||
assert.equal(renders, 1);
|
||||
});
|
||||
|
||||
it("pauses while the tab is hidden and polls at once when it is shown", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
store.subscribe({}, false, () => {});
|
||||
await settle();
|
||||
f.state.visible = false;
|
||||
await f.advance(60_000);
|
||||
assert.equal(f.calls.length, 1);
|
||||
await f.show();
|
||||
assert.equal(f.calls.length, 2);
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls.length, 3);
|
||||
});
|
||||
|
||||
it("follows the log with a cursor", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
const line = (id: number) => ({ id, ts: id, stream: "stdout", line: `line ${id}` });
|
||||
f.state.respond = () => ({ v: "1", snapshot: { worker, jobs: [], files: [] }, logs: [line(1), line(2)] });
|
||||
store.subscribe({ job: "j1" }, true, () => {});
|
||||
await settle();
|
||||
assert.equal(f.calls[0], "/api/live?job=j1&logAfter=0");
|
||||
f.state.respond = () => ({ v: "1", logs: [line(3)] });
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls[1], "/api/live?job=j1&logAfter=2&v=1");
|
||||
assert.deepEqual(
|
||||
store.get({ job: "j1" }, true).logs.map((l) => l.id),
|
||||
[1, 2, 3],
|
||||
);
|
||||
});
|
||||
|
||||
it("refreshes once when a job finishes, however many components show it", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
let refreshes = 0;
|
||||
f.state.respond = () => ({ v: "a", snapshot: { worker, jobs: [job("j1", "downloading")], files: [] } });
|
||||
store.subscribe({}, false, () => {}, () => refreshes++);
|
||||
store.subscribe({}, false, () => {}, () => refreshes++);
|
||||
await settle();
|
||||
assert.equal(refreshes, 0);
|
||||
f.state.respond = () => ({ v: "b", snapshot: { worker, jobs: [job("j1", "completed")], files: [] } });
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(refreshes, 1);
|
||||
});
|
||||
|
||||
it("stops when nothing shows the query and keeps its data for a moment", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
const off = store.subscribe({}, false, () => {});
|
||||
await settle();
|
||||
off();
|
||||
await f.advance(POLL_MS * 3);
|
||||
assert.equal(f.calls.length, 1);
|
||||
assert.notEqual(store.get({}), EMPTY_LIVE);
|
||||
await f.advance(KEEP_MS);
|
||||
assert.equal(store.get({}), EMPTY_LIVE);
|
||||
});
|
||||
|
||||
it("backs off while requests fail", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
f.state.fail = true;
|
||||
store.subscribe({}, false, () => {});
|
||||
await settle();
|
||||
await f.advance(RETRY_MS[0] - 1);
|
||||
assert.equal(f.calls.length, 1);
|
||||
await f.advance(1);
|
||||
assert.equal(f.calls.length, 2);
|
||||
await f.advance(RETRY_MS[1]);
|
||||
assert.equal(f.calls.length, 3);
|
||||
f.state.fail = false;
|
||||
await f.advance(RETRY_MS[2]);
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls.length, 5);
|
||||
});
|
||||
|
||||
it("takes the worker status from the live poll, else from /api/status every 10 s", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
store.subscribeWorker(() => {});
|
||||
await f.advance(STATUS_POLL_MS);
|
||||
assert.deepEqual(f.calls, ["/api/status"]);
|
||||
assert.deepEqual(store.getWorker(), worker);
|
||||
const off = store.subscribe({}, false, () => {});
|
||||
await f.advance(STATUS_POLL_MS * 3);
|
||||
assert.equal(f.calls.filter((c) => c === "/api/status").length, 1);
|
||||
assert.ok(live(f.calls).length > 10);
|
||||
off();
|
||||
await f.advance(STATUS_POLL_MS);
|
||||
assert.equal(f.calls.filter((c) => c === "/api/status").length, 2);
|
||||
});
|
||||
|
||||
it("poke polls every shown query at once", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
store.subscribe({ model: "m1" }, false, () => {});
|
||||
store.subscribe({ job: "j1" }, false, () => {});
|
||||
await settle();
|
||||
assert.equal(f.calls.length, 2);
|
||||
store.poke();
|
||||
await settle();
|
||||
assert.equal(f.calls.length, 4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
// Live job state in the browser: one poller per query and tab, shared by every component that shows
|
||||
// it (the library header and table, a model's download card and job history, …). Short requests to
|
||||
// /api/live instead of a stream per component: over HTTP/1.1 a browser allows 6 connections per
|
||||
// host, and open streams used them up after a few tabs. Polling pauses while the tab is hidden.
|
||||
//
|
||||
// The worker status rides along: components that only need it (the menu's worker dot) read it from
|
||||
// whatever is polled; with nothing polled, /api/status is asked every 10 s.
|
||||
|
||||
import type { LogLine } from "@/lib/jobs";
|
||||
import { type LiveQuery, type LiveResponse, type LiveSnapshot, liveUrl } from "@/lib/live-protocol";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export type LiveState = { snapshot: LiveSnapshot | null; logs: LogLine[] };
|
||||
|
||||
export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"];
|
||||
export const POLL_MS = 1_000;
|
||||
export const STATUS_POLL_MS = 10_000;
|
||||
/** After failed polls: wait this long before the next try (the last value repeats). */
|
||||
export const RETRY_MS = [3_000, 6_000, 12_000, 30_000];
|
||||
/** A query nobody shows any more keeps its data this long, so going back shows it at once. */
|
||||
export const KEEP_MS = 10_000;
|
||||
const MAX_LOG_LINES = 5000;
|
||||
|
||||
export const EMPTY_LIVE: LiveState = { snapshot: null, logs: [] };
|
||||
|
||||
/** What the store needs from the browser (injected so it can be tested without one). */
|
||||
export type LiveEnv = {
|
||||
fetch: (url: string) => Promise<{ ok: boolean; json(): Promise<unknown> }>;
|
||||
setTimeout: (fn: () => void, ms: number) => unknown;
|
||||
clearTimeout: (timer: unknown) => void;
|
||||
visible: () => boolean;
|
||||
/** Calls `fn` whenever the tab becomes visible again. */
|
||||
onVisible: (fn: () => void) => void;
|
||||
};
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
type Entry = {
|
||||
query: LiveQuery;
|
||||
withLogs: boolean;
|
||||
state: LiveState;
|
||||
/** Version of the snapshot in `state` (the server leaves an unchanged snapshot out). */
|
||||
version: string | null;
|
||||
/** Id of the newest log line received. */
|
||||
logCursor: number;
|
||||
listeners: Set<Listener>;
|
||||
/** Called (one of them) when a job of this query reaches a terminal state. */
|
||||
onFinish: Set<() => void>;
|
||||
jobStates: Map<string, string>;
|
||||
timer: unknown;
|
||||
inFlight: boolean;
|
||||
/** A poll was asked for while one was running: run another right after it. */
|
||||
again: boolean;
|
||||
failures: number;
|
||||
dropTimer: unknown;
|
||||
};
|
||||
|
||||
export function liveKey(query: LiveQuery, withLogs: boolean): string {
|
||||
return `${query.model ?? ""}|${query.job ?? ""}|${withLogs ? 1 : 0}`;
|
||||
}
|
||||
|
||||
const sameWorker = (a: WorkerStatus, b: WorkerStatus) =>
|
||||
a.online === b.online &&
|
||||
a.hfVersion === b.hfVersion &&
|
||||
a.modelsDirFreeBytes === b.modelsDirFreeBytes &&
|
||||
a.modelsDirTotalBytes === b.modelsDirTotalBytes;
|
||||
|
||||
export function createLiveStore(env: LiveEnv) {
|
||||
const entries = new Map<string, Entry>();
|
||||
let worker: WorkerStatus | null = null;
|
||||
const workerListeners = new Set<Listener>();
|
||||
let statusTimer: unknown = null;
|
||||
let statusInFlight = false;
|
||||
|
||||
const polling = () => [...entries.values()].some((e) => e.listeners.size > 0);
|
||||
|
||||
function setWorker(next: WorkerStatus) {
|
||||
if (worker && sameWorker(worker, next)) return;
|
||||
worker = next;
|
||||
for (const l of [...workerListeners]) l();
|
||||
}
|
||||
|
||||
function schedule(e: Entry, ms: number) {
|
||||
env.clearTimeout(e.timer);
|
||||
e.timer = null;
|
||||
// Hidden tab: nothing is scheduled; onVisible starts again.
|
||||
if (e.listeners.size === 0 || !env.visible()) return;
|
||||
e.timer = env.setTimeout(() => void poll(e), ms);
|
||||
}
|
||||
|
||||
async function poll(e: Entry): Promise<void> {
|
||||
env.clearTimeout(e.timer);
|
||||
e.timer = null;
|
||||
if (e.inFlight) {
|
||||
e.again = true;
|
||||
return;
|
||||
}
|
||||
if (e.listeners.size === 0 || !env.visible()) return;
|
||||
e.inFlight = true;
|
||||
let ok = false;
|
||||
try {
|
||||
const url = liveUrl(e.query, { v: e.version, logAfter: e.withLogs ? e.logCursor : null });
|
||||
const res = await env.fetch(url);
|
||||
if (res.ok) {
|
||||
apply(e, (await res.json()) as LiveResponse);
|
||||
ok = true;
|
||||
}
|
||||
} catch {
|
||||
// network error or a bad body: try again later
|
||||
}
|
||||
e.inFlight = false;
|
||||
e.failures = ok ? 0 : e.failures + 1;
|
||||
if (e.again) {
|
||||
e.again = false;
|
||||
return poll(e);
|
||||
}
|
||||
schedule(e, ok ? POLL_MS : RETRY_MS[Math.min(e.failures, RETRY_MS.length) - 1]);
|
||||
}
|
||||
|
||||
function apply(e: Entry, r: LiveResponse) {
|
||||
let state = e.state;
|
||||
let finished = false;
|
||||
if (r.snapshot) {
|
||||
e.version = r.v;
|
||||
state = { ...state, snapshot: r.snapshot };
|
||||
for (const j of r.snapshot.jobs) {
|
||||
const prev = e.jobStates.get(j.id);
|
||||
if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true;
|
||||
e.jobStates.set(j.id, j.state);
|
||||
}
|
||||
setWorker(r.snapshot.worker);
|
||||
}
|
||||
if (r.logs && r.logs.length > 0) {
|
||||
const seen = state.logs.length ? state.logs[state.logs.length - 1].id : 0;
|
||||
const fresh = r.logs.filter((l) => l.id > seen);
|
||||
if (fresh.length > 0) {
|
||||
const merged = state.logs.concat(fresh);
|
||||
state = { ...state, logs: merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged };
|
||||
}
|
||||
e.logCursor = Math.max(e.logCursor, r.logs[r.logs.length - 1].id);
|
||||
}
|
||||
if (state !== e.state) {
|
||||
e.state = state;
|
||||
for (const l of [...e.listeners]) l();
|
||||
}
|
||||
// Every handler refreshes the same page; one is enough.
|
||||
if (finished) [...e.onFinish][0]?.();
|
||||
}
|
||||
|
||||
function scheduleStatus() {
|
||||
if (statusTimer != null || statusInFlight || workerListeners.size === 0 || polling() || !env.visible()) return;
|
||||
statusTimer = env.setTimeout(() => void pollStatus(), STATUS_POLL_MS);
|
||||
}
|
||||
|
||||
function stopStatus() {
|
||||
env.clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
statusTimer = null;
|
||||
if (statusInFlight || workerListeners.size === 0 || polling() || !env.visible()) return;
|
||||
statusInFlight = true;
|
||||
try {
|
||||
const res = await env.fetch("/api/status");
|
||||
if (res.ok) setWorker(((await res.json()) as { worker: WorkerStatus }).worker);
|
||||
} catch {
|
||||
// keep the last known status
|
||||
}
|
||||
statusInFlight = false;
|
||||
scheduleStatus();
|
||||
}
|
||||
|
||||
env.onVisible(() => {
|
||||
for (const e of entries.values()) if (e.listeners.size > 0 && e.timer == null) void poll(e);
|
||||
if (workerListeners.size > 0 && !polling() && statusTimer == null) void pollStatus();
|
||||
});
|
||||
|
||||
return {
|
||||
/** Current state of a query (the same object until something changes). */
|
||||
get(query: LiveQuery, withLogs = false): LiveState {
|
||||
return entries.get(liveKey(query, withLogs))?.state ?? EMPTY_LIVE;
|
||||
},
|
||||
|
||||
subscribe(query: LiveQuery, withLogs: boolean, listener: Listener, onFinish?: () => void): () => void {
|
||||
const key = liveKey(query, withLogs);
|
||||
let e = entries.get(key);
|
||||
if (!e) {
|
||||
e = {
|
||||
query: { model: query.model, job: query.job },
|
||||
withLogs,
|
||||
state: EMPTY_LIVE,
|
||||
version: null,
|
||||
logCursor: 0,
|
||||
listeners: new Set(),
|
||||
onFinish: new Set(),
|
||||
jobStates: new Map(),
|
||||
timer: null,
|
||||
inFlight: false,
|
||||
again: false,
|
||||
failures: 0,
|
||||
dropTimer: null,
|
||||
};
|
||||
entries.set(key, e);
|
||||
}
|
||||
const entry = e;
|
||||
env.clearTimeout(entry.dropTimer);
|
||||
entry.dropTimer = null;
|
||||
entry.listeners.add(listener);
|
||||
if (onFinish) entry.onFinish.add(onFinish);
|
||||
stopStatus(); // the live snapshot carries the worker status now
|
||||
if (entry.listeners.size === 1 && entry.timer == null && !entry.inFlight) void poll(entry);
|
||||
|
||||
return () => {
|
||||
entry.listeners.delete(listener);
|
||||
if (onFinish) entry.onFinish.delete(onFinish);
|
||||
if (entry.listeners.size > 0) return;
|
||||
env.clearTimeout(entry.timer);
|
||||
entry.timer = null;
|
||||
entry.dropTimer = env.setTimeout(() => {
|
||||
if (entry.listeners.size === 0 && entries.get(key) === entry) entries.delete(key);
|
||||
}, KEEP_MS);
|
||||
scheduleStatus();
|
||||
};
|
||||
},
|
||||
|
||||
/** Latest worker status seen (from a live snapshot or /api/status), null until there is one. */
|
||||
getWorker(): WorkerStatus | null {
|
||||
return worker;
|
||||
},
|
||||
|
||||
subscribeWorker(listener: Listener): () => void {
|
||||
workerListeners.add(listener);
|
||||
scheduleStatus();
|
||||
return () => {
|
||||
workerListeners.delete(listener);
|
||||
if (workerListeners.size === 0) stopStatus();
|
||||
};
|
||||
},
|
||||
|
||||
/** Poll every shown query now (after starting or cancelling a job, for instant feedback). */
|
||||
poke() {
|
||||
for (const e of entries.values()) if (e.listeners.size > 0) void poll(e);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type LiveStore = ReturnType<typeof createLiveStore>;
|
||||
|
||||
let store: LiveStore | null = null;
|
||||
|
||||
/** The tab's store, created on first use (never on the server). */
|
||||
export function liveStore(): LiveStore {
|
||||
return (store ??= createLiveStore({
|
||||
fetch: (url) => fetch(url, { cache: "no-store" }),
|
||||
setTimeout: (fn, ms) => window.setTimeout(fn, ms),
|
||||
clearTimeout: (t) => window.clearTimeout(t as number | undefined),
|
||||
visible: () => document.visibilityState === "visible",
|
||||
onVisible: (fn) =>
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible") fn();
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Poll now, if anything is shown (no-op on the server). */
|
||||
export function pokeLive() {
|
||||
if (typeof window !== "undefined" && store) store.poke();
|
||||
}
|
||||
@@ -4,21 +4,31 @@ import { db } from "@/lib/db/client";
|
||||
import { localFolders, models, workerState } from "@/lib/db/schema";
|
||||
|
||||
export type LocalFolder = typeof localFolders.$inferSelect;
|
||||
export type LocalFolderSummary = Pick<LocalFolder, "path" | "commit" | "fileCount" | "totalBytes">;
|
||||
|
||||
/** Folders in MODELS_DIR that no model uses (from the worker's last scan). */
|
||||
export async function listLocalFolders(): Promise<LocalFolder[]> {
|
||||
/**
|
||||
* Folders in MODELS_DIR that no model uses (from the worker's last scan), without their file lists:
|
||||
* those can hold thousands of entries and are only needed once you click Import (getLocalFolder).
|
||||
*/
|
||||
export async function listLocalFolders(): Promise<LocalFolderSummary[]> {
|
||||
const d = db();
|
||||
return d
|
||||
.select()
|
||||
.select({ path: localFolders.path, commit: localFolders.commit, fileCount: localFolders.fileCount, totalBytes: localFolders.totalBytes })
|
||||
.from(localFolders)
|
||||
.where(notInArray(localFolders.path, d.select({ p: models.localPath }).from(models)))
|
||||
.orderBy(asc(localFolders.path));
|
||||
}
|
||||
|
||||
/** One folder with its file list. */
|
||||
export async function getLocalFolder(path: string): Promise<LocalFolder | undefined> {
|
||||
return db().query.localFolders.findFirst({ where: eq(localFolders.path, path) });
|
||||
}
|
||||
|
||||
export async function localFolderExists(path: string): Promise<boolean> {
|
||||
const row = await db().query.localFolders.findFirst({ columns: { path: true }, where: eq(localFolders.path, path) });
|
||||
return !!row;
|
||||
}
|
||||
|
||||
/** Ask the worker to scan MODELS_DIR now (it picks this up with its next heartbeat). */
|
||||
export async function requestFolderScan(): Promise<void> {
|
||||
await db().update(workerState).set({ scanRequestedAt: new Date() }).where(eq(workerState.id, "worker"));
|
||||
|
||||
+52
-4
@@ -7,7 +7,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { hasOpenJob, queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
|
||||
import { localFolderExists, requestFolderScan } from "@/lib/local-folders";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { contentId } from "@/lib/update-diff";
|
||||
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
||||
@@ -39,7 +39,7 @@ export async function addModel(input: {
|
||||
const info = await getRepoInfo(input.repoId, input.sha);
|
||||
const repoId = info.repoId;
|
||||
const localPath = input.localPath ?? repoId;
|
||||
if (input.localPath && !(await getLocalFolder(input.localPath))) {
|
||||
if (input.localPath && !(await localFolderExists(input.localPath))) {
|
||||
throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
|
||||
}
|
||||
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, localPath) });
|
||||
@@ -51,7 +51,8 @@ export async function addModel(input: {
|
||||
});
|
||||
if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409);
|
||||
|
||||
const files = await listFiles(repoId, info.sha);
|
||||
// Independent: the author's avatar loads while the file list does (usually cached from the lookup).
|
||||
const [files, avatar] = await Promise.all([listFiles(repoId, info.sha), getAuthorAvatar(repoId.split("/")[0])]);
|
||||
const selectedFiles = files.filter((f) => isSelected(f.path, input.rule));
|
||||
if (selectedFiles.length === 0) {
|
||||
throw new ModelError("empty_selection", "No files selected.", 400);
|
||||
@@ -81,7 +82,7 @@ export async function addModel(input: {
|
||||
localPath,
|
||||
includePatterns: input.rule.include,
|
||||
excludePatterns: input.rule.exclude,
|
||||
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
|
||||
...metadataColumns(info.metadata, avatar),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
@@ -231,3 +232,50 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
|
||||
const { jobId } = await queueDownload(modelId, "add");
|
||||
return { jobId, added: changed.filter((f) => !f.selected).length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove files from a model: take them out of the selection rule (exact-path excludes, and their
|
||||
* exact includes dropped), mark them unselected, and queue a delete job that removes them from
|
||||
* disk. The model and its other files stay. Removing every selected file is refused: delete the
|
||||
* model instead.
|
||||
*/
|
||||
export async function removeFilesFromModel(modelId: string, paths: string[]): Promise<{ jobId: string; removed: number }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
if (await hasOpenJob(modelId)) throw new ModelError("busy", "A job for this model is still queued or running. Remove files when it has finished.", 409);
|
||||
|
||||
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
|
||||
const wanted = new Set(paths);
|
||||
const remove = files.filter((f) => f.selected && wanted.has(f.path));
|
||||
if (remove.length === 0) throw new ModelError("empty_selection", "None of these files is selected.", 400);
|
||||
if (remove.length === files.filter((f) => f.selected).length) {
|
||||
throw new ModelError("empty_selection", "That would remove every file of this model. Delete the model instead.", 400);
|
||||
}
|
||||
|
||||
const exact = new Set(remove.map((f) => escapeGlob(f.path)));
|
||||
// Drop the files' exact includes; files a broader pattern still selects get an exact exclude.
|
||||
const include = model.includePatterns.filter((p) => !exact.has(p));
|
||||
const stillSelected = remove.filter((f) => isSelected(f.path, { include, exclude: model.excludePatterns }));
|
||||
const rule: SelectionRule = { include, exclude: [...model.excludePatterns, ...stillSelected.map((f) => escapeGlob(f.path))] };
|
||||
// The rule must now select exactly the old selection minus these files.
|
||||
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
||||
if (changed.some((f) => !wanted.has(f.path))) throw new ModelError("busy", "The selection rule couldn't be narrowed to just these files.", 409);
|
||||
|
||||
const jobId = ulid();
|
||||
await d.batch([
|
||||
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
|
||||
...remove.map((f) => d.update(modelFiles).set({ selected: false }).where(eq(modelFiles.id, f.id))),
|
||||
d.insert(jobs).values({
|
||||
id: jobId,
|
||||
modelId,
|
||||
kind: "delete",
|
||||
purpose: "remove",
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: remove.reduce((s, f) => s + f.size, 0),
|
||||
result: { removePaths: remove.map((f) => f.path) },
|
||||
}),
|
||||
]);
|
||||
return { jobId, removed: remove.length };
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Removing single files from a model: selection rule, the queued job, and the worker deleting only
|
||||
// those files. Temporary SQLite database and models folder; no Hub access.
|
||||
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "kaname-remove-"));
|
||||
const modelsDir = join(dir, "models");
|
||||
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
|
||||
process.env.MODELS_DIR = modelsDir;
|
||||
|
||||
type Mods = {
|
||||
db: typeof import("./db/client");
|
||||
schema: typeof import("./db/schema");
|
||||
models: typeof import("./models");
|
||||
delete: typeof import("../worker/delete");
|
||||
};
|
||||
let M: Mods;
|
||||
const MODEL = "01M6000000000000000000000A";
|
||||
const FILES = ["Qwen3-8B-Q4_K_M.gguf", "Qwen3-8B-Q8_0.gguf", "mmproj-F16.gguf", "README.md"];
|
||||
|
||||
before(async () => {
|
||||
const { runMigrations } = await import("./db/migrate");
|
||||
await runMigrations();
|
||||
M = { db: await import("./db/client"), schema: await import("./db/schema"), models: await import("./models"), delete: await import("../worker/delete") };
|
||||
const d = M.db.db();
|
||||
// Q4 and Q8 picked by exact path, mmproj by a pattern; README not selected.
|
||||
await d.insert(M.schema.models).values({
|
||||
id: MODEL,
|
||||
repoId: "unsloth/Qwen3-8B-GGUF",
|
||||
pinnedSha: "a".repeat(40),
|
||||
localPath: "unsloth/Qwen3-8B-GGUF",
|
||||
includePatterns: ["Qwen3-8B-Q4_K_M.gguf", "Qwen3-8B-Q8_0.gguf", "mmproj-*"],
|
||||
status: "ready",
|
||||
});
|
||||
await d.insert(M.schema.modelFiles).values(FILES.map((path) => ({ modelId: MODEL, path, size: 100, selected: path !== "README.md", state: path === "README.md" ? ("pending" as const) : ("present" as const) })));
|
||||
mkdirSync(join(modelsDir, "unsloth", "Qwen3-8B-GGUF"), { recursive: true });
|
||||
for (const f of FILES.slice(0, 3)) writeFileSync(join(modelsDir, "unsloth", "Qwen3-8B-GGUF", f), "x".repeat(100));
|
||||
});
|
||||
|
||||
after(() => {
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {}
|
||||
});
|
||||
|
||||
describe("removing files from a model", () => {
|
||||
it("narrows the selection rule to exactly the rest and queues a remove job", async () => {
|
||||
const { jobId, removed } = await M.models.removeFilesFromModel(MODEL, ["Qwen3-8B-Q8_0.gguf", "mmproj-F16.gguf", "README.md"]);
|
||||
assert.equal(removed, 2, "README isn't selected, so it isn't removed");
|
||||
const model = await M.db.db().query.models.findFirst({ where: eq(M.schema.models.id, MODEL) });
|
||||
assert.deepEqual(model!.includePatterns, ["Qwen3-8B-Q4_K_M.gguf", "mmproj-*"], "the exact include goes");
|
||||
assert.deepEqual(model!.excludePatterns, ["mmproj-F16.gguf"], "the pattern stays, an exact exclude stops it");
|
||||
const files = await M.db.db().select().from(M.schema.modelFiles).where(eq(M.schema.modelFiles.modelId, MODEL));
|
||||
assert.deepEqual(files.filter((f) => f.selected).map((f) => f.path), ["Qwen3-8B-Q4_K_M.gguf"]);
|
||||
const job = await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.id, jobId) });
|
||||
assert.equal(job!.kind, "delete");
|
||||
assert.equal(job!.purpose, "remove");
|
||||
assert.deepEqual(job!.result?.removePaths, ["Qwen3-8B-Q8_0.gguf", "mmproj-F16.gguf"]);
|
||||
await assert.rejects(M.models.removeFilesFromModel(MODEL, ["Qwen3-8B-Q4_K_M.gguf"]), /still queued or running/);
|
||||
});
|
||||
|
||||
it("the worker deletes only those files and keeps the model", async () => {
|
||||
const job = (await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.modelId, MODEL) }))!;
|
||||
const model = (await M.db.db().query.models.findFirst({ where: eq(M.schema.models.id, MODEL) }))!;
|
||||
await new M.delete.DeleteRunner(job, model, FILES).run();
|
||||
const folder = join(modelsDir, "unsloth", "Qwen3-8B-GGUF");
|
||||
assert.ok(existsSync(join(folder, "Qwen3-8B-Q4_K_M.gguf")));
|
||||
assert.ok(!existsSync(join(folder, "Qwen3-8B-Q8_0.gguf")) && !existsSync(join(folder, "mmproj-F16.gguf")));
|
||||
const done = await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.id, job.id) });
|
||||
assert.equal(done!.state, "completed");
|
||||
assert.deepEqual(done!.result?.removed, ["Qwen3-8B-Q8_0.gguf", "mmproj-F16.gguf"].sort());
|
||||
const after = await M.db.db().query.models.findFirst({ where: eq(M.schema.models.id, MODEL) });
|
||||
assert.equal(after!.status, "ready", "the remaining selection is complete");
|
||||
});
|
||||
|
||||
it("refuses to remove every selected file", async () => {
|
||||
await assert.rejects(M.models.removeFilesFromModel(MODEL, ["Qwen3-8B-Q4_K_M.gguf"]), /Delete the model instead/);
|
||||
await assert.rejects(M.models.removeFilesFromModel(MODEL, ["README.md"]), /None of these files is selected/);
|
||||
});
|
||||
});
|
||||
+11
-1
@@ -3,7 +3,7 @@ import { describe, it } from "node:test";
|
||||
import { groupSplitFiles, splitInfo } from "./file-groups";
|
||||
import { fileRole } from "./file-roles";
|
||||
import { modelFamilies, parseRepoMetadata } from "./hub/metadata";
|
||||
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search";
|
||||
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, queryTerms, type SearchableModel, searchText } from "./search";
|
||||
|
||||
describe("parseRepoMetadata (real Hub responses, trimmed)", () => {
|
||||
it("unsloth GGUF quant of Qwen", () => {
|
||||
@@ -69,6 +69,16 @@ describe("matchesQuery", () => {
|
||||
assert.ok(matchesQuery(m, " "));
|
||||
assert.ok(!matchesQuery(m, "unsloth gemma"));
|
||||
});
|
||||
it("takes pre-split terms and a precomputed text with the same result", () => {
|
||||
const m = model({});
|
||||
const cached = { ...m, text: searchText(m) };
|
||||
for (const q of ["qwen", "unsloth qwen", "ROLEPLAY", " ", "unsloth gemma"]) {
|
||||
assert.equal(matchesQuery(cached, queryTerms(q)), matchesQuery(m, q), q);
|
||||
}
|
||||
// The stored text is what gets searched (it isn't rebuilt per call).
|
||||
assert.ok(matchesQuery({ ...m, text: "only this" }, "only"));
|
||||
assert.ok(!matchesQuery({ ...m, text: "only this" }, "qwen"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("hub status", () => {
|
||||
|
||||
+18
-7
@@ -14,6 +14,8 @@ export type SearchableModel = {
|
||||
status: string;
|
||||
/** Extra status value when the repo or commit is gone from the Hub, e.g. "deleted on Hub". */
|
||||
hubStatus: string | null;
|
||||
/** The text search terms are matched against (searchText), computed once per model. */
|
||||
text?: string;
|
||||
};
|
||||
|
||||
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
|
||||
@@ -37,7 +39,8 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
function haystack(m: SearchableModel): string {
|
||||
/** Lowercased text of every searchable field; store it as `text` to build it only once. */
|
||||
export function searchText(m: SearchableModel): string {
|
||||
return [
|
||||
m.repoId,
|
||||
m.author,
|
||||
@@ -57,11 +60,16 @@ function haystack(m: SearchableModel): string {
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/** The search terms of a query: lowercased, split on whitespace. */
|
||||
export function queryTerms(query: string): string[] {
|
||||
return query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
}
|
||||
|
||||
/** Every whitespace-separated term must appear somewhere (case-insensitive substring). */
|
||||
export function matchesQuery(m: SearchableModel, query: string): boolean {
|
||||
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
export function matchesQuery(m: SearchableModel, query: string | string[]): boolean {
|
||||
const terms = typeof query === "string" ? queryTerms(query) : query;
|
||||
if (terms.length === 0) return true;
|
||||
const text = haystack(m);
|
||||
const text = m.text ?? searchText(m);
|
||||
return terms.every((t) => text.includes(t));
|
||||
}
|
||||
|
||||
@@ -75,17 +83,20 @@ export function matchesFilters(m: SearchableModel, filters: Filters, except?: Fa
|
||||
});
|
||||
}
|
||||
|
||||
const byName = new Intl.Collator(undefined, { numeric: true });
|
||||
|
||||
/**
|
||||
* Value counts for one facet, computed over the models that match the query and all *other*
|
||||
* facets, so picking e.g. an author narrows the quant counts but not the author list itself.
|
||||
*/
|
||||
export function facetCounts(models: SearchableModel[], facet: Facet, query: string, filters: Filters) {
|
||||
export function facetCounts(models: SearchableModel[], facet: Facet, query: string | string[], filters: Filters) {
|
||||
const terms = typeof query === "string" ? queryTerms(query) : query;
|
||||
const counts = new Map<string, number>();
|
||||
for (const m of models) {
|
||||
if (!matchesQuery(m, query) || !matchesFilters(m, filters, facet)) continue;
|
||||
if (!matchesQuery(m, terms) || !matchesFilters(m, filters, facet)) continue;
|
||||
for (const v of new Set(facetValues(m, facet))) counts.set(v, (counts.get(v) ?? 0) + 1);
|
||||
}
|
||||
// Keep selected values visible even if their count dropped to 0.
|
||||
for (const v of filters[facet]) if (!counts.has(v)) counts.set(v, 0);
|
||||
return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true }));
|
||||
return [...counts.entries()].sort((a, b) => b[1] - a[1] || byName.compare(a[0], b[0]));
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import "server-only";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { settings, workerState } from "@/lib/db/schema";
|
||||
import { type Backdrop, BACKDROP_KEY, parseBackdrop } from "@/lib/backdrop";
|
||||
import { isLabelColor } from "@/lib/colors";
|
||||
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
|
||||
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
|
||||
@@ -140,3 +141,19 @@ export async function getScanStatus(): Promise<ScanStatus> {
|
||||
nextScanAt: next?.getTime() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The custom picture behind the page headers (Settings → Appearance), or null for the built-in painting. */
|
||||
export async function getBackdrop(): Promise<Backdrop | null> {
|
||||
return parseBackdrop(await read<unknown>(BACKDROP_KEY));
|
||||
}
|
||||
|
||||
export async function saveBackdrop(input: unknown): Promise<Backdrop | null> {
|
||||
if (input == null) {
|
||||
await db().delete(settings).where(eq(settings.key, BACKDROP_KEY));
|
||||
return null;
|
||||
}
|
||||
const backdrop = parseBackdrop(input);
|
||||
if (!backdrop) throw new SettingsError("That picture couldn't be read. Try another image.");
|
||||
await write(BACKDROP_KEY, backdrop);
|
||||
return backdrop;
|
||||
}
|
||||
@@ -5,33 +5,38 @@ import { workerState } from "@/lib/db/schema";
|
||||
|
||||
/** The worker writes a heartbeat every 5s; after this long without one we call it offline. */
|
||||
const OFFLINE_AFTER_MS = 20_000;
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* What the UI shows about the worker. No heartbeat time on purpose: it changes every 5 s, and the
|
||||
* live snapshot (see /api/live) would then change every 5 s even when nothing else did.
|
||||
*/
|
||||
export type WorkerStatus = {
|
||||
online: boolean;
|
||||
heartbeatAt: string | null;
|
||||
hfVersion: string | null;
|
||||
/** Free/total bytes of the models folder, rounded to whole MiB for the same reason. */
|
||||
modelsDirFreeBytes: number | null;
|
||||
modelsDirTotalBytes: number | null;
|
||||
};
|
||||
|
||||
const OFFLINE: WorkerStatus = {
|
||||
online: false,
|
||||
heartbeatAt: null,
|
||||
hfVersion: null,
|
||||
modelsDirFreeBytes: null,
|
||||
modelsDirTotalBytes: null,
|
||||
};
|
||||
|
||||
const toMiB = (bytes: number | null) => (bytes == null ? null : Math.round(bytes / MIB) * MIB);
|
||||
|
||||
export async function getWorkerStatus(): Promise<WorkerStatus> {
|
||||
try {
|
||||
const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
|
||||
if (!row) return OFFLINE;
|
||||
return {
|
||||
online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS,
|
||||
heartbeatAt: row.heartbeatAt.toISOString(),
|
||||
hfVersion: row.hfVersion,
|
||||
modelsDirFreeBytes: row.modelsDirFreeBytes,
|
||||
modelsDirTotalBytes: row.modelsDirTotalBytes,
|
||||
modelsDirFreeBytes: toMiB(row.modelsDirFreeBytes),
|
||||
modelsDirTotalBytes: toMiB(row.modelsDirTotalBytes),
|
||||
};
|
||||
} catch {
|
||||
// Table missing (worker never ran migrations yet) or DB unavailable.
|
||||
|
||||
+1
-1
@@ -28,5 +28,5 @@ export async function proxy(req: NextRequest, event: NextFetchEvent) {
|
||||
export const config = {
|
||||
// Everything except the Auth.js endpoints, the login page and static assets.
|
||||
// Exact exclusions only: an org like "loginx" must still go through the gate.
|
||||
matcher: ["/((?!api/auth/|login$|_next/static/|_next/image/|favicon\\.ico$|icon\\.svg$).*)"],
|
||||
matcher: ["/((?!api/auth/|login$|_next/static/|_next/image/|favicon\\.ico$).*)"],
|
||||
};
|
||||
@@ -63,6 +63,8 @@ let starting = false;
|
||||
const pending: { runId: string; stream: LogStream; line: string; ts: Date }[] = [];
|
||||
const partial = new Map<string, string>();
|
||||
const tails = new Map<string, string[]>();
|
||||
/** The step last written to a run's `phase`: progress lines repeat it, a write per line isn't needed. */
|
||||
const steps = new Map<string, string>();
|
||||
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
@@ -84,7 +86,10 @@ function chunk(runId: string, stream: "stdout" | "stderr", data: Buffer, secrets
|
||||
if (!p.trim()) continue;
|
||||
addLog(runId, stream, p, secrets);
|
||||
const step = stepOf(p);
|
||||
if (step) void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
|
||||
if (step && steps.get(runId) !== step) {
|
||||
steps.set(runId, step);
|
||||
void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,6 +341,7 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
|
||||
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
|
||||
partial.delete(`${id}:${stream}`);
|
||||
}
|
||||
steps.delete(id);
|
||||
if (current === cur) current = null;
|
||||
const dir = runDir(id);
|
||||
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
|
||||
|
||||
+41
-1
@@ -1,4 +1,5 @@
|
||||
// Delete a model: its files on disk, then its database rows.
|
||||
// Delete a model: its files on disk, then its database rows. Or ("remove" jobs) only some of its
|
||||
// files, which were already taken out of the selection; the model stays.
|
||||
// Only files that belong to the repo (any revision we know of) and hf's .cache folder are removed;
|
||||
// anything else in the folder is kept and logged, and the folder stays if it isn't empty.
|
||||
|
||||
@@ -58,6 +59,7 @@ export class DeleteRunner implements Runner {
|
||||
interrupt() {}
|
||||
|
||||
async run(): Promise<void> {
|
||||
if (this.job.purpose === "remove") return this.removeFiles();
|
||||
const root = resolve(coreEnv().MODELS_DIR);
|
||||
const dir = modelDir(root, this.model.localPath);
|
||||
const deleted: string[] = [];
|
||||
@@ -104,4 +106,42 @@ export class DeleteRunner implements Runner {
|
||||
log.error(`job ${this.job.id}: deleting ${this.model.repoId} failed`, err);
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete the files a "remove" job names, if they are still unselected (the user may have re-added one). */
|
||||
private async removeFiles(): Promise<void> {
|
||||
const dir = modelDir(resolve(coreEnv().MODELS_DIR), this.model.localPath);
|
||||
const d = db();
|
||||
const named = this.job.result?.removePaths ?? [];
|
||||
const rows = named.length
|
||||
? await d.select().from(modelFiles).where(and(eq(modelFiles.modelId, this.model.id), inArray(modelFiles.path, named)))
|
||||
: [];
|
||||
const removed: string[] = [];
|
||||
try {
|
||||
for (const f of rows) {
|
||||
if (f.selected) {
|
||||
this.jobLog.system(`Kept ${f.path}: it is selected again.`);
|
||||
continue;
|
||||
}
|
||||
const existed = await removeLocalFile(dir, f.path);
|
||||
removed.push(f.path);
|
||||
this.jobLog.system(existed ? `Deleted ${f.path} (${formatBytes(f.size)}).` : `${f.path} wasn't on disk.`);
|
||||
}
|
||||
await removeEmptyDirs(dir);
|
||||
await this.jobLog.close();
|
||||
await d.batch([
|
||||
d.update(jobs).set({ state: "completed", finishedAt: new Date(), result: { removePaths: named, removed } }).where(eq(jobs.id, this.job.id)),
|
||||
...(removed.length
|
||||
? [d.update(modelFiles).set({ state: "pending", checkedAt: new Date() }).where(and(eq(modelFiles.modelId, this.model.id), inArray(modelFiles.path, removed)))]
|
||||
: []),
|
||||
]);
|
||||
log.info(`removed ${removed.length} file(s) from ${this.model.repoId}`);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.jobLog.system(`Failed after removing ${removed.length} file(s): ${message}`);
|
||||
await this.jobLog.close();
|
||||
await d.update(jobs).set({ state: "failed", finishedAt: new Date(), errorCode: "unknown", errorMessage: message }).where(eq(jobs.id, this.job.id));
|
||||
log.error(`job ${this.job.id}: removing files from ${this.model.repoId} failed`, err);
|
||||
}
|
||||
await settleModelStatus(this.model.id);
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import { XetCounter } from "./hf-progress";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import { ProgressSampler } from "./progress-sampler";
|
||||
import type { Runner } from "./runner";
|
||||
import { SpeedMeter } from "./speed";
|
||||
import { Throttle } from "./throttle";
|
||||
@@ -319,7 +320,9 @@ export class DownloadRunner implements Runner {
|
||||
);
|
||||
child.on("close", (code, signal) => done({ code, signal }));
|
||||
running.add(this);
|
||||
const throttleTimer = this.throttle(dir, expected);
|
||||
// One sampler for progress and the speed limit; it skips files it already found complete.
|
||||
const sampler = new ProgressSampler(dir, expected);
|
||||
const throttleTimer = this.throttle(sampler);
|
||||
|
||||
// Progress from bytes on disk, written to the DB once per second.
|
||||
const xetBytes = new XetCounter();
|
||||
@@ -331,7 +334,7 @@ export class DownloadRunner implements Runner {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const progress = steadyProgress(last, await this.sample(dir, expected));
|
||||
const progress = steadyProgress(last, await sampler.sample());
|
||||
last = progress;
|
||||
const onDisk = progress.reduce((s, p) => s + p.done, 0);
|
||||
const doneBytes = Math.min(this.job.totalBytes, Math.max(onDisk, alreadyDone + xetBytes.bytes));
|
||||
@@ -351,7 +354,7 @@ export class DownloadRunner implements Runner {
|
||||
* Enforce Settings → Downloads → Speed limit by pausing hf while it is ahead of the budget
|
||||
* (see Throttle). The limit is re-read every few seconds, so changes apply to running downloads.
|
||||
*/
|
||||
private throttle(dir: string, expected: ExpectedFile[]): NodeJS.Timeout {
|
||||
private throttle(sampler: ProgressSampler): NodeJS.Timeout {
|
||||
let total: number | null = null;
|
||||
let readAt = 0;
|
||||
let bucket: Throttle | null = null;
|
||||
@@ -383,7 +386,7 @@ export class DownloadRunner implements Runner {
|
||||
const limit = total / Math.max(1, running.size);
|
||||
if (!bucket) bucket = new Throttle(limit);
|
||||
bucket.limit = limit;
|
||||
const bytes = (await this.sample(dir, expected)).reduce((s, p) => s + p.done, 0);
|
||||
const bytes = (await sampler.sample()).reduce((s, p) => s + p.done, 0);
|
||||
if (bucket.update(Date.now(), bytes)) this.pause();
|
||||
else this.resume();
|
||||
} catch (err) {
|
||||
@@ -406,6 +409,7 @@ export class DownloadRunner implements Runner {
|
||||
if (this.child.exitCode === null) this.child.kill("SIGCONT");
|
||||
}
|
||||
|
||||
/** Every file, looked at fresh (before hf starts and after it exits). */
|
||||
private async sample(dir: string, expected: ExpectedFile[]) {
|
||||
const incomplete = await listIncomplete(dir);
|
||||
return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete)));
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import type { ExpectedFile, FileProgress } from "./hf-layout";
|
||||
import { ProgressSampler, SHARE_MS } from "./progress-sampler";
|
||||
|
||||
const files: ExpectedFile[] = [
|
||||
{ path: "a.gguf", size: 100, etags: ["a"] },
|
||||
{ path: "b.gguf", size: 200, etags: ["b"] },
|
||||
];
|
||||
|
||||
/** A fake disk: `done[path]` bytes per file; counts what the sampler looks at. */
|
||||
function fakeDisk() {
|
||||
const done: Record<string, number> = { "a.gguf": 0, "b.gguf": 0 };
|
||||
const looked: string[] = [];
|
||||
let listed = 0;
|
||||
let clock = 0;
|
||||
const measure = async (_dir: string, f: ExpectedFile): Promise<FileProgress> => {
|
||||
looked.push(f.path);
|
||||
return { done: done[f.path], complete: done[f.path] === f.size };
|
||||
};
|
||||
const listPartials = async () => {
|
||||
listed++;
|
||||
return [];
|
||||
};
|
||||
const sampler = new ProgressSampler("/models/x", files, measure, listPartials, () => clock);
|
||||
return {
|
||||
sampler,
|
||||
done,
|
||||
looked,
|
||||
listed: () => listed,
|
||||
later: (ms = SHARE_MS) => void (clock += ms),
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProgressSampler", () => {
|
||||
it("doesn't look at a file again once it is complete", async () => {
|
||||
const d = fakeDisk();
|
||||
d.done["a.gguf"] = 100;
|
||||
d.done["b.gguf"] = 50;
|
||||
assert.deepEqual(await d.sampler.sample(), [{ done: 100, complete: true }, { done: 50, complete: false }]);
|
||||
d.later();
|
||||
d.done["b.gguf"] = 120;
|
||||
assert.deepEqual(await d.sampler.sample(), [{ done: 100, complete: true }, { done: 120, complete: false }]);
|
||||
assert.deepEqual(d.looked, ["a.gguf", "b.gguf", "b.gguf"]);
|
||||
});
|
||||
|
||||
it("stops listing partial files when everything is complete", async () => {
|
||||
const d = fakeDisk();
|
||||
d.done["a.gguf"] = 100;
|
||||
d.done["b.gguf"] = 200;
|
||||
await d.sampler.sample();
|
||||
assert.equal(d.listed(), 1);
|
||||
d.later();
|
||||
assert.deepEqual(await d.sampler.sample(), [{ done: 100, complete: true }, { done: 200, complete: true }]);
|
||||
assert.equal(d.listed(), 1);
|
||||
assert.equal(d.looked.length, 2);
|
||||
});
|
||||
|
||||
it("shares samples taken close together (progress and speed limit)", async () => {
|
||||
const d = fakeDisk();
|
||||
const [x, y] = await Promise.all([d.sampler.sample(), d.sampler.sample()]);
|
||||
assert.equal(x, y);
|
||||
d.later(SHARE_MS - 1);
|
||||
assert.equal(await d.sampler.sample(), x);
|
||||
d.later(1);
|
||||
assert.notEqual(await d.sampler.sample(), x);
|
||||
assert.equal(d.listed(), 2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// Bytes on disk of a running download, for the progress timer (every second) and the speed limit
|
||||
// (every 250 ms). Both used to look at every file each time: a stat per file, hf's .metadata for
|
||||
// every file that already had its size, and the partial files, which on a network share added up to
|
||||
// hundreds of operations a second. Now:
|
||||
// - a file found complete isn't looked at again during the run (hf moves a finished file into
|
||||
// place; it doesn't go back to partial),
|
||||
// - with every file complete, the partial files aren't listed either,
|
||||
// - samples asked for within SHARE_MS of each other are one sample.
|
||||
// The check after hf exits doesn't use this: it looks at every file again.
|
||||
|
||||
import { bytesOnDisk, type ExpectedFile, type FileProgress, listIncomplete } from "./hf-layout";
|
||||
|
||||
export const SHARE_MS = 200;
|
||||
|
||||
export class ProgressSampler {
|
||||
private complete: boolean[];
|
||||
private last: { at: number; result: Promise<FileProgress[]> } | null = null;
|
||||
|
||||
constructor(
|
||||
private dir: string,
|
||||
private files: ExpectedFile[],
|
||||
private measure: typeof bytesOnDisk = bytesOnDisk,
|
||||
private listPartials: typeof listIncomplete = listIncomplete,
|
||||
private now: () => number = Date.now,
|
||||
) {
|
||||
this.complete = files.map(() => false);
|
||||
}
|
||||
|
||||
sample(): Promise<FileProgress[]> {
|
||||
const at = this.now();
|
||||
if (this.last && at - this.last.at < SHARE_MS) return this.last.result;
|
||||
const result = this.take();
|
||||
this.last = { at, result };
|
||||
// A failed sample isn't handed out again.
|
||||
result.catch(() => {
|
||||
if (this.last?.result === result) this.last = null;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private async take(): Promise<FileProgress[]> {
|
||||
const partials = this.complete.every(Boolean) ? [] : await this.listPartials(this.dir);
|
||||
return Promise.all(
|
||||
this.files.map(async (f, i) => {
|
||||
if (this.complete[i]) return { done: f.size, complete: true };
|
||||
const p = await this.measure(this.dir, f, partials);
|
||||
if (p.complete) this.complete[i] = true;
|
||||
return p;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// The models-folder scan, on a temporary folder and SQLite database.
|
||||
// Runs with `--conditions=react-server` (see package.json).
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "kaname-scan-"));
|
||||
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
|
||||
const modelsDir = join(dir, "models");
|
||||
process.env.MODELS_DIR = modelsDir;
|
||||
|
||||
let scan: typeof import("./scan");
|
||||
let D: typeof import("@/lib/db/client");
|
||||
let S: typeof import("@/lib/db/schema");
|
||||
|
||||
before(async () => {
|
||||
const { runMigrations } = await import("@/lib/db/migrate");
|
||||
await runMigrations();
|
||||
scan = await import("./scan");
|
||||
D = await import("@/lib/db/client");
|
||||
S = await import("@/lib/db/schema");
|
||||
});
|
||||
|
||||
after(() => {
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {}
|
||||
});
|
||||
|
||||
function put(path: string, bytes = 3) {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, "x".repeat(bytes));
|
||||
}
|
||||
|
||||
const tick = () => new Promise((r) => setTimeout(r, 5));
|
||||
|
||||
async function stored() {
|
||||
const rows = await D.db().select().from(S.localFolders);
|
||||
return Object.fromEntries(rows.map((r) => [r.path, r]));
|
||||
}
|
||||
|
||||
describe("models folder scan", () => {
|
||||
it("writes only new or changed folders and removes the ones that are gone", async () => {
|
||||
put(join(modelsDir, "org", "a", "model.gguf"));
|
||||
put(join(modelsDir, "org", "b", "shards", "x.safetensors"));
|
||||
assert.equal(await scan.scanModelsDir(modelsDir), 2);
|
||||
const first = await stored();
|
||||
|
||||
await tick();
|
||||
assert.equal(await scan.scanModelsDir(modelsDir), 2);
|
||||
const second = await stored();
|
||||
assert.equal(second["org/a"].scannedAt.getTime(), first["org/a"].scannedAt.getTime(), "unchanged: not written");
|
||||
assert.equal(second["org/b"].scannedAt.getTime(), first["org/b"].scannedAt.getTime(), "unchanged: not written");
|
||||
|
||||
await tick();
|
||||
put(join(modelsDir, "org", "a", "extra.json"), 10);
|
||||
rmSync(join(modelsDir, "org", "b"), { recursive: true });
|
||||
assert.equal(await scan.scanModelsDir(modelsDir), 1);
|
||||
const third = await stored();
|
||||
assert.deepEqual(Object.keys(third), ["org/a"]);
|
||||
assert.equal(third["org/a"].fileCount, 2);
|
||||
assert.deepEqual(third["org/a"].files.map((f) => f.path), ["extra.json", "model.gguf"]);
|
||||
assert.ok(third["org/a"].scannedAt.getTime() > first["org/a"].scannedAt.getTime(), "changed: written");
|
||||
});
|
||||
|
||||
it("compares the file list, not only the counts", () => {
|
||||
const at = new Date();
|
||||
const found = { path: "o/m", files: [{ path: "b.gguf", size: 2 }], fileCount: 1, totalBytes: 2, commit: null, scannedAt: at };
|
||||
const same = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 2, commit: null };
|
||||
assert.deepEqual(scan.folderChanges([same], [found]), { insert: [], update: [], remove: [] });
|
||||
const renamed = { ...same, filesJson: JSON.stringify([{ path: "a.gguf", size: 2 }]) };
|
||||
assert.deepEqual(scan.folderChanges([renamed], [found]).update, [found]);
|
||||
});
|
||||
});
|
||||
+41
-2
@@ -4,6 +4,7 @@
|
||||
|
||||
import { readdir, readFile, stat } from "node:fs/promises";
|
||||
import { join, relative, sep } from "node:path";
|
||||
import { eq, inArray, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { localFolders, models } from "@/lib/db/schema";
|
||||
import { HF_CACHE_DIR } from "./hf-layout";
|
||||
@@ -65,7 +66,29 @@ async function hfCommit(folder: string): Promise<string | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Scan MODELS_DIR and replace the `local_folders` table with folders no model uses. */
|
||||
/** A stored folder, its file list as the JSON text it is stored as (compared, never parsed). */
|
||||
export type StoredFolder = { path: string; filesJson: string; fileCount: number; totalBytes: number; commit: string | null };
|
||||
|
||||
/**
|
||||
* What to write so `local_folders` matches a scan: new folders, changed ones, and the paths of
|
||||
* folders that are gone. Unchanged folders aren't written: the scan runs every 2 minutes by
|
||||
* default, and rewriting every folder's file list each time added up to hundreds of MB a day.
|
||||
*/
|
||||
export function folderChanges(stored: StoredFolder[], found: FoundFolder[]) {
|
||||
const before = new Map(stored.map((s) => [s.path, s]));
|
||||
const insert: FoundFolder[] = [];
|
||||
const update: FoundFolder[] = [];
|
||||
for (const f of found) {
|
||||
const s = before.get(f.path);
|
||||
if (!s) insert.push(f);
|
||||
else if (s.fileCount !== f.fileCount || s.totalBytes !== f.totalBytes || s.commit !== (f.commit ?? null) || s.filesJson !== JSON.stringify(f.files)) update.push(f);
|
||||
}
|
||||
const seen = new Set(found.map((f) => f.path));
|
||||
const remove = stored.filter((s) => !seen.has(s.path)).map((s) => s.path);
|
||||
return { insert, update, remove };
|
||||
}
|
||||
|
||||
/** Scan MODELS_DIR and update the `local_folders` table to the folders no model uses. */
|
||||
export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||
const used = new Set((await db().select({ p: models.localPath }).from(models)).map((m) => m.p));
|
||||
const found: FoundFolder[] = [];
|
||||
@@ -84,6 +107,22 @@ export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||
}
|
||||
}
|
||||
const d = db();
|
||||
await d.batch([d.delete(localFolders), ...found.map((f) => d.insert(localFolders).values(f))]);
|
||||
const stored = await d
|
||||
.select({
|
||||
path: localFolders.path,
|
||||
// The raw JSON text: comparing it is enough, parsing every list each scan isn't needed.
|
||||
filesJson: sql<string>`${localFolders.files}`,
|
||||
fileCount: localFolders.fileCount,
|
||||
totalBytes: localFolders.totalBytes,
|
||||
commit: localFolders.commit,
|
||||
})
|
||||
.from(localFolders);
|
||||
const { insert, update, remove } = folderChanges(stored, found);
|
||||
const writes = [
|
||||
...(remove.length ? [d.delete(localFolders).where(inArray(localFolders.path, remove))] : []),
|
||||
...insert.map((f) => d.insert(localFolders).values(f)),
|
||||
...update.map((f) => d.update(localFolders).set(f).where(eq(localFolders.path, f.path))),
|
||||
];
|
||||
if (writes.length > 0) await d.batch(writes as [(typeof writes)[number], ...typeof writes]);
|
||||
return found.length;
|
||||
}
|
||||
Reference in new issue
Block a user