Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f862717158 | ||
|
|
d27e79bba0 | ||
|
|
5a8893e7db | ||
|
|
80ccf800df | ||
|
|
90d6007b55 | ||
|
|
85d79b6f7a | ||
|
|
02756ddf90 | ||
|
|
422e46bf65 | ||
|
|
67cd0c945a | ||
|
|
6b779debf7 | ||
|
|
6f4932e04d | ||
|
|
d58bff3437 | ||
|
|
d10a491042 | ||
|
|
2e56351e96 | ||
|
|
7239ba2692 | ||
|
|
76d851896e | ||
|
|
16c3fcc113 | ||
|
|
aab48d6181 |
No files matched your search
@@ -4,6 +4,74 @@ All notable changes to this project are documented here.
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
|
||||
step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.20.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Local models have a model card again:** the folder's `README.md`. The worker reads it when it
|
||||
scans the models folder (the web app can't see that folder), so edits show up after the next
|
||||
scan. Relative images and links in it are left out.
|
||||
|
||||
## [0.19.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Import a folder that isn't on Hugging Face** (Add model → Found in the models folder → Import →
|
||||
**Add as local model**): Kaname adds every file in the folder as it is, named after the folder.
|
||||
Local models have no pinned commit, model card or model tree, and no Hub checks, updates or
|
||||
downloads. Verify still checks that each file is there with the right size; deep verify isn't
|
||||
offered because there are no Hub hashes to compare with.
|
||||
|
||||
## [0.18.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- **Your own background picture** (Settings → Appearance): upload an image and every page header
|
||||
draws it as the dot matrix instead of *The Creation of Adam*; click the preview to choose the part
|
||||
that stays in view. The browser turns it into dots, so only those are saved (not the image).
|
||||
**Use the built-in painting** switches back.
|
||||
|
||||
## [0.17.0] - 2026-11-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Several open tabs no longer stall Kaname.** Every tab with live progress kept one or two
|
||||
connections open, and over plain HTTP a browser allows six per server: the third tab loaded
|
||||
slowly and a fourth not at all. Live updates are now short requests, one poller per tab shared by
|
||||
everything on the page, paused while the tab is in the background. The server also no longer
|
||||
grows in memory while a tab stays open, and an idle page no longer redraws every 5 seconds.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Lighter library page**: folders found in the models folder no longer bring their whole file
|
||||
list (up to 5,000 entries each) into the page; **Import** loads it when you click it. Search and
|
||||
filter counts are computed once per change instead of on every progress update.
|
||||
- **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K
|
||||
search load only what they show (headline numbers, the quality score), not every run's full
|
||||
results; the list refreshed every 3 s during a run now sends a fraction of the data.
|
||||
- **Less JavaScript per page** (10–29 KB gzipped less on every page): the dot painting's data is
|
||||
loaded once and cached instead of being part of each page, the ⌘K search loads when you first
|
||||
reach for it, and the endpoint pages no longer include database code. The painting is drawn once
|
||||
per page view instead of twice, and at most once per frame while the window is resized.
|
||||
- **Less disk activity**: the models folder scan writes only folders that changed (it rewrote
|
||||
every found folder's file list each time, every 2 minutes by default), and download progress
|
||||
no longer re-checks files that are already complete, which matters on network shares. A
|
||||
benchmark's current step is written when it changes, not for every line BetterBench prints.
|
||||
- **Fewer and smaller Hugging Face requests**: adding a model right after looking it up reuses the
|
||||
file list it just fetched (a commit's files never change), the author's avatar loads alongside,
|
||||
and the regular Hub check asks only for the commit SHA instead of the full model info.
|
||||
- The **Model card** tab shows the page at once and the card when it arrives from the Hub.
|
||||
- Database indexes for the queries the live view and the worker repeat every few seconds (the
|
||||
migration runs by itself on start).
|
||||
- **The image is 427 MB instead of 1.04 GB.** The web server runs as Next.js standalone output
|
||||
(only the files it uses instead of all of `node_modules`), the worker is bundled, and neither the
|
||||
build cache nor the downloaded archives end up in the image; build-only packages (`shadcn`,
|
||||
`tw-animate-css`) are dev dependencies. The worker container used about 40 MB at idle instead of
|
||||
about 190 MB in our test. Building the image again after a code change reuses npm's and Next's
|
||||
caches (the Next build went from 30 to 12 seconds). Nothing changes in `compose.yaml` or `.env`.
|
||||
|
||||
## [0.16.0] - 2026-10-30
|
||||
|
||||
A new look, a search for everything (⌘K / Ctrl+K), removing single files, and an easier deployment
|
||||
|
||||
+35
-26
@@ -9,43 +9,52 @@ 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 \
|
||||
@@ -65,9 +74,9 @@ 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/
|
||||
|
||||
@@ -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
|
||||
@@ -143,7 +143,8 @@ 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.
|
||||
|
||||
@@ -55,7 +55,7 @@ case "$role" in
|
||||
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:`).
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 705 KiB |
@@ -0,0 +1,2 @@
|
||||
CREATE INDEX `benchmark_runs_state_idx` ON `benchmark_runs` (`state`,`created_at`);--> statement-breakpoint
|
||||
CREATE INDEX `jobs_finished_idx` ON `jobs` (`finished_at`);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `models` ADD `source` text DEFAULT 'hub' NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `local_folders` ADD `readme` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `local_readme` text;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -169,6 +169,27 @@
|
||||
"when": 1793115558680,
|
||||
"tag": "0023_scan_schedule",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 24,
|
||||
"version": "6",
|
||||
"when": 1793567055573,
|
||||
"tag": "0024_polling_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 25,
|
||||
"version": "6",
|
||||
"when": 1794093022425,
|
||||
"tag": "0025_local_models",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 26,
|
||||
"version": "6",
|
||||
"when": 1794093954553,
|
||||
"tag": "0026_local_readme",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,6 +15,27 @@ const eslintConfig = defineConfig([
|
||||
// Bundled worker output
|
||||
"dist/**",
|
||||
]),
|
||||
// A value import from the schema in a client component puts drizzle-orm and every table
|
||||
// definition into the browser bundle. Enums are in @/lib/db/enums; types are fine. Pages, layouts
|
||||
// and route handlers run on the server only.
|
||||
{
|
||||
files: ["src/components/**/*.{ts,tsx}", "src/hooks/**/*.{ts,tsx}", "src/app/**/*.{ts,tsx}"],
|
||||
ignores: ["src/app/**/page.tsx", "src/app/**/layout.tsx", "src/app/**/route.ts"],
|
||||
rules: {
|
||||
"@typescript-eslint/no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
paths: [
|
||||
{
|
||||
name: "@/lib/db/schema",
|
||||
allowTypeImports: true,
|
||||
message: "In client code this bundles drizzle-orm and every table. Import enums from @/lib/db/enums.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -3,6 +3,14 @@ import type { NextConfig } from "next";
|
||||
const nextConfig: NextConfig = {
|
||||
// Native SQLite driver: load from node_modules at runtime instead of bundling.
|
||||
serverExternalPackages: ["@libsql/client", "libsql"],
|
||||
// The Docker image runs the standalone server: only the files the server needs instead of all of
|
||||
// node_modules (see Dockerfile). Local `next build` / `next start` stay as they are.
|
||||
output: process.env.NEXT_OUTPUT === "standalone" ? "standalone" : undefined,
|
||||
// Nothing uses next/image (model cards show the Hub's images as they are). With the optimizer off
|
||||
// (/_next/image answers 404), sharp and its native libvips (28 MB) stay out of the standalone
|
||||
// output; "next-server" is the key Next applies to its own server's trace.
|
||||
images: { unoptimized: true },
|
||||
outputFileTracingExcludes: { "next-server": ["**/node_modules/sharp/**/*", "**/node_modules/@img/**/*"] },
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+389
-5
File diff suppressed because it is too large.
Load diff
+4
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.16.0",
|
||||
"version": "0.20.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
@@ -14,7 +14,7 @@
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
|
||||
"test": "tsx --conditions=react-server --test \"src/**/*.test.ts\"",
|
||||
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs && 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"
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,14 @@ export function DownloadCard({
|
||||
modelId,
|
||||
status,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
status: ModelStatus;
|
||||
/** The repo or pinned commit is gone from the Hub; no new downloads. */
|
||||
hubMissing: boolean;
|
||||
/** A local model (no Hub repo): nothing to download or repair, no hashes to deep-verify against. */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const { snapshot } = useLive({ model: modelId });
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -58,15 +61,16 @@ export function DownloadCard({
|
||||
: latest?.state === "failed" && latest.kind === "download"
|
||||
? "Retry"
|
||||
: "Download missing";
|
||||
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
const canDownload = !open && !local && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && (!neverRan || local) && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !local && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
|
||||
let hint = "Downloads the selected files at the pinned commit.";
|
||||
let hint = local ? "A local folder: Kaname keeps its files as they are." : "Downloads the selected files at the pinned commit.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
else if (open) hint = "Runs in the background; you can close this page.";
|
||||
else if (status === "deleting") hint = "Deleting…";
|
||||
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
else if (local && (verifyProblems > 0 || status === "incomplete")) hint = "Some files are missing or changed. A local model can't be repaired from the Hub.";
|
||||
else if (status === "ready") hint = "All selected files are present.";
|
||||
|
||||
const showProgress =
|
||||
@@ -77,7 +81,7 @@ export function DownloadCard({
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
|
||||
<DownloadIcon className="size-4 text-muted-foreground" />
|
||||
{open ? jobLabel(open) : "Download"}
|
||||
{open ? jobLabel(open) : local ? "Files" : "Download"}
|
||||
</h3>
|
||||
{latest && <JobStateBadge job={latest} />}
|
||||
</div>
|
||||
@@ -145,15 +149,17 @@ export function DownloadCard({
|
||||
<ShieldCheckIcon />
|
||||
Verify
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, true))}
|
||||
title="Hash every file and compare with the Hub (slow: reads every byte)"
|
||||
>
|
||||
Deep verify
|
||||
</Button>
|
||||
{!local && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, true))}
|
||||
title="Hash every file and compare with the Hub (slow: reads every byte)"
|
||||
>
|
||||
Deep verify
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -121,7 +121,7 @@ export function FilesHeader({
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
|
||||
· {formatBytes(totalBytes)} · {sha ? `commit ${shortSha(sha)}` : "local folder"}
|
||||
</span>
|
||||
</span>
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -68,7 +68,7 @@ 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, action }: { entry: Entry; href: string; muted?: boolean; showState: boolean; action?: React.ReactNode }) {
|
||||
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;
|
||||
@@ -76,8 +76,8 @@ function Row({ entry, href, muted, showState, action }: { entry: Entry; href: st
|
||||
<li className="flex items-center pr-3">
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
target={href ? "_blank" : undefined}
|
||||
rel={href ? "noreferrer" : undefined}
|
||||
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
|
||||
className={cn(
|
||||
// Fixed status column so sizes line up between selected and unselected rows.
|
||||
@@ -125,6 +125,7 @@ export function FilesTab({
|
||||
freeBytes,
|
||||
busy,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
repoId: string;
|
||||
@@ -134,10 +135,13 @@ export function FilesTab({
|
||||
freeBytes: number | null;
|
||||
busy: boolean;
|
||||
hubMissing: boolean;
|
||||
/** A local model (no Hub repo): files don't link anywhere. */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const hub = `https://huggingface.co/${repoId}`;
|
||||
// Split files link to their folder (all parts), single files to the file itself.
|
||||
const href = (e: Entry) => {
|
||||
if (local) return undefined;
|
||||
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
|
||||
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import "server-only";
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
|
||||
import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { shortSha } from "@/lib/format";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
|
||||
// Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts,
|
||||
// styles or event handlers, only the tags/attributes GitHub-style READMEs normally use.
|
||||
@@ -17,9 +22,84 @@ const schema = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
|
||||
const base = `https://huggingface.co/${repoId}`;
|
||||
/**
|
||||
* The Model card tab: the README at the pinned commit, fetched from the Hub (cached per commit).
|
||||
* Rendered inside a Suspense boundary, so the rest of the page doesn't wait for the Hub.
|
||||
*/
|
||||
export async function ModelCardSection({ repoId, sha }: { repoId: string; sha: string }) {
|
||||
const hub = `https://huggingface.co/${repoId}`;
|
||||
const card = await fetchModelCard(repoId, sha).catch(() => undefined);
|
||||
if (!card) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
|
||||
<a href={hub} target="_blank" rel="noreferrer" className="underline">
|
||||
Open on Hugging Face
|
||||
</a>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<ModelCard markdown={card} repoId={repoId} sha={sha} />
|
||||
<div className="mt-6 flex justify-end">
|
||||
<a
|
||||
href={`${hub}/blob/${sha}/README.md`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
README.md @ {shortSha(sha)}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Model card tab of a local model: the folder's README.md, as the worker last read it. Relative
|
||||
* images and links are dropped: the web app can't serve files from the models folder.
|
||||
*/
|
||||
export function LocalModelCardSection({ markdown, localPath }: { markdown: string | null; localPath: string }) {
|
||||
if (!markdown) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This folder has no README.md. Add one to <code className="font-mono">{localPath}</code> and it shows up here after the
|
||||
next scan of the models folder.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<ModelCard markdown={markdown} />
|
||||
<p className="mt-6 text-right text-xs text-muted-foreground">
|
||||
README.md in <code className="font-mono">{localPath}</code>, as of the last scan
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelCardSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3" aria-busy="true" aria-label="Loading the model card">
|
||||
<Skeleton className="h-7 w-2/5" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-11/12" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
<Skeleton className="mt-3 h-5 w-1/4" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a repo's README like the Hub: relative links/images point at the pinned commit. Without a
|
||||
* repo (a local model's README) they are dropped.
|
||||
*/
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId?: string; sha?: string }) {
|
||||
const base = repoId ? `https://huggingface.co/${repoId}` : null;
|
||||
return (
|
||||
<article className="prose prose-sm max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-img:inline-block prose-img:my-1 prose-pre:bg-muted prose-pre:text-foreground prose-table:text-xs">
|
||||
<ReactMarkdown
|
||||
@@ -29,6 +109,7 @@ export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId:
|
||||
const safe = defaultUrlTransform(url);
|
||||
if (!safe || safe.startsWith("#") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(safe)) return safe;
|
||||
// Relative path inside the repo: images from /resolve, links to /blob, both at the pinned SHA.
|
||||
if (!base) return null;
|
||||
const path = safe.replace(/^\.?\//, "");
|
||||
return key === "src" ? `${base}/resolve/${sha}/${path}` : `${base}/blob/${sha}/${path}`;
|
||||
}}
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
ArrowDownIcon,
|
||||
BoxIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FileTextIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
@@ -17,6 +16,7 @@ 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";
|
||||
@@ -26,8 +26,7 @@ import { ModelStatusBadge } from "@/components/model-status-badge";
|
||||
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 { LocalModelCardSection, ModelCardSection, ModelCardSkeleton } from "./model-card";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
@@ -94,6 +93,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const { model, files } = data;
|
||||
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
|
||||
|
||||
// A local model has no Hub repo: no commit, Hub checks or model tree; its README is the model card.
|
||||
const local = model.source === "local";
|
||||
const tab: TabId = TABS.some((t) => t.id === sp.tab) ? (sp.tab as TabId) : "files";
|
||||
const [author, name] = model.repoId.split("/");
|
||||
const hub = `https://huggingface.co/${model.repoId}`;
|
||||
@@ -101,13 +102,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
|
||||
@@ -139,7 +140,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</Link>
|
||||
<span className="font-normal text-muted-foreground">/</span>
|
||||
<span className="break-all">{name}</span>
|
||||
<CopyButton value={model.repoId} label="Copy repo ID" />
|
||||
<CopyButton value={model.repoId} label={local ? "Copy name" : "Copy repo ID"} />
|
||||
{!local && (
|
||||
<a
|
||||
href={hub}
|
||||
target="_blank"
|
||||
@@ -150,7 +152,16 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
>
|
||||
🤗
|
||||
</a>
|
||||
)}
|
||||
<ModelStatusBadge status={model.status} />
|
||||
{local && (
|
||||
<span
|
||||
title="A folder in the models folder without a Hugging Face repo"
|
||||
className="inline-flex h-5 items-center rounded-4xl border border-foreground/15 bg-background/80 px-2 text-xs font-medium text-muted-foreground"
|
||||
>
|
||||
local
|
||||
</span>
|
||||
)}
|
||||
<HubStateBadge state={model.hubState} />
|
||||
{update && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
|
||||
@@ -253,28 +264,12 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
{tab === "card" && (
|
||||
<div className="p-5 sm:p-6">
|
||||
{card ? (
|
||||
<>
|
||||
<ModelCard markdown={card} repoId={model.repoId} sha={model.pinnedSha} />
|
||||
<div className="mt-6 flex justify-end">
|
||||
<a
|
||||
href={`${hub}/blob/${model.pinnedSha}/README.md`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
README.md @ {shortSha(model.pinnedSha)}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
{local ? (
|
||||
<LocalModelCardSection markdown={model.localReadme} localPath={model.localPath} />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
|
||||
<a href={hub} target="_blank" rel="noreferrer" className="underline">
|
||||
Open on Hugging Face
|
||||
</a>
|
||||
</p>
|
||||
<Suspense fallback={<ModelCardSkeleton />}>
|
||||
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -288,6 +283,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
|
||||
busy={model.status === "downloading"}
|
||||
hubMissing={hubMissing}
|
||||
local={local}
|
||||
/>
|
||||
)}
|
||||
{tab === "jobs" && (
|
||||
@@ -299,20 +295,20 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
<aside className="flex flex-col gap-4">
|
||||
<SideCard>
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} local={local} />
|
||||
</SideCard>
|
||||
|
||||
{runs.length > 0 && (
|
||||
<SideCard title="Benchmarks" icon={GaugeIcon}>
|
||||
<div className="flex flex-col gap-1">
|
||||
{runs.slice(0, 5).map((r) => {
|
||||
const h = headline(r.summary);
|
||||
const h = r.headline;
|
||||
return (
|
||||
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
|
||||
{r.kind === "eval" ? (r.qualityScore != null ? `quality ${r.qualityScore}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
|
||||
</span>
|
||||
</span>
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
@@ -332,6 +328,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd>{quants.length > 0 ? quants.join(", ") : `${selected.length} file${selected.length === 1 ? "" : "s"}`}</dd>
|
||||
<dt className="text-muted-foreground">Size</dt>
|
||||
<dd className="tabular-nums">{formatBytes(selectedBytes)}</dd>
|
||||
{local ? (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Source</dt>
|
||||
<dd>Local folder, no Hugging Face repo</dd>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Commit</dt>
|
||||
<dd className="flex items-center gap-1">
|
||||
<a href={`${hub}/commit/${model.pinnedSha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline" title={model.pinnedSha}>
|
||||
@@ -344,6 +347,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd>
|
||||
<LocalTime value={model.downloadedAt} />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Path</dt>
|
||||
<dd className="flex min-w-0 items-center gap-1">
|
||||
<span className="truncate font-mono text-xs" title={`$MODELS_DIR/${model.localPath}`}>
|
||||
@@ -363,6 +368,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd className="flex flex-col font-mono text-xs">{model.excludePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
|
||||
</>
|
||||
)}
|
||||
{!local && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">On the Hub</dt>
|
||||
<dd className="flex flex-col items-start gap-0.5">
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
|
||||
@@ -384,6 +391,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
|
||||
<HubCheckButton modelId={model.id} />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Added</dt>
|
||||
<dd>
|
||||
<LocalTime value={model.createdAt} />
|
||||
@@ -391,6 +400,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</dl>
|
||||
</SideCard>
|
||||
|
||||
{!local && (
|
||||
<SideCard title="Model tree" icon={SparklesIcon}>
|
||||
<ModelTree
|
||||
repoId={model.repoId}
|
||||
@@ -410,6 +420,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
</SideCard>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</PageHero>
|
||||
|
||||
@@ -175,6 +175,21 @@ export function AddModelForm({
|
||||
});
|
||||
}
|
||||
|
||||
/** Import without a Hub repo: every file in the folder, kept as it is. */
|
||||
async function addAsLocal() {
|
||||
if (!importFolder) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const { id } = await postJson<{ id: string }>("/api/models", { source: "local", localPath: importFolder.path });
|
||||
toast.success(`${importFolder.path} added as a local model`);
|
||||
onAdded(id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function addToLibrary() {
|
||||
if (!result) return;
|
||||
setSubmitting(true);
|
||||
@@ -241,6 +256,18 @@ export function AddModelForm({
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{importFolder && (
|
||||
<div className="mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t pt-4">
|
||||
<p className="min-w-0 flex-1 text-sm text-muted-foreground">
|
||||
<span className="font-medium text-foreground">Not on Hugging Face?</span> Add the folder as a local model: all{" "}
|
||||
{importFolder.fileCount} file{importFolder.fileCount === 1 ? "" : "s"} as they are, without Hub checks, updates or
|
||||
downloads.
|
||||
</p>
|
||||
<Button type="button" variant="outline" onClick={addAsLocal} disabled={submitting || loading}>
|
||||
{submitting ? "Adding…" : "Add as local model"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ 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 }) {
|
||||
@@ -37,7 +38,9 @@ export function AddModelPanel({
|
||||
setOpen: (open: boolean) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
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) {
|
||||
@@ -51,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 {
|
||||
@@ -89,7 +108,8 @@ export function AddModelPanel({
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{folders.length} folder{folders.length === 1 ? " isn't" : "s aren't"} in the library yet. Import matches
|
||||
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again.
|
||||
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again,
|
||||
or adds {folders.length === 1 ? "it" : "them"} as a local model if there is no Hub repo.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
|
||||
@@ -109,15 +129,8 @@ export function AddModelPanel({
|
||||
{f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)}
|
||||
{f.commit && <> · hf commit {shortSha(f.commit)}</>}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setImporting(f);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Import
|
||||
<Button size="sm" variant="outline" disabled={fetching != null} onClick={() => void startImport(f)}>
|
||||
{fetching === f.path ? "Loading…" : "Import"}
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib
|
||||
import { CONFIG_ROWS, targetName } from "@/lib/benchmark-view";
|
||||
import type { PairedResult } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
import type { RunRow } from "../benchmark-list";
|
||||
|
||||
const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
|
||||
|
||||
@@ -56,7 +56,7 @@ function Side({ label, name, value, unit }: { label: string; name: string; value
|
||||
);
|
||||
}
|
||||
|
||||
export function AbReport({ run }: { run: ListRow }) {
|
||||
export function AbReport({ run }: { run: RunRow }) {
|
||||
const ab = run.ab;
|
||||
const a = run.snapshot;
|
||||
const b = run.snapshotB;
|
||||
|
||||
@@ -39,7 +39,7 @@ import {
|
||||
modelName,
|
||||
targetName,
|
||||
} from "@/lib/benchmark-view";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
import type { RunRow } from "../benchmark-list";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { RunMetaCard } from "@/components/run-meta";
|
||||
import {
|
||||
@@ -68,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());
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
)}
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -5,7 +5,6 @@ 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";
|
||||
@@ -21,8 +20,8 @@ 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,20 +3,22 @@ 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 (
|
||||
@@ -46,7 +48,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
</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>
|
||||
);
|
||||
|
||||
@@ -27,7 +27,9 @@ import {
|
||||
type Filters,
|
||||
matchesFilters,
|
||||
matchesQuery,
|
||||
queryTerms,
|
||||
type SearchableModel,
|
||||
searchText,
|
||||
} from "@/lib/search";
|
||||
import { FacetFilter } from "./facet-filter";
|
||||
|
||||
@@ -45,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,
|
||||
@@ -64,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. */
|
||||
@@ -106,9 +109,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
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);
|
||||
@@ -147,7 +160,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
<FacetFilter
|
||||
key={facet}
|
||||
label={FACET_LABEL[facet]}
|
||||
values={facetCounts(searchable, facet, query, filters)}
|
||||
values={facetOptions[facet]}
|
||||
selected={filters[facet]}
|
||||
onChange={(v) => updateFilter(facet, v)}
|
||||
format={facet === "status" ? statusLabel : undefined}
|
||||
@@ -223,9 +236,15 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
|
||||
{r.trackedRevision}@{shortSha(r.pinnedSha)}
|
||||
</code>
|
||||
{r.source === "local" ? (
|
||||
<span className="text-xs text-muted-foreground" title="A folder without a Hugging Face repo">
|
||||
local
|
||||
</span>
|
||||
) : (
|
||||
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
|
||||
{r.trackedRevision}@{shortSha(r.pinnedSha)}
|
||||
</code>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
|
||||
<LocalTime value={r.downloadedAt} />
|
||||
|
||||
@@ -24,10 +24,7 @@ export default async function LibraryPage({ searchParams }: PageProps<"/">) {
|
||||
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: folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes })),
|
||||
}}
|
||||
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()} />;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
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";
|
||||
|
||||
@@ -6,13 +6,14 @@ 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 (
|
||||
<PageHero
|
||||
title="Settings"
|
||||
description="File labels, tags, and how Kaname downloads and scans models."
|
||||
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)]">
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
@@ -8,5 +8,6 @@ export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (
|
||||
const { id } = await params;
|
||||
const model = await getCheckedModel(id);
|
||||
if (!model) return apiError(404, "not_found", "Model not found.");
|
||||
if (model.source === "local") return apiError(409, "local_model", "This is a local model without a Hugging Face repo.");
|
||||
return NextResponse.json(await checkHub(model));
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { addModel, ModelError } from "@/lib/models";
|
||||
import { addLocalModel, addModel, ModelError } from "@/lib/models";
|
||||
import { addTag, normalizeTagName, TagError } from "@/lib/tags";
|
||||
|
||||
const Body = z.object({
|
||||
@@ -19,10 +19,28 @@ const Body = z.object({
|
||||
localPath: z.string().min(1).max(512).optional(),
|
||||
});
|
||||
|
||||
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
|
||||
/** A folder from the models folder without a Hub repo, added as it is. */
|
||||
const LocalBody = z.object({
|
||||
source: z.literal("local"),
|
||||
localPath: z.string().min(1).max(512),
|
||||
tags: z.array(z.string()).max(50).default([]),
|
||||
});
|
||||
|
||||
/**
|
||||
* Add a model to the library, pinned to the SHA the user reviewed, and queue its download. With
|
||||
* `source: "local"`, add a folder from the models folder that has no Hub repo instead (nothing queued).
|
||||
*/
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
const json = await req.json();
|
||||
if (json?.source === "local") {
|
||||
const body = LocalBody.parse(json);
|
||||
body.tags.forEach(normalizeTagName);
|
||||
const { id } = await addLocalModel({ localPath: body.localPath });
|
||||
for (const tag of body.tags) await addTag(id, tag);
|
||||
return NextResponse.json({ id, jobId: null }, { status: 201 });
|
||||
}
|
||||
const body = Body.parse(json);
|
||||
body.tags.forEach(normalizeTagName); // validate before anything is written
|
||||
const { id } = await addModel({
|
||||
repoId: body.repoId,
|
||||
|
||||
@@ -10,11 +10,11 @@ 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(), listTags()]);
|
||||
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.slice(0, 300).map((r) => ({
|
||||
benchmarks: runs.map((r) => ({
|
||||
id: r.id,
|
||||
label: r.label,
|
||||
kind: r.kind,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { getBackdrop, saveBackdrop, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Appearance: the custom picture behind the page headers (null for the built-in painting). */
|
||||
export const GET = withAuth(async () => NextResponse.json({ backdrop: await getBackdrop() }));
|
||||
|
||||
const Body = z.object({ backdrop: z.unknown() });
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json({ backdrop: await saveBackdrop(body.backdrop ?? null) });
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const INTERVAL_MS = 1_000;
|
||||
const KEEPALIVE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Server-Sent Events with live job state, polled from the DB once per second.
|
||||
* ?model=<id> jobs of one model (+ files of its newest job)
|
||||
* ?job=<id> one job with per-file progress and incremental log lines
|
||||
* (none) open and recently finished jobs (library view)
|
||||
* Events: "snapshot" (only when something changed) and "logs" (new lines).
|
||||
*/
|
||||
export const GET = withAuth(async (req) => {
|
||||
const url = new URL(req.url);
|
||||
const modelId = url.searchParams.get("model");
|
||||
const jobId = url.searchParams.get("job");
|
||||
let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0;
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const signal = req.signal;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
let last = "";
|
||||
let lastWrite = Date.now();
|
||||
const write = (chunk: string) => {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
lastWrite = Date.now();
|
||||
};
|
||||
const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
|
||||
try {
|
||||
write("retry: 3000\n\n");
|
||||
while (!signal.aborted) {
|
||||
const snapshot = await buildSnapshot(modelId, jobId);
|
||||
const serialized = JSON.stringify(snapshot);
|
||||
if (serialized !== last) {
|
||||
send("snapshot", snapshot);
|
||||
last = serialized;
|
||||
}
|
||||
if (jobId) {
|
||||
const lines = await listJobLogs(jobId, logCursor);
|
||||
if (lines.length > 0) {
|
||||
logCursor = lines[lines.length - 1].id;
|
||||
send("logs", lines);
|
||||
}
|
||||
}
|
||||
if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n");
|
||||
await sleep(INTERVAL_MS, signal);
|
||||
}
|
||||
} catch {
|
||||
// client went away or the stream was closed
|
||||
} finally {
|
||||
try {
|
||||
controller.close();
|
||||
} catch {}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
async function buildSnapshot(modelId: string | null, jobId: string | null) {
|
||||
const worker = await getWorkerStatus();
|
||||
if (jobId) {
|
||||
const job = await getJob(jobId);
|
||||
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
|
||||
}
|
||||
if (modelId) {
|
||||
const jobs = await listModelJobs(modelId);
|
||||
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
|
||||
return { worker, jobs, files };
|
||||
}
|
||||
return { worker, jobs: await listLiveJobs(), files: [] };
|
||||
}
|
||||
|
||||
function sleep(ms: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const t = setTimeout(resolve, ms);
|
||||
signal.addEventListener("abort", () => {
|
||||
clearTimeout(t);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,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>
|
||||
);
|
||||
}
|
||||
@@ -1,258 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import { Dialog } from "@base-ui/react/dialog";
|
||||
import {
|
||||
BoxIcon,
|
||||
CornerDownLeftIcon,
|
||||
DownloadIcon,
|
||||
GaugeIcon,
|
||||
LibraryIcon,
|
||||
MonitorIcon,
|
||||
MoonIcon,
|
||||
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, useSyncExternalStore } from "react";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState, useSyncExternalStore } 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[];
|
||||
};
|
||||
// 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();
|
||||
|
||||
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 OPEN_EVENT = "kaname:command-palette";
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { run: "speed run", ab: "A/B", eval: "quality eval" };
|
||||
/** ⌘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);
|
||||
|
||||
/** 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;
|
||||
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 = () => () => {};
|
||||
|
||||
/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */
|
||||
export function CommandPalette() {
|
||||
const router = useRouter();
|
||||
const { setTheme } = useTheme();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [index, setIndex] = useState<Index | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const list = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
|
||||
e.preventDefault();
|
||||
setOpen((o) => !o);
|
||||
}
|
||||
};
|
||||
const onOpen = () => setOpen(true);
|
||||
window.addEventListener("keydown", onKey);
|
||||
window.addEventListener("kaname:command-palette", onOpen);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
window.removeEventListener("kaname:command-palette", onOpen);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 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") },
|
||||
];
|
||||
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, 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>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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("kaname:command-palette"))}
|
||||
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"
|
||||
>
|
||||
|
||||
@@ -1,60 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { ADAM_DOTS, ADAM_H, ADAM_W } from "./adam-dots";
|
||||
import { createContext, useContext, useEffect, useMemo, useRef } from "react";
|
||||
import type { Backdrop } from "@/lib/backdrop";
|
||||
|
||||
const SPACING = 6; // CSS px between dot centres
|
||||
const levels = Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16));
|
||||
|
||||
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] = focus;
|
||||
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 = getComputedStyle(canvas).color;
|
||||
const dark = document.documentElement.classList.contains("dark");
|
||||
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 / (view * ADAM_W), height / ADAM_H);
|
||||
const offX = ax * width - fx * ADAM_W * scale;
|
||||
const offY = ay * height - fy * ADAM_H * scale;
|
||||
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, ADAM_W * scale);
|
||||
const oy = clampOff(offY, height, ADAM_H * scale);
|
||||
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(ADAM_H - 1, Math.max(0, Math.floor((y - oy) / scale)));
|
||||
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(ADAM_W - 1, Math.max(0, Math.floor((x - ox) / scale)));
|
||||
const v = levels[iy * ADAM_W + ix] / 15;
|
||||
const r = maxR * (dark ? v : 1 - v);
|
||||
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);
|
||||
@@ -62,17 +104,29 @@ export function DotPainting({
|
||||
}
|
||||
}
|
||||
};
|
||||
draw();
|
||||
const resize = new ResizeObserver(draw);
|
||||
// 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(draw);
|
||||
const theme = new MutationObserver(schedule);
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(frame);
|
||||
resize.disconnect();
|
||||
theme.disconnect();
|
||||
};
|
||||
}, [view, fx, fy, ax, ay]);
|
||||
}, [customGrid, v, fx, fy, ax, ay]);
|
||||
|
||||
return <canvas ref={ref} aria-hidden className={className} />;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,25 +1,12 @@
|
||||
"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) {
|
||||
|
||||
+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,100 @@
|
||||
// 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];
|
||||
|
||||
/**
|
||||
* Where a model comes from: a Hub repo pinned to a commit, or a folder in the models folder that has
|
||||
* no Hub repo ("local": no pinned commit, no Hub checks, updates or downloads).
|
||||
*/
|
||||
export const MODEL_SOURCES = ["hub", "local"] as const;
|
||||
export type ModelSource = (typeof MODEL_SOURCES)[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];
|
||||
+43
-90
@@ -8,6 +8,29 @@ 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_SOURCES,
|
||||
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 +59,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). */
|
||||
@@ -81,9 +90,12 @@ export const models = sqliteTable(
|
||||
{
|
||||
id: id(),
|
||||
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
|
||||
repoId: text("repo_id").notNull(), // "org/name"
|
||||
repoId: text("repo_id").notNull(), // "org/name"; for local models the folder's path
|
||||
source: text("source", { enum: MODEL_SOURCES }).notNull().default("hub"),
|
||||
trackedRevision: text("tracked_revision").notNull().default("main"),
|
||||
pinnedSha: text("pinned_sha").notNull(),
|
||||
pinnedSha: text("pinned_sha").notNull(), // "" for local models
|
||||
/** Local models: the folder's README.md, read by the worker (the web app can't see MODELS_DIR). */
|
||||
localReadme: text("local_readme"),
|
||||
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
|
||||
localPath: text("local_path").notNull(),
|
||||
/**
|
||||
@@ -181,16 +193,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",
|
||||
@@ -218,37 +220,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];
|
||||
|
||||
/** 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 jobs = sqliteTable(
|
||||
"jobs",
|
||||
{
|
||||
@@ -276,12 +247,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",
|
||||
{
|
||||
@@ -299,9 +272,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",
|
||||
{
|
||||
@@ -355,7 +325,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". */
|
||||
@@ -366,6 +336,9 @@ 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"),
|
||||
/** The folder's README.md (capped), so an import as a local model has a model card. */
|
||||
readme: text("readme"),
|
||||
/** When a scan last wrote this folder (found it, or found it changed). */
|
||||
scannedAt: ts("scanned_at").notNull(),
|
||||
});
|
||||
|
||||
@@ -425,9 +398,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.
|
||||
@@ -499,12 +469,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;
|
||||
@@ -518,9 +482,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. */
|
||||
@@ -539,10 +500,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;
|
||||
@@ -773,7 +730,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(
|
||||
@@ -792,14 +753,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,16 +6,17 @@ 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,
|
||||
"id" | "repoId" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
|
||||
"id" | "repoId" | "source" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
|
||||
>;
|
||||
|
||||
const CHECKED_COLUMNS = {
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
source: models.source,
|
||||
pinnedSha: models.pinnedSha,
|
||||
trackedRevision: models.trackedRevision,
|
||||
hubMissingSince: models.hubMissingSince,
|
||||
@@ -45,7 +46,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;
|
||||
@@ -128,7 +129,7 @@ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Prom
|
||||
return db()
|
||||
.select(CHECKED_COLUMNS)
|
||||
.from(models)
|
||||
.where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff)))
|
||||
.where(and(eq(models.source, "hub"), or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff))))
|
||||
.orderBy(asc(models.lastCheckedAt))
|
||||
.limit(limit);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { eq, isNull } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models } from "@/lib/db/schema";
|
||||
import { getAuthorAvatar, getRepoInfo } from "./client";
|
||||
@@ -26,7 +26,7 @@ export async function backfillMetadata(onError: (repoId: string, err: unknown) =
|
||||
const missing = await db()
|
||||
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha })
|
||||
.from(models)
|
||||
.where(isNull(models.metadataFetchedAt));
|
||||
.where(and(eq(models.source, "hub"), isNull(models.metadataFetchedAt)));
|
||||
let updated = 0;
|
||||
for (const m of missing) {
|
||||
try {
|
||||
|
||||
+5
-1
@@ -16,7 +16,7 @@ import {
|
||||
|
||||
export class JobError extends Error {
|
||||
constructor(
|
||||
public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing",
|
||||
public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing" | "local_model",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -50,6 +50,7 @@ export async function queueDownload(
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
if (model.source === "local") throw new JobError("local_model", "This is a local model without a Hugging Face repo: there's nothing to download.", 409);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new JobError("hub_missing", missing, 409);
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
@@ -87,6 +88,9 @@ export async function queueVerify(modelId: string, deep: boolean): Promise<{ job
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
if (deep && model.source === "local") {
|
||||
throw new JobError("local_model", "A local model has no Hub hashes to compare with. Use Verify (existence and size).", 409);
|
||||
}
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
|
||||
@@ -16,6 +16,7 @@ export async function listLibrary() {
|
||||
.select({
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
source: models.source,
|
||||
trackedRevision: models.trackedRevision,
|
||||
pinnedSha: models.pinnedSha,
|
||||
remoteSha: models.remoteSha,
|
||||
|
||||
@@ -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"));
|
||||
|
||||
+56
-5
@@ -7,14 +7,14 @@ 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 { getLocalFolder, 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";
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update",
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update" | "local_model",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -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)),
|
||||
@@ -90,6 +91,54 @@ export async function addModel(input: {
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a folder from the models folder that has no Hub repo as a local model: every file the scan
|
||||
* found, kept as it is. No pinned commit, so no Hub checks, updates, downloads or deep verify; its
|
||||
* name is the folder's path.
|
||||
*/
|
||||
export async function addLocalModel(input: { localPath: string }): Promise<{ id: string }> {
|
||||
const folder = await getLocalFolder(input.localPath);
|
||||
if (!folder) throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
|
||||
if (folder.files.length === 0) throw new ModelError("empty_selection", "This folder has no files.", 400);
|
||||
if (folder.files.length < folder.fileCount) {
|
||||
throw new ModelError("empty_selection", `This folder has ${folder.fileCount} files, more than a local model can list (${folder.files.length}).`, 400);
|
||||
}
|
||||
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, folder.path) });
|
||||
if (usedBy) throw new ModelError("already_exists", `The folder ${folder.path} already belongs to ${usedBy.repoId}.`, 409);
|
||||
const existing = await db().query.models.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(models.repoType, "model"), eq(sql`lower(${models.repoId})`, folder.path.toLowerCase())),
|
||||
});
|
||||
if (existing) throw new ModelError("already_exists", `${folder.path} is already in the library.`, 409);
|
||||
|
||||
const d = db();
|
||||
const modelId = ulid();
|
||||
const now = new Date();
|
||||
const fileRows = folder.files.map((f) => ({ modelId, path: f.path, size: f.size, selected: true, state: "present" as const, checkedAt: folder.scannedAt }));
|
||||
await d.batch([
|
||||
d.insert(models).values({
|
||||
id: modelId,
|
||||
repoId: folder.path,
|
||||
source: "local",
|
||||
trackedRevision: "",
|
||||
pinnedSha: "",
|
||||
localPath: folder.path,
|
||||
status: "ready",
|
||||
localReadme: folder.readme,
|
||||
// Nothing to fetch from the Hub.
|
||||
metadataFetchedAt: now,
|
||||
}),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
d.delete(localFolders).where(eq(localFolders.path, folder.path)), // no longer an import candidate
|
||||
]);
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/** Refuse Hub actions (download, update, adding files) for a local model. */
|
||||
export function assertHubModel(model: { source: string }): void {
|
||||
if (model.source === "local") throw new ModelError("local_model", "This is a local model without a Hugging Face repo.", 409);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
|
||||
* files that aren't part of the repo are kept); without, only the library entry goes and the
|
||||
@@ -126,6 +175,7 @@ export async function applyUpdate(id: string): Promise<{ jobId: string; sha: str
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
assertHubModel(model);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new ModelError("hub_missing", missing, 409);
|
||||
if (await hasOpenJob(id)) {
|
||||
@@ -201,6 +251,7 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
|
||||
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);
|
||||
assertHubModel(model);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new ModelError("hub_missing", missing, 409);
|
||||
|
||||
|
||||
+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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,92 @@
|
||||
// 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, readme: 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]);
|
||||
});
|
||||
|
||||
it("writes a folder again when its README changed", () => {
|
||||
const at = new Date();
|
||||
const found = { path: "o/m", files: [{ path: "README.md", size: 3 }], fileCount: 1, totalBytes: 3, commit: null, readme: "new", scannedAt: at };
|
||||
const stored = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 3, commit: null, readme: "old" };
|
||||
assert.deepEqual(scan.folderChanges([stored], [found]).update, [found]);
|
||||
});
|
||||
|
||||
it("reads README.md in any case, and only at the top level", async () => {
|
||||
const folder = join(dir, "readme-test"); // outside MODELS_DIR: no other test scans it
|
||||
put(join(folder, "sub", "README.md"), 1);
|
||||
assert.equal(await scan.readReadme(folder), null);
|
||||
writeFileSync(join(folder, "ReadMe.md"), "# Hello\n");
|
||||
assert.equal(await scan.readReadme(folder), "# Hello\n");
|
||||
});
|
||||
});
|
||||
+72
-4
@@ -4,10 +4,14 @@
|
||||
|
||||
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";
|
||||
|
||||
/** Longer READMEs are cut off here (it's stored in the database). */
|
||||
const MAX_README_BYTES = 512 * 1024;
|
||||
|
||||
/** Stop listing a folder's files after this many (the count stays exact). */
|
||||
const MAX_LISTED_FILES = 5_000;
|
||||
const SKIP_DIRS = new Set([".cache", ".git"]);
|
||||
@@ -65,9 +69,56 @@ async function hfCommit(folder: string): Promise<string | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Scan MODELS_DIR and replace the `local_folders` table with folders no model uses. */
|
||||
/** The folder's top-level README.md (any case), capped; null if there is none. */
|
||||
export async function readReadme(folder: string): Promise<string | null> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(folder, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const file = entries.find((e) => e.isFile() && e.name.toLowerCase() === "readme.md");
|
||||
if (!file) return null;
|
||||
const buf = await readFile(join(folder, file.name)).catch(() => null);
|
||||
if (!buf) return null;
|
||||
// Cut at a line break so a multi-byte character or a Markdown construct isn't split mid-way.
|
||||
const text = buf.subarray(0, MAX_README_BYTES).toString("utf8");
|
||||
return buf.length > MAX_README_BYTES ? text.slice(0, text.lastIndexOf("\n") + 1) : text;
|
||||
}
|
||||
|
||||
/** 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; readme: 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.readme !== (f.readme ?? 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. Also refreshes
|
||||
* the README of local models (their model card).
|
||||
*/
|
||||
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 inLibrary = await db().select({ id: models.id, p: models.localPath, source: models.source, readme: models.localReadme }).from(models);
|
||||
const used = new Set(inLibrary.map((m) => m.p));
|
||||
for (const m of inLibrary.filter((x) => x.source === "local")) {
|
||||
const readme = await readReadme(join(modelsDir, m.p));
|
||||
if (readme !== m.readme) await db().update(models).set({ localReadme: readme }).where(eq(models.id, m.id));
|
||||
}
|
||||
const found: FoundFolder[] = [];
|
||||
const now = new Date();
|
||||
for (const org of await subdirs(modelsDir)) {
|
||||
@@ -80,10 +131,27 @@ export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||
await walk(folder, folder, files, totals);
|
||||
if (totals.count === 0) continue;
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
found.push({ path, files, fileCount: totals.count, totalBytes: totals.bytes, commit: await hfCommit(folder), scannedAt: now });
|
||||
found.push({ path, files, fileCount: totals.count, totalBytes: totals.bytes, commit: await hfCommit(folder), readme: await readReadme(folder), scannedAt: now });
|
||||
}
|
||||
}
|
||||
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,
|
||||
readme: localFolders.readme,
|
||||
})
|
||||
.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;
|
||||
}
|
||||
@@ -159,7 +159,8 @@ export class VerifyRunner implements Runner {
|
||||
// hf records the etag it downloaded; a different one means another version of the file.
|
||||
const meta = await readMetadata(dir, f.path);
|
||||
const etags = [f.lfsSha256, f.blobOid].filter(Boolean);
|
||||
return meta && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
// Local models (no Hub repo) have no etags to compare with: existence and size is all.
|
||||
return meta && etags.length > 0 && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
}
|
||||
const actual = await this.hash(full, f, onBytes);
|
||||
const expected = f.lfsSha256 ?? f.blobOid;
|
||||
|
||||
Reference in new issue
Block a user