Compare commits

...
20 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 f0b4adda63 Release 0.8.0: deployments
Release / release (push) Successful in 3m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:30:14 +02:00
Pascal LinxweilerandClaude Opus 5.5 ea1f18cc74 Deployments: API keys, deploy from the library, reorganized form
- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:28:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 66e6a8c4f7 Deployments: llama.cpp web UI toggle, clearer start failures, log fixes
- Web UI option for llama.cpp deployments (--no-webui when off); the deployment
  page links to it on the published host port.
- Follow container logs after the start with tail=all: following a created
  container returned an already-closed stream, so startup output was lost.
- Failed starts name the cause from the log (vLLM ValueError, llama.cpp error
  lines) before the last output.
- A deployment's vLLM dtype replaces the runtime's --dtype instead of repeating it.
- vLLM memory estimate: 3 GiB overhead (measured ~6.9 GiB for SmolLM2-135M
  with a 4 GiB KV cache).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:01:52 +02:00
Pascal LinxweilerandClaude Opus 5.5 8b74fa69db Deployments: serve a model with a runtime container
- deployments + deployment_logs tables; desired/actual state reconciled by
  the worker (create/start/stop/remove via the socket proxy, /health wait,
  log follower, stats, memory guard, adopt/remove containers on restart).
- Pure command builder for llama-server and vllm serve (mmproj, MTP draft,
  KV cache types, dtype, KV cache size) with tests; file candidates per
  engine with tests.
- New main menu entry Deployments: list, new/edit form (runtime -> model
  and files -> launch options, live command preview), detail page with
  stats, log, endpoint and a streaming chat smoke test.

Not yet tested end-to-end against real containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:31:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 4f7ae1fc8c Fix image pull progress never being written
`void query` doesn't execute a Drizzle query (it runs on then/await), so
pull progress stayed at "Starting" until the pull finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:39:15 +02:00
Pascal LinxweilerandClaude Opus 5.5 a756eb3794 Release workflow: drop setup-node's npm cache
The act_runner cache server isn't reachable from job containers
(getCacheEntry ETIMEDOUT), so restoring and saving the cache timed out
for ~4.5 min each, ~9 of the ~12 minutes per release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:30:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 930126c5eb Release 0.7.0: runtimes and Docker connection
Release / release (push) Successful in 11m56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:27:18 +02:00
Pascal LinxweilerandClaude Opus 5.5 b68b4a2b23 Runtimes: Docker connection via socket proxy, runtime images, host info
- docker-proxy service (tecnativa/docker-socket-proxy) in both compose
  files; worker uses it via DOCKER_HOST with a dependency-free client.
- runtimes table with presets (llama.cpp CPU, vLLM CPU) and custom
  images; validation of image refs, env, args, devices (/dev/dri, /dev/kfd).
- Worker reports Docker/CPU/memory facts and detects its network and
  models mount; pulls images with progress; image state per runtime.
- Settings -> Runtimes page with host card, list, editor, pull/update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:24:59 +02:00
Pascal LinxweilerandClaude Opus 5.5 76683ffd7b Release 0.6.0: delete, verify/repair, update checks
Release / release (push) Successful in 11m55s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:02:22 +02:00
Pascal LinxweilerandClaude Opus 5.5 7864a492c9 Delete, verify/deep verify, repair and update checks
- Delete any model (incl. failed ones); the worker removes the repo's
  files (keeps foreign files and empty-folder cleanup), then the rows.
- Verify (existence, size, hf metadata) and deep verify (SHA-256 /
  git blob SHA-1 against the Hub) with missing/mismatch/extra report.
- Repair = download of the selection; broken files are deleted first
  because hf skips files whose metadata matches without checking them.
- Hub check resolves the tracked revision and stores which selected
  files a newer commit changes/adds/removes; Update pins it (old commit
  kept in model_revisions), downloads, then removes dropped files.
- Worker runs verify/delete jobs next to downloads (2 local slots).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:00:55 +02:00
Pascal LinxweilerandClaude Opus 5.5 c2c239bf16 Release 0.5.0: model pages, file labels, recommended files, import, Hub checks
Release / release (push) Successful in 11m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 00:12:41 +02:00
Pascal LinxweilerandClaude Opus 5.5 0247f257fb Recommended files with a quant; floating selection bar
Picking model weights in Add model or Download more also selects the
files that usually go with them (chat template, MTP head, mmproj, ...),
shown in a strip where each can be unchecked. Variants are matched by
quant, otherwise the best single one; kinds already selected aren't
added twice. Which kinds is set in Settings -> Downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:10:53 +02:00
Pascal LinxweilerandClaude Opus 5.5 145818f149 Import models that are already in the models folder
The worker scans MODELS_DIR (startup, every 2 min, on "Rescan") for
<org>/<name> folders that no model uses and stores them in local_folders.
The library lists them; Import opens Add model prefilled with the folder,
the commit hf recorded and the files on disk preselected. The import job
runs hf download into the existing folder: hf 2.1.1 hashes files it didn't
download itself, keeps matching ones and re-downloads the rest (verified
in Docker, including a corrupted file being replaced).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:01:58 +02:00
Pascal LinxweilerandClaude Opus 5.5 3603742637 Flag models deleted from the Hub; tag picker, tags in settings, account menu
- Worker checks each model's repo and pinned commit on the Hub every
  UPDATE_CHECK_INTERVAL_HOURS and after failed downloads; missing repos or
  commits are flagged (badge, banner, Status filter) and block new
  downloads. Local files are never touched. "Check now" on the model page.
- Tag picker dropdown ("Create new tag…" first, then existing tags) on the
  model page and in Add model.
- Settings: separate File labels and Tags pages; create tags there. Unused
  tags are no longer deleted automatically.
- Header: app icon, nav with active state, account menu with the OIDC
  profile picture, theme switch and sign out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 22:53:57 +02:00
Pascal LinxweilerandClaude Opus 5.5 df18415e02 Download more, file labels, split-file grouping, settings for labels and tags
- Files tab: "Download more" adds files to a model's selection and queues them
- Colored file labels (Model, MTP, Vision/mmproj, imatrix, Config, …)
- Split GGUF/safetensors parts shown and selected as one entry everywhere
- Settings page with a Labels section: file label names/colors, tag
  rename/recolor/delete; new settings table and tags.color
- Quants only count model weights

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:42:03 +02:00
Pascal LinxweilerandClaude Opus 5.5 5211ec9064 Fix hydration mismatch in progress bars on non-English browsers
Base UI formats aria-valuetext with the runtime locale (server: "50%", German browser: "50 %"). Pin the Progress wrapper to en-US.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:26:56 +02:00
Pascal LinxweilerandClaude Opus 5.5 6dc9527682 Model page: Files tab first with a new file list, colored tags, single Hub link
- Files is the default tab: icon/size/LFS/state per file, on-disk summary, unselected files collapsed
- Custom tags color-coded by name (editor, library, filter chips and menu)
- Header: only the Hugging Face link (top right); README link moved to the end of the model card
- App icon; proxy lets /icon.svg through

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:24:23 +02:00
Pascal LinxweilerandClaude Opus 5.5 5fadd64367 Model page: header, content and sidebar as consistent cards
Tabs become a segmented control in the content card header; drop the full-bleed header band and the page-wide tab line; files tab without nested boxes; download card heading matches the other sidebar cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:16:00 +02:00
Pascal LinxweilerandClaude Opus 5.5 1527fcd830 Hugging Face style model pages at /<org>/<name>
- Model URLs are the repo path (case-insensitive, canonical redirect);
  /models/<id> redirects
- Header with avatar, org/name + copy, task/format/arch/language/license
  pills, user tags, cross-links to the Hub (files @ sha, commits, community,
  base model) and tabs: rendered model card at the pinned commit, files, jobs
- Sidebar: download card, local copy, model tree with related local models
- Metadata gains author avatar and base relation (refetched once)
- Proxy matcher excludes only exact /login and /api/auth/ paths

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:12:39 +02:00
Pascal LinxweilerandClaude Opus 5.5 d16bd6dfee README: move NAS guide and config reference to the wiki
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:53:39 +02:00
161 changed files with 21514 additions and 647 deletions

No files matched your search

+1 -1
View File
@@ -37,7 +37,7 @@ KANAME_VERSION=
# ---------------------------------------------------------------------------
MAX_CONCURRENT_DOWNLOADS=1
# Hub update check interval; 0 disables it
# How often the worker checks every model on the Hub (still there? newer commit?); 0 disables it
UPDATE_CHECK_INTERVAL_HOURS=12
# 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk.
# 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps.
+2 -1
View File
@@ -14,10 +14,11 @@ jobs:
steps:
- uses: actions/checkout@v4
# No `cache: npm`: the runner's cache server isn't reachable from job containers here, and the
# restore + save timeouts cost ~9 minutes per run. `npm ci` alone takes ~20 s.
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- name: Resolve version and image name
run: |
+170
View File
@@ -6,6 +6,176 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.8.0] - 2026-10-06
Model testing, part two: deployments. Serve a downloaded model with a llama.cpp or vLLM runtime
container, tune its launch options, protect it with API keys and try it from Kaname.
No changes to `compose.yaml`; the new database tables are created on start.
### Added
- **Deployments** (new main menu entry): serve a downloaded model with a runtime container.
- **New deployment:** pick a runtime (only pulled images), then a model it can serve (llama.cpp:
downloaded GGUF files with the quant, optional mmproj for vision and MTP head / draft model for
speculative decoding; vLLM: safetensors repos with a config.json), then launch options: context
size, threads, parallel slots, KV cache types, flash attention, batch sizes (llama.cpp) or data
type, max sequences, KV cache GiB (vLLM), CPU and memory limits (with an estimate), an optional
published host port and extra arguments. A live preview shows the exact `docker run` command.
- The worker starts the container on Kaname's Docker network with the models mounted read-only,
waits for `/health`, follows the log, samples CPU/RAM every 5 s and refuses to start when the
memory limits of running deployments wouldn't fit. Containers keep running across worker
restarts; orphaned ones are removed.
- Deployment page: state, load time, live CPU/RAM, endpoint URLs (Docker network and published
port), live log, start/stop/edit/delete, and a "Try it" chat that streams the answer and shows
time to first token and tokens/s.
- llama.cpp's built-in **web UI** can be switched on or off per deployment (`--no-webui`); with a
published host port the deployment page links to it.
- A failed start names the cause from the log (e.g. vLLM's `ValueError` instead of the end of the
traceback), followed by the last lines of output.
- A deployment's vLLM data type replaces the runtime's `--dtype` instead of repeating the flag.
- Models and runtimes used by a deployment can't be deleted until the deployment is.
- **API keys** (Settings → API keys): add generated or own keys, show and copy them again later.
A deployment with "Require an API key" accepts any of them (`LLAMA_API_KEY`, `VLLM_API_KEY` or
`--api-key` for several vLLM keys); the values are masked in the shown command and in the log, and
Kaname's own "Try it" chat sends one. Key changes apply when a deployment restarts.
- **Deploy from the library:** a "Deploy" button in the library and on the model page opens a new
deployment with the model and a fitting runtime preselected. The library and the model page link
to the deployments that use a model.
- Deployment form reorganized: launch options in groups (General, Context, Performance, KV cache,
Resources, Extra arguments) with each field's flag next to its label, the command in its own step,
and extra arguments as flag/value rows with "+ Add argument" (also in the runtime form).
### Fixed
- Dropdowns were unreadable in dark mode (white option list with light text): native controls now
follow the theme.
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
written (Drizzle queries only run when awaited).
## [0.7.0] - 2026-10-06
First part of model testing: runtimes (llama.cpp, vLLM and your own images) and the Docker
connection through a socket proxy. Starting containers with a model comes next.
**Upgrade note:** `compose.yaml` has a new `docker-proxy` service and `DOCKER_HOST` on the worker;
copy them from `deploy/compose.yaml`.
### Added
- **Runtimes** (Settings → Runtimes): container images that serve models. Presets for the official
llama.cpp CPU server (`ghcr.io/ggml-org/llama.cpp:server`) and vLLM CPU
(`vllm/vllm-openai-cpu:v0.31.0`), plus your own images from any registry (e.g. patched forks) with
an engine type (llama.cpp- or vLLM-compatible), environment, extra arguments, shared memory,
device passthrough (only `/dev/dri…`, `/dev/kfd`) and an opt-in "NUMA tuning" switch (the
`CAP_SYS_NICE` + `seccomp=unconfined` that vLLM recommends on CPU; off by default).
- Pull and update runtime images from the UI, with progress and readable errors.
- Docker host card: Docker version, CPU model and features (AVX2, AVX-512, AMX, …), memory, and the
network and models source the worker detected from its own container.
- `docker-proxy` service (`tecnativa/docker-socket-proxy:v0.5.0`) in both compose files; the worker
reaches Docker only through it (`DOCKER_HOST`). New settings `DOCKER_HOST`,
`KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` (see the wiki).
## [0.6.0] - 2026-10-06
Delete models (with their files), verify and deep verify, one-click repair, and update checks
with a deliberate Update. Database migrations run automatically on start.
### Added
- **Delete** any model (also failed or incomplete ones), with confirmation. By default the worker
deletes its files from disk: only the repo's files and hf's `.cache`; files you put in the folder
yourself are kept, empty folders are removed. Unchecked, only the library entry goes and the folder
shows up under "Found in the models folder".
- **Verify** a model: every selected file is checked for existence, size and the version hf recorded;
reports missing files, size mismatches and extra files in the folder. **Deep verify** hashes every
file (SHA-256 for LFS files, git blob SHA-1 for small files) against the Hub, with progress.
- **Repair** re-downloads only what's missing or broken. Broken files are deleted before `hf` runs,
because `hf` skips a file whose metadata matches without checking its content or size.
- **Update checks:** the Hub check (every `UPDATE_CHECK_INTERVAL_HOURS` and "Check now") also
resolves the tracked revision. If there's a newer commit, the model shows "update available" (badge
in the library and a Status filter value, banner on the model page) with the selected files that
changed, were added or were removed. **Update** is a deliberate action: it pins the new commit (the
old one stays in the revision history), downloads changed and new files, and deletes files that are
no longer selected once the download succeeded.
- Download card: **Resume** for interrupted or cancelled downloads, **Retry** for failed ones.
- Job names in the job list and job page: Download, Download more, Import, Repair, Update, Verify,
Deep verify, Delete.
## [0.5.0] - 2026-10-06
Hugging Face style model pages, file labels, recommended files, importing models already on disk,
and flagging models deleted from the Hub. Database migrations run automatically on start.
### Added
- Model pages modeled on Hugging Face, built from cards: a header with org avatar, `org / name`
with copy button, pills for task, format, architecture, language and license, your tags and a
Hugging Face link; a content card with tabs:
- **Files** (default): selected files with type icon, size, LFS marker and local state
(downloaded, missing, size mismatch, …), a "on disk" progress summary, and the unselected repo
files collapsed below; each file links to the Hub at the pinned commit
- **Model card**: the repo's README at the pinned commit, rendered (sanitized HTML, relative
links/images resolved to the Hub)
- **Jobs**: download history
- Custom tags are color-coded: automatic color from the name, or one you pick in Settings.
- File labels in front of every file name: Model, MTP, Vision (mmproj), Draft, Adapter, imatrix,
Config, Tokenizer, Template, Docs, Image, Git (detected from the file name).
- Split files (`…-00001-of-00003.gguf`) are shown and selected as one entry with "N parts", the
combined size and a combined status, in the Files tab, Add model, Download more and progress lists.
- **Download more** in the Files tab: pick additional files (quick-select chips, checkboxes) and
download them; they're added to the model's selection. Files already on disk are skipped.
- **Settings** page (`/settings`), first section **Labels**: name and color per file label (with
reset), and rename, recolor or delete your tags. Stored in a new `settings` table.
- App icon (要).
- Sidebar with download status/actions, local copy details (commit, path, patterns) and a model
tree (base model → quantized/finetuned → this repo) listing other local models of the same base.
- Hub metadata now includes the author's avatar and the relation to the base model; existing models
are refetched once by the worker.
- Models deleted from Hugging Face are flagged, never deleted locally: the worker checks every model
every `UPDATE_CHECK_INTERVAL_HOURS` (and right after a failed download) whether the repo and the
pinned commit still exist. A deleted repo (or one made private) or a rewritten history shows a
warning badge in the library (searchable, and a value of the Status filter), a banner on the model
page, and blocks new downloads and "Download more". "On the Hub" in the sidebar shows the last
check, with "Check now".
- **Import models already on disk:** the worker scans the models folder (at startup, every
2 minutes and on "Rescan") for `<org>/<name>` folders that aren't in the library. They're listed
under "Found in the models folder"; **Import** opens Add model for that folder with the repo, the
commit hf recorded (if any) and the files already there preselected, marked "on disk". The import
job runs `hf download` into the existing folder: hf 2.1.1 hashes files it didn't download itself,
keeps those that match and downloads only missing or different ones. Other files in the folder
are left alone. Jobs show the purpose "import".
- **Recommended files:** picking a quant (chip or checkbox) in Add model or Download more also
selects the files that usually go with it, shown in a "Recommended with your quant" strip where
each can be unchecked. They drop out again when you deselect the quant. Variants are matched:
the MTP head or mmproj with the same quant if there is one, otherwise the best single one (mmproj:
F16, BF16, Q8_0, F32); nothing is added if the model already has one of that kind. Which kinds
(default: chat template, MTP, vision) is set in the new **Settings → Downloads**.
- Create tags in Settings (name and color), before any model uses them.
- Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your
existing tags with their colors, and "Manage tags…".
- Account menu in the header with your profile picture from the OIDC provider (initials as
fallback): name and email, links to the settings, theme (system/light/dark) and sign out.
### Changed
- Model URLs are the repo path, like on Hugging Face: `/unsloth/Qwen3-8B-GGUF` (case-insensitive,
redirects to the canonical spelling). Old `/models/<id>` links redirect.
- The auth gate excludes only exact paths (`/login`, `/api/auth/…`), so org names like `loginx`
can't bypass it.
- Quant labels (library column, Quant filter, "Local copy") only count model weights, not MTP,
mmproj or imatrix files.
- Tags are no longer deleted automatically when no model uses them anymore; delete them in Settings.
- Settings has separate pages for **File labels**, **Tags** and **Downloads**.
- The selection bar at the bottom of Add model is a floating card like the rest of the page.
- Header: app icon, navigation with icons and the current page highlighted.
- Docs: full configuration reference and the NAS guide moved to the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki); the README keeps the quick install.
### Fixed
- Hydration error in progress bars on non-English browsers (locale-dependent `aria-valuetext`).
## [0.4.0] - 2026-10-05
The app is now called **Kaname**; search, filters and tags.
+23 -35
View File
@@ -47,44 +47,15 @@ Open your `AUTH_URL`, sign in, click **Add model**. That's it.
**Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g.
`KANAME_VERSION=0.4.0` in `.env`. The running version is shown next to the app name.
### Storing models on a NAS
Mount the share on the Docker host and point `KANAME_MODELS_DIR` at it, e.g. in `/etc/fstab`:
```
truenas.lan:/mnt/tank/models /mnt/nas/models nfs4 rw,hard,noatime,_netdev 0 0
```
```bash
# .env
KANAME_MODELS_DIR=/mnt/nas/models
```
- Use NFSv4: the `hf` CLI uses file locks.
- The share must be writable for uid 1000 (dataset owner 1000, or TrueNAS *Mapall User/Group*).
- Mount it before the containers start (`_netdev`), otherwise Docker uses the empty local folder.
- Keep `KANAME_DATA_DIR` on local disk: SQLite doesn't work reliably on NFS.
## Configuration
All settings live in `.env` (see [`.env.example`](.env.example)):
| Variable | Default | |
| --- | --- | --- |
| `AUTH_URL` | | Public URL of Kaname (used for the OIDC redirect) |
| `AUTH_SECRET` | | Secret for session cookies |
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | | OIDC provider (authorization code + PKCE) |
| `OIDC_ALLOWED_GROUPS` | *(anyone)* | Comma-separated groups from the `groups` claim |
| `HF_TOKEN` | | Hugging Face token (read-only is enough) |
| `KANAME_DATA_DIR` | `./data` | Host folder for the SQLite DB (local disk) |
| `KANAME_MODELS_DIR` | `./models` | Host folder for downloaded models |
| `WEB_PORT` | `3000` | Host port of the web UI |
| `KANAME_VERSION` | `latest` | Image tag to run |
| `MAX_CONCURRENT_DOWNLOADS` | `1` | Downloads running in parallel |
| `UPDATE_CHECK_INTERVAL_HOURS` | `12` | Hub update checks (`0` = off) |
| `HF_HUB_DISABLE_XET` | `1` | `0` uses Xet transfers (progress then only moves in large jumps) |
All settings live in `.env`. The four steps above cover the required ones; the **[configuration
reference in the wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration)**
lists every option with defaults and examples (folders, ports, download tuning, OIDC groups, which
Hugging Face token to use).
Models end up in `<models folder>/<org>/<repo>/`, e.g. `models/unsloth/Qwen3-8B-GGUF/`.
More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki).
## Using it
@@ -93,12 +64,27 @@ Models end up in `<models folder>/<org>/<repo>/`, e.g. `models/unsloth/Qwen3-8B-
</p>
- **Add model:** enter a repo ID like `unsloth/Qwen3-8B-GGUF` (or paste the URL), click a quant, and
**Add & download**. You can add tags right there.
**Add & download**. Files that belong with the quant (chat template, MTP head, vision projector)
are selected along with it; choose which kinds in Settings → Downloads. You can add tags right there.
- **Search:** type anything: `unsloth qwen`, `q4_k_m`, `gemma`, `roleplay`. Every word has to match
somewhere (repo, author, base model family, architecture, quant, tags).
- **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so
you can bookmark a view.
- **Tags:** add or remove your own tags on a model's page; click a tag in the list to filter by it.
Create, rename and color them in Settings.
- **Import:** models you already have in the models folder (as `<org>/<name>`) show up under
"Found in the models folder"; **Import** matches them with the Hub repo and verifies the files
instead of downloading them again. See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models).
- **Verify / repair:** Verify checks every file's presence and size, Deep verify hashes them against
the Hub; Repair downloads only what's missing or broken.
- **Updates:** Kaname checks the Hub regularly and shows which of your files a newer commit changes;
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
model is flagged and your local copy is kept.
- **Delete:** removes the model and, if you want, its files from disk.
- **Runtimes:** register llama.cpp, vLLM or your own fork images and pull them from Settings → Runtimes
(groundwork for testing model configs). See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
## How it works
@@ -117,6 +103,8 @@ Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image):
to show accurate progress.
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
metadata after each download.
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
hashed and kept if they match, and downloaded again if not. Imports rely on this.
## Development
+22
View File
@@ -16,6 +16,11 @@ services:
worker:
<<: *app
command: worker
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
DOCKER_HOST: tcp://docker-proxy:2375
volumes: [data:/data, models:/models]
web:
@@ -23,6 +28,23 @@ services:
ports: ["${WEB_PORT:-3000}:3000"]
volumes: [data:/data]
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
volumes:
data:
models:
+19
View File
@@ -8,6 +8,8 @@ services:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
DOCKER_HOST: tcp://docker-proxy:2375
volumes:
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
@@ -20,3 +22,20 @@ services:
volumes:
- ${KANAME_DATA_DIR:-./data}:/data
restart: unless-stopped
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `models` ADD `base_relation` text;--> statement-breakpoint
ALTER TABLE `models` ADD `author_avatar_url` text;
+2
View File
@@ -0,0 +1,2 @@
-- Refetch Hub metadata once so existing models get author avatar and base relation.
UPDATE `models` SET `metadata_fetched_at` = NULL;
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE `settings` (
`key` text PRIMARY KEY NOT NULL,
`value` text NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `tags` ADD `color` text;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `models` ADD `hub_state` text;--> statement-breakpoint
ALTER TABLE `models` ADD `hub_missing_since` integer;
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE `local_folders` (
`path` text PRIMARY KEY NOT NULL,
`files` text NOT NULL,
`file_count` integer NOT NULL,
`total_bytes` integer NOT NULL,
`commit` text,
`scanned_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `worker_state` ADD `scan_requested_at` integer;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `jobs` ADD `result` text;--> statement-breakpoint
ALTER TABLE `models` ADD `update_diff` text;
+26
View File
@@ -0,0 +1,26 @@
CREATE TABLE `runtimes` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`engine` text NOT NULL,
`image` text NOT NULL,
`description` text,
`env` text DEFAULT '{}' NOT NULL,
`extra_args` text DEFAULT '[]' NOT NULL,
`devices` text DEFAULT '[]' NOT NULL,
`shm_size_mb` integer,
`numa_tuning` integer DEFAULT false NOT NULL,
`preset` text,
`image_state` text DEFAULT 'unknown' NOT NULL,
`image_id` text,
`image_size` integer,
`image_created` text,
`pull_requested_at` integer,
`pull_started_at` integer,
`pull_progress` text,
`pull_error` text,
`image_checked_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `worker_state` ADD `docker` text;
+37
View File
@@ -0,0 +1,37 @@
CREATE TABLE `deployment_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`deployment_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL,
FOREIGN KEY (`deployment_id`) REFERENCES `deployments`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `deployment_logs_idx` ON `deployment_logs` (`deployment_id`,`id`);--> statement-breakpoint
CREATE TABLE `deployments` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`runtime_id` text NOT NULL,
`model_id` text NOT NULL,
`options` text NOT NULL,
`cpus` real,
`memory_mb` integer,
`host_port` integer,
`desired_state` text DEFAULT 'stopped' NOT NULL,
`state` text DEFAULT 'stopped' NOT NULL,
`delete_requested_at` integer,
`container_id` text,
`container_name` text,
`command` text,
`image_id` text,
`started_at` integer,
`ready_at` integer,
`stopped_at` integer,
`exit_code` integer,
`error` text,
`stats` text,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`runtime_id`) REFERENCES `runtimes`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
+8
View File
@@ -0,0 +1,8 @@
CREATE TABLE `api_keys` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`key` text NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_keys_key_unique` ON `api_keys` (`key`);
+908
View File
@@ -0,0 +1,908 @@
{
"version": "6",
"dialect": "sqlite",
"id": "024725ee-3ede-4d7d-85b0-52dfd38971f8",
"prevId": "9c67e3d1-730e-4c71-ac1e-2ec7d0d37dea",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+908
View File
@@ -0,0 +1,908 @@
{
"id": "0388c49a-d01a-4c5a-9694-0d844297213f",
"prevId": "024725ee-3ede-4d7d-85b0-52dfd38971f8",
"version": "6",
"dialect": "sqlite",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"columnsFrom": [
"job_id"
],
"tableTo": "jobs",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"columnsFrom": [
"model_file_id"
],
"tableTo": "model_files",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"columnsFrom": [
"job_id"
],
"tableTo": "jobs",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"columnsFrom": [
"model_id"
],
"tableTo": "models",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"columnsFrom": [
"tag_id"
],
"tableTo": "tags",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
},
"internal": {
"indexes": {}
}
}
+946
View File
@@ -0,0 +1,946 @@
{
"version": "6",
"dialect": "sqlite",
"id": "84e7c88b-53c4-4eba-8f2f-7de08b494316",
"prevId": "0388c49a-d01a-4c5a-9694-0d844297213f",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+960
View File
@@ -0,0 +1,960 @@
{
"version": "6",
"dialect": "sqlite",
"id": "4bf01375-42a2-440f-aeba-69644c7bca95",
"prevId": "84e7c88b-53c4-4eba-8f2f-7de08b494316",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_tags": {
"name": "model_tags",
"columns": {
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_tags_tag_idx": {
"name": "model_tags_tag_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_tags_model_id_models_id_fk": {
"name": "model_tags_model_id_models_id_fk",
"tableFrom": "model_tags",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"model_tags_tag_id_tags_id_fk": {
"name": "model_tags_tag_id_tags_id_fk",
"tableFrom": "model_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"model_tags_model_id_tag_id_pk": {
"columns": [
"model_id",
"tag_id"
],
"name": "model_tags_model_id_tag_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_state": {
"name": "hub_state",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_missing_since": {
"name": "hub_missing_since",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_models": {
"name": "base_models",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"base_relation": {
"name": "base_relation",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"author_avatar_url": {
"name": "author_avatar_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"architecture": {
"name": "architecture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pipeline_tag": {
"name": "pipeline_tag",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"license": {
"name": "license",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hub_tags": {
"name": "hub_tags",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"metadata_fetched_at": {
"name": "metadata_fetched_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"tags": {
"name": "tags",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"tags_slug_uq": {
"name": "tags_slug_uq",
"columns": [
"slug"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"instance_id": {
"name": "instance_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_free_bytes": {
"name": "models_dir_free_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"models_dir_total_bytes": {
"name": "models_dir_total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+63
View File
@@ -29,6 +29,69 @@
"when": 1791221700558,
"tag": "0003_model_metadata_and_tags",
"breakpoints": true
},
{
"idx": 4,
"version": "6",
"when": 1791223472733,
"tag": "0004_model_avatar_relation",
"breakpoints": true
},
{
"idx": 5,
"version": "6",
"when": 1791223474007,
"tag": "0005_refetch_metadata",
"breakpoints": true
},
{
"idx": 6,
"version": "6",
"when": 1791224932279,
"tag": "0006_settings_and_tag_color",
"breakpoints": true
},
{
"idx": 7,
"version": "6",
"when": 1791233230682,
"tag": "0007_hub_state",
"breakpoints": true
},
{
"idx": 8,
"version": "6",
"when": 1791233749207,
"tag": "0008_local_folders",
"breakpoints": true
},
{
"idx": 9,
"version": "6",
"when": 1791238659338,
"tag": "0009_verify_update",
"breakpoints": true
},
{
"idx": 10,
"version": "6",
"when": 1791242201063,
"tag": "0010_runtimes",
"breakpoints": true
},
{
"idx": 11,
"version": "6",
"when": 1791278463453,
"tag": "0011_deployments",
"breakpoints": true
},
{
"idx": 12,
"version": "6",
"when": 1791281615301,
"tag": "0012_api_keys",
"breakpoints": true
}
]
}
+1708 -5
View File
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.4.0",
"version": "0.8.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -28,6 +28,10 @@
"next-themes": "^0.4.6",
"react": "19.2.8",
"react-dom": "19.2.8",
"react-markdown": "^10.1.0",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.1",
"server-only": "^0.0.1",
"shadcn": "^4.21.1",
"sonner": "^2.0.8",
@@ -37,6 +41,7 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tailwindcss/typography": "^0.5.20",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
@@ -0,0 +1,99 @@
"use client";
import { Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
/**
* Delete a model, whatever its state (failed, incomplete, ready, …). By default its files are
* deleted from disk too (by the worker); unchecked, only the library entry goes.
*/
export function DeleteModelButton({
id,
repoId,
localPath,
mayHaveFiles,
}: {
id: string;
repoId: string;
localPath: string;
/** False if nothing was ever downloaded, so there's nothing on disk to ask about. */
mayHaveFiles: boolean;
}) {
const router = useRouter();
const [deleteFiles, setDeleteFiles] = useState(true);
const [pending, setPending] = useState(false);
async function remove() {
setPending(true);
const res = await fetch(`/api/models/${id}${mayHaveFiles && deleteFiles ? "?files=1" : ""}`, { method: "DELETE" });
if (res.ok) {
toast.success(res.status === 202 ? `Deleting ${repoId} and its files…` : `${repoId} removed from the library`);
router.push("/");
router.refresh();
} else {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Delete failed (${res.status})`);
setPending(false);
}
}
return (
<AlertDialog>
<AlertDialogTrigger
render={
<Button
variant="outline"
size="sm"
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
/>
}
>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {repoId}?</AlertDialogTitle>
<AlertDialogDescription>
{mayHaveFiles
? "The model is removed from the library, including its tags and job history."
: "Nothing was downloaded yet, so this only removes the library entry."}
</AlertDialogDescription>
</AlertDialogHeader>
{mayHaveFiles && (
<label className="flex cursor-pointer items-start gap-2.5 rounded-md bg-muted/50 px-3 py-2.5 text-sm">
<Checkbox checked={deleteFiles} onCheckedChange={(v) => setDeleteFiles(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>Also delete the files from disk</span>
<span className="text-xs text-muted-foreground">
Deletes the repo&apos;s files in <code className="font-mono">{localPath}</code>. Files you put there yourself are
kept. Unchecked, the folder stays and shows up under &ldquo;Found in the models folder&rdquo;.
</span>
</span>
</label>
)}
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove} disabled={pending}>
{mayHaveFiles && deleteFiles ? "Delete with files" : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
@@ -0,0 +1,169 @@
"use client";
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { VerifyResult } from "@/components/verify-result";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { groupJobFiles } from "@/lib/file-groups";
import { formatBytes, percent } from "@/lib/format";
import { jobLabel } from "@/lib/job-labels";
const OPEN = ["queued", "downloading", "verifying"];
const VERIFY_KINDS = ["verify", "deep_verify"];
/** Sidebar card: current job with progress, the last verify result, and the model's actions. */
export function DownloadCard({
modelId,
status,
hubMissing,
}: {
modelId: string;
status: ModelStatus;
/** The repo or pinned commit is gone from the Hub; no new downloads. */
hubMissing: boolean;
}) {
const { snapshot } = useLive({ model: modelId });
const [busy, setBusy] = useState(false);
const jobs = snapshot?.jobs ?? [];
const latest = jobs[0];
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
// The newest verify, unless a download ran after it (its result would be stale).
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
const verify = lastCheck && VERIFY_KINDS.includes(lastCheck.kind) && lastCheck.state === "completed" ? lastCheck : undefined;
const verifyProblems = verify?.result
? (verify.result.missing?.length ?? 0) + (verify.result.sizeMismatch?.length ?? 0) + (verify.result.hashMismatch?.length ?? 0)
: 0;
async function run(fn: () => Promise<unknown>) {
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
}
const neverRan = jobs.length === 0;
const downloadLabel = neverRan
? "Download"
: latest?.state === "interrupted" || latest?.state === "cancelled"
? "Resume"
: latest?.state === "failed" && latest.kind === "download"
? "Retry"
: "Download missing";
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
let hint = "Downloads the selected files at the pinned commit.";
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
else if (open) hint = "Runs in the background; you can close this page.";
else if (status === "deleting") hint = "Deleting…";
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
else if (status === "ready") hint = "All selected files are present.";
const showProgress =
latest && latest.kind !== "delete" && !(latest.state === "completed" && (status === "ready" || VERIFY_KINDS.includes(latest.kind)));
return (
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-2">
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
<DownloadIcon className="size-4 text-muted-foreground" />
{open ? jobLabel(open) : "Download"}
</h3>
{latest && <JobStateBadge job={latest} />}
</div>
<p className="text-xs text-muted-foreground">{hint}</p>
{showProgress && <JobProgress job={latest} compact />}
{latest?.state === "failed" && latest.errorMessage && (
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
{latest.errorMessage}
</pre>
)}
{files.length > 0 && (
<ul className="flex flex-col gap-1.5">
{files.map((f) => (
<li key={f.path} className="flex flex-col gap-1">
<div className="flex justify-between gap-2 text-xs">
<span className="truncate font-mono" title={f.path}>
{f.path}
{f.parts > 1 && <span className="text-muted-foreground"> · {f.parts} parts</span>}
</span>
<span className="shrink-0 text-muted-foreground tabular-nums">{formatBytes(f.expectedBytes)}</span>
</div>
<Progress value={percent(f.doneBytes, f.expectedBytes)} />
</li>
))}
</ul>
)}
{verify?.result && !open && (
<div className="rounded-md bg-muted/50 px-2.5 py-2">
<VerifyResult result={verify.result} deep={verify.kind === "deep_verify"} />
</div>
)}
<div className="flex flex-wrap gap-2">
{open ? (
<Button variant="destructive" size="sm" disabled={busy || open.cancelRequested} onClick={() => run(() => cancelJob(open.id))}>
{open.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
<>
{needsRepair ? (
<Button size="sm" disabled={busy} onClick={() => run(() => startRepair(modelId))}>
<WrenchIcon />
Repair
</Button>
) : (
canDownload && (
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
{downloadLabel}
</Button>
)
)}
{canVerify && (
<>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => run(() => startVerify(modelId, false))}
title="Check that every selected file exists with the right size (seconds)"
>
<ShieldCheckIcon />
Verify
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => run(() => startVerify(modelId, true))}
title="Hash every file and compare with the Hub (slow: reads every byte)"
>
Deep verify
</Button>
</>
)}
</>
)}
{latest && latest.kind !== "delete" && (
<Link href={`/jobs/${latest.id}`} className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted">
View log
</Link>
)}
</div>
</div>
);
}
@@ -0,0 +1,241 @@
"use client";
import { PlusIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
type Candidate = { path: string; size: number };
/**
* Files tab header: selection summary + on-disk progress, and a "Download more" panel to add
* files that aren't selected yet.
*/
export function FilesHeader({
modelId,
sha,
selectedCount,
totalBytes,
localCount,
localBytes,
candidates,
selectedPaths,
freeBytes,
busy,
hubMissing,
}: {
modelId: string;
sha: string;
selectedCount: number;
totalBytes: number;
localCount: number;
localBytes: number;
candidates: Candidate[];
/** Files the model already has selected (no second mmproj/MTP is recommended). */
selectedPaths: string[];
freeBytes: number | null;
/** A download is queued/running; adding files has to wait. */
busy: boolean;
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
hubMissing: boolean;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [submitting, setSubmitting] = useState(false);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
for (const c of candidates) {
const g = quantGroup(c.path);
if (!g) continue;
const entry = m.get(g) ?? { paths: [], size: 0 };
entry.paths.push(c.path);
entry.size += c.size;
m.set(g, entry);
}
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [candidates]);
// Companions (template, MTP, mmproj, …) of newly picked model files come along.
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(candidates, picked, { have: selectedPaths });
const chosen = useMemo(() => new Set([...picked, ...recActive]), [picked, recActive]);
// Split files are one entry; its checkbox selects all parts.
const entries = useMemo(() => groupSplitFiles(candidates), [candidates]);
const pickedEntries = entries.filter((e) => e.parts.every((p) => chosen.has(p.path))).length;
const pickedBytes = candidates.filter((c) => chosen.has(c.path)).reduce((s, c) => s + c.size, 0);
const tooBig = freeBytes != null && pickedBytes > freeBytes;
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setPicked((prev) => {
const next = new Set(prev);
for (const p of paths) {
if (on) next.add(p);
else next.delete(p);
}
return next;
});
}
async function submit() {
setSubmitting(true);
try {
const res = await fetch(`/api/models/${modelId}/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ add: [...chosen] }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not add files (${res.status})`);
return;
}
toast.success(`${body.added} file${body.added === 1 ? "" : "s"} added, download queued`);
setOpen(false);
setPicked(new Set());
resetRecommended();
router.refresh();
} finally {
setSubmitting(false);
}
}
return (
<div className="border-b">
<div className="flex flex-col gap-2 px-5 py-4">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-sm">
<span>
<span className="font-medium">
{selectedCount} selected file{selectedCount === 1 ? "" : "s"}
</span>
<span className="text-muted-foreground">
{" "}
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
</span>
</span>
<div className="flex items-center gap-3">
<span className="text-muted-foreground">
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
</span>
{candidates.length > 0 && !hubMissing && (
<Button
size="sm"
variant={open ? "outline" : "default"}
onClick={() => setOpen((o) => !o)}
disabled={busy && !open}
title={busy ? "Wait until the current download has finished" : undefined}
>
{open ? (
"Close"
) : (
<>
<PlusIcon /> Download more
</>
)}
</Button>
)}
</div>
</div>
<Progress value={percent(localBytes, totalBytes)} />
</div>
{open && (
<div className="border-t bg-muted/30">
{groups.length > 0 && (
<div className="flex flex-col gap-1.5 px-5 pt-4">
<span className="text-xs text-muted-foreground">Quick select</span>
<div className="flex flex-wrap gap-1.5">
{groups.map(([name, g]) => {
const on = g.paths.every((p) => picked.has(p));
return (
<Button
key={name}
type="button"
size="xs"
variant={on ? "default" : "outline"}
onClick={() => toggle(g.paths, !on)}
title={g.paths.join("\n")}
>
{name}
<span className="opacity-70">{formatBytes(g.size)}</span>
</Button>
);
})}
</div>
</div>
)}
<RecommendedStrip files={candidates} paths={recAll} active={recActive} onToggle={toggle} className="mx-5 mt-3" />
<ul className="mt-3 max-h-96 divide-y overflow-y-auto border-y bg-card">
{entries.map((e) => {
const paths = e.parts.map((p) => p.path);
const on = paths.every((p) => chosen.has(p));
const isRecommended = paths.every((p) => recAll.includes(p));
return (
<li key={e.path}>
<label className="grid cursor-pointer grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2 hover:bg-muted/50">
<Checkbox checked={on} onCheckedChange={(v) => toggle(paths, v === true)} />
<FileRoleBadge path={e.path} />
<span className="flex min-w-0 items-center gap-2" title={paths.join("\n")}>
<span className="truncate font-mono text-[13px]">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
</span>
<span className="text-right text-sm text-muted-foreground tabular-nums">{formatBytes(e.size)}</span>
</label>
</li>
);
})}
</ul>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-3 text-sm">
<span>
<span className="font-medium">
{pickedEntries} file{pickedEntries === 1 ? "" : "s"} · {formatBytes(pickedBytes)}
</span>
{freeBytes != null && (
<span className={tooBig ? "text-destructive" : "text-muted-foreground"}>
{" "}
({formatBytes(freeBytes)} free)
</span>
)}
</span>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" onClick={() => {
setPicked(new Set());
resetRecommended();
}}
disabled={chosen.size === 0}
>
Clear
</Button>
<Button size="sm" onClick={submit} disabled={chosen.size === 0 || submitting || busy}>
{submitting ? "Adding…" : pickedEntries === 0 ? "Download" : `Download ${pickedEntries} file${pickedEntries === 1 ? "" : "s"}`}
</Button>
</div>
</div>
</div>
)}
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
import {
AlertTriangleIcon,
BoxIcon,
CheckCircle2Icon,
ChevronRightIcon,
CircleDashedIcon,
FileIcon,
FileImageIcon,
FileJsonIcon,
FileTextIcon,
ShieldCheckIcon,
XCircleIcon,
} from "lucide-react";
import { FileRoleBadge } from "@/components/labels";
import type { ModelFileState } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { type FileGroup, groupSplitFiles } from "@/lib/file-groups";
import { cn } from "@/lib/utils";
import { FilesHeader } from "./download-more";
type FileRow = { id: string; path: string; size: number; lfsSha256: string | null; state: ModelFileState };
const STATE: Record<ModelFileState, { label: string; icon: React.ReactNode; className: string }> = {
pending: { label: "Not downloaded", icon: <CircleDashedIcon className="size-3.5" />, className: "text-muted-foreground" },
present: { label: "Downloaded", icon: <CheckCircle2Icon className="size-3.5" />, className: "text-emerald-600 dark:text-emerald-400" },
verified: { label: "Verified", icon: <ShieldCheckIcon className="size-3.5" />, className: "text-emerald-600 dark:text-emerald-400" },
missing: { label: "Missing", icon: <XCircleIcon className="size-3.5" />, className: "text-destructive" },
size_mismatch: { label: "Size mismatch", icon: <AlertTriangleIcon className="size-3.5" />, className: "text-amber-600 dark:text-amber-400" },
hash_mismatch: { label: "Hash mismatch", icon: <AlertTriangleIcon className="size-3.5" />, className: "text-amber-600 dark:text-amber-400" },
};
function FileTypeIcon({ path }: { path: string }) {
const ext = path.toLowerCase().split(".").pop() ?? "";
const cls = "size-4 text-muted-foreground";
if (["gguf", "safetensors", "bin", "pt", "onnx"].includes(ext)) return <BoxIcon className={cls} />;
if (ext === "json") return <FileJsonIcon className={cls} />;
if (["md", "txt"].includes(ext)) return <FileTextIcon className={cls} />;
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext)) return <FileImageIcon className={cls} />;
return <FileIcon className={cls} />;
}
function FileName({ path }: { path: string }) {
const slash = path.lastIndexOf("/");
return (
<span className="min-w-0 truncate font-mono text-[13px]" title={path}>
{slash >= 0 && <span className="text-muted-foreground">{path.slice(0, slash + 1)}</span>}
{path.slice(slash + 1)}
</span>
);
}
type Entry = FileGroup<FileRow>;
/** One status for a whole entry (all parts of a split file). */
function entryState(e: Entry): { state: ModelFileState; label: string } {
const states = e.parts.map((p) => p.state);
const done = states.filter((st) => st === "present" || st === "verified").length;
const worst = (["missing", "hash_mismatch", "size_mismatch"] as const).find((st) => states.includes(st));
if (worst) return { state: worst, label: STATE[worst].label };
if (done === states.length) {
const state = states.every((st) => st === "verified") ? "verified" : "present";
return { state, label: STATE[state].label };
}
if (done > 0) return { state: "pending", label: `${done} of ${states.length} parts` };
return { state: "pending", label: STATE.pending.label };
}
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
function Row({ entry, href, muted, showState }: { entry: Entry; href: string; muted?: boolean; showState: boolean }) {
const { state: stateKey, label } = entryState(entry);
const state = STATE[stateKey];
const split = entry.totalParts > 1;
return (
<li>
<a
href={href}
target="_blank"
rel="noreferrer"
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
className={cn(
// Fixed status column so sizes line up between selected and unselected rows.
"grid grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2.5 transition-colors hover:bg-muted/50 sm:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_1rem] md:grid-cols-[1rem_auto_minmax(0,1fr)_5rem_7.5rem]",
muted && "text-muted-foreground",
)}
>
<FileTypeIcon path={entry.path} />
<FileRoleBadge path={entry.path} className={muted ? "opacity-70" : undefined} />
<span className="flex min-w-0 items-center gap-2">
<FileName path={entry.path} />
{split && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{entry.parts.length === entry.totalParts
? `${entry.totalParts} parts`
: `${entry.parts.length} of ${entry.totalParts} parts`}
</span>
)}
{entry.parts[0].lfsSha256 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">LFS</span>
)}
</span>
<span className="hidden text-right text-sm tabular-nums sm:block">{formatBytes(entry.size)}</span>
{showState ? (
<span className={cn("flex items-center justify-end gap-1.5 text-xs whitespace-nowrap", state.className)}>
{state.icon}
<span className="hidden md:inline">{label}</span>
</span>
) : (
<span className="text-right text-sm tabular-nums sm:hidden">{formatBytes(entry.size)}</span>
)}
</a>
</li>
);
}
/** "Files and versions"-style list: selected files with their local state, the rest collapsed. */
export function FilesTab({
modelId,
repoId,
sha,
selected,
others,
freeBytes,
busy,
hubMissing,
}: {
modelId: string;
repoId: string;
sha: string;
selected: FileRow[];
others: FileRow[];
freeBytes: number | null;
busy: boolean;
hubMissing: 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) => {
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}`;
};
const selectedEntries = groupSplitFiles(selected);
const otherEntries = groupSplitFiles(others);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const localEntries = selectedEntries.filter(isLocal);
const localBytes = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
return (
<div>
<FilesHeader
modelId={modelId}
sha={sha}
selectedCount={selectedEntries.length}
totalBytes={totalBytes}
localCount={localEntries.length}
localBytes={localBytes}
candidates={others.map((f) => ({ path: f.path, size: f.size }))}
selectedPaths={selected.map((f) => f.path)}
freeBytes={freeBytes}
busy={busy}
hubMissing={hubMissing}
/>
<ul className="divide-y">
{selectedEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} showState />
))}
</ul>
{otherEntries.length > 0 && (
<details className="group border-t">
<summary className="flex cursor-pointer list-none items-center gap-2 px-5 py-3 text-sm hover:bg-muted/50">
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-open:rotate-90" />
<span className="font-medium">Not selected</span>
<span className="text-muted-foreground">
{otherEntries.length} file{otherEntries.length === 1 ? "" : "s"} ·{" "}
{formatBytes(others.reduce((s, f) => s + f.size, 0))}
</span>
</summary>
<ul className="divide-y border-t">
{otherEntries.map((e) => (
<Row key={e.path} entry={e} href={href(e)} muted showState={false} />
))}
</ul>
</details>
)}
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { RefreshCwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/** Check the Hub right now: repo and pinned commit still there, newer commit on the tracked revision. */
export function HubCheckButton({ modelId, label = "Check now" }: { modelId: string; label?: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function check() {
setBusy(true);
try {
const res = await fetch(`/api/models/${modelId}/hub-check`, { method: "POST" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Check failed (${res.status})`);
else if (json.state === "available" && json.update) toast.info("Update available");
else if (json.state === "available") toast.success(json.warning ?? "Up to date");
else if (json.state === "repo_missing") toast.warning("The repo is no longer on Hugging Face");
else if (json.state === "commit_missing") toast.warning("The pinned commit is no longer on Hugging Face");
else toast.error(`Could not check: ${json.error ?? "unknown error"}`);
router.refresh();
} finally {
setBusy(false);
}
}
return (
<Button variant="ghost" size="xs" onClick={check} disabled={busy}>
<RefreshCwIcon className={cn(busy && "animate-spin")} />
{label}
</Button>
);
}
+53
View File
@@ -0,0 +1,53 @@
"use client";
import Link from "next/link";
import { JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import { formatBytes } from "@/lib/format";
import { jobLabel } from "@/lib/job-labels";
/** Job history of one model (live). */
export function JobsTab({ modelId }: { modelId: string }) {
const { snapshot } = useLive({ model: modelId });
const jobs = snapshot?.jobs ?? [];
if (snapshot && jobs.length === 0) {
return <p className="py-6 text-sm text-muted-foreground">No jobs yet.</p>;
}
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Started</TableHead>
<TableHead>Kind</TableHead>
<TableHead>State</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden sm:table-cell">Finished</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<Link href={`/jobs/${j.id}`} className="hover:underline">
<LocalTime value={j.startedAt ?? j.createdAt} />
</Link>
</TableCell>
<TableCell className="text-sm">
{jobLabel(j)}
</TableCell>
<TableCell>
<JobStateBadge job={j} />
</TableCell>
<TableCell className="text-right text-sm tabular-nums">{formatBytes(j.totalBytes)}</TableCell>
<TableCell className="hidden text-sm text-muted-foreground sm:table-cell">
<LocalTime value={j.finishedAt} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
+49
View File
@@ -0,0 +1,49 @@
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkGfm from "remark-gfm";
// 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.
const schema = {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
img: [...(defaultSchema.attributes?.img ?? []), "width", "height", "align", "loading"],
div: [...(defaultSchema.attributes?.div ?? []), "align"],
p: [...(defaultSchema.attributes?.p ?? []), "align"],
td: [...(defaultSchema.attributes?.td ?? []), "align"],
th: [...(defaultSchema.attributes?.th ?? []), "align"],
},
};
/** 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}`;
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
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw, [rehypeSanitize, schema]]}
urlTransform={(url, key) => {
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.
const path = safe.replace(/^\.?\//, "");
return key === "src" ? `${base}/resolve/${sha}/${path}` : `${base}/blob/${sha}/${path}`;
}}
components={{
a: ({ href, children, ...props }) => (
<a href={href} {...props} target={href?.startsWith("#") ? undefined : "_blank"} rel="noreferrer">
{children}
</a>
),
// eslint-disable-next-line @next/next/no-img-element
img: ({ alt, ...props }) => <img alt={alt ?? ""} loading="lazy" referrerPolicy="no-referrer" {...props} />,
}}
>
{markdown}
</ReactMarkdown>
</article>
);
}
+526
View File
@@ -0,0 +1,526 @@
import {
ArrowDownIcon,
BoxIcon,
CpuIcon,
ExternalLinkIcon,
FileTextIcon,
FolderIcon,
HistoryIcon,
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
PlusIcon,
RocketIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
} from "lucide-react";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
import { getModelByRepo, relatedModels } from "@/lib/library";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
import { modelTagList } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
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 { DeleteModelButton } from "./delete-model-button";
import { TagEditor } from "./tag-editor";
import { UpdateBanner } from "./update-banner";
export const dynamic = "force-dynamic";
const TABS = [
{ id: "files", label: "Files", icon: FolderIcon },
{ id: "card", label: "Model card", icon: FileTextIcon },
{ id: "jobs", label: "Jobs", icon: HistoryIcon },
] as const;
type TabId = (typeof TABS)[number]["id"];
const FORMATS: Record<string, string> = {
gguf: "GGUF",
safetensors: "Safetensors",
transformers: "Transformers",
pytorch: "PyTorch",
onnx: "ONNX",
mlx: "MLX",
};
const RELATION_LABEL: Record<string, string> = {
quantized: "Quantized",
finetune: "Finetuned",
adapter: "Adapter",
merge: "Merged",
};
const titleCase = (s: string) => s.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
function languageName(code: string): string | null {
if (!/^[a-z]{2,3}$/.test(code)) return null;
try {
const name = new Intl.DisplayNames(["en"], { type: "language" }).of(code);
return name && name !== code ? name : null;
} catch {
return null;
}
}
export async function generateMetadata({ params }: PageProps<"/[org]/[repo]">): Promise<Metadata> {
const { org, repo } = await params;
return { title: `${org}/${repo}` };
}
export default async function ModelPage({ params, searchParams }: PageProps<"/[org]/[repo]">) {
const { org, repo } = await params;
const sp = await searchParams;
const data = await getModelByRepo(`${org}/${repo}`);
if (!data) notFound();
const { model, files } = data;
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
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}`;
const baseModels = model.baseModels ?? [];
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
deploymentsByModel(),
listDeployableModels(),
]);
const modelDeployments = byModel.get(model.id) ?? [];
const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
: null;
const selected = files.filter((f) => f.selected);
const others = files.filter((f) => !f.selected);
const selectedBytes = selected.reduce((s, f) => s + f.size, 0);
const quants = [
...new Set(selected.filter((f) => fileRole(f.path) === "model").map((f) => quantGroup(f.path)).filter(Boolean)),
] as string[];
const formats = hubTags.filter((t) => FORMATS[t]).map((t) => FORMATS[t]);
const languages = hubTags.map(languageName).filter(Boolean) as string[];
const shown = new Set([...Object.keys(FORMATS), model.architecture, author.toLowerCase(), model.pipelineTag]);
const extraTags = hubTags.filter((t) => !shown.has(t) && !languageName(t)).slice(0, 8);
const tabHref = (id: TabId) => (id === "files" ? `/${model.repoId}` : `/${model.repoId}?tab=${id}`);
return (
<div className="flex flex-col gap-4">
{/* Header card, styled after the Hugging Face model page */}
<Panel className="flex flex-col gap-4 p-5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
<Avatar url={model.authorAvatarUrl} name={author} />
<Link href={`/?author=${encodeURIComponent(author)}`} className="text-muted-foreground hover:text-foreground hover:underline">
{author}
</Link>
<span className="text-muted-foreground">/</span>
<h1 className="text-xl font-semibold break-all">{name}</h1>
<CopyButton value={model.repoId} label="Copy repo ID" />
<ModelStatusBadge status={model.status} />
<HubStateBadge state={model.hubState} />
{update && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
update available
</span>
)}
<div className="ml-auto flex items-center gap-2">
{canDeploy && (
<Link
href={`/deployments/new?model=${model.id}`}
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
>
<RocketIcon />
Deploy
</Link>
)}
<DeleteModelButton
id={model.id}
repoId={model.repoId}
localPath={model.localPath}
mayHaveFiles={model.status !== "pending" || recentJobs.length > 0}
/>
<ExternalButton href={hub}>🤗 Hugging Face</ExternalButton>
</div>
</div>
<div className="flex flex-wrap items-center gap-1.5">
{model.pipelineTag && (
<Pill icon={MessagesSquareIcon} accent>
{titleCase(model.pipelineTag)}
</Pill>
)}
{formats.map((f) => (
<Pill key={f} icon={BoxIcon}>
{f}
</Pill>
))}
{model.architecture && <Pill icon={CpuIcon}>{model.architecture}</Pill>}
{languages.length > 0 && <Pill icon={LanguagesIcon}>{languages.join(", ")}</Pill>}
{model.license && <Pill icon={ScaleIcon}>License: {model.license}</Pill>}
{extraTags.map((t) => (
<Pill key={t} muted>
{t}
</Pill>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-muted-foreground">Your tags</span>
<TagEditor modelId={model.id} tags={tags} />
</div>
</Panel>
{hubMissing && (
<div className="flex flex-wrap items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="font-medium text-amber-800 dark:text-amber-200">
{model.hubState === "repo_missing"
? "This repo is no longer on Hugging Face"
: "The pinned commit is no longer on Hugging Face"}
</p>
<p className="text-muted-foreground">
{model.hubState === "repo_missing"
? "It was deleted, renamed or made private. "
: "The repo's history was rewritten. "}
Your local copy is kept and stays usable; downloading more files or repairing isn&apos;t possible.
{model.hubMissingSince && (
<>
{" "}
Missing since <LocalTime value={model.hubMissingSince} />.
</>
)}
</p>
</div>
<HubCheckButton modelId={model.id} label="Check again" />
</div>
)}
{update && (
<UpdateBanner modelId={model.id} revision={model.trackedRevision} pinnedSha={model.pinnedSha} diff={update} hubUrl={hub} />
)}
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
{/* Content card with the tabs as a segmented control in its header */}
<Panel className="min-w-0 overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-3">
<nav className="inline-flex rounded-lg bg-muted p-1">
{TABS.map((t) => (
<Link
key={t.id}
href={tabHref(t.id)}
scroll={false}
className={cn(
"flex items-center gap-1.5 rounded-md px-3 py-1 text-sm transition-colors",
tab === t.id
? "bg-background font-medium text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}
>
<t.icon className="size-4" />
{t.label}
{t.id === "files" && <span className="text-xs text-muted-foreground tabular-nums">{selected.length}</span>}
</Link>
))}
</nav>
</div>
{tab === "card" && (
<div className="p-5 sm:p-6">
{card ? (
<>
<ModelCard markdown={card} repoId={model.repoId} sha={model.pinnedSha} />
<div className="mt-6 flex justify-end">
<a
href={`${hub}/blob/${model.pinnedSha}/README.md`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
README.md @ {shortSha(model.pinnedSha)}
<ExternalLinkIcon className="size-3" />
</a>
</div>
</>
) : (
<p className="text-sm text-muted-foreground">
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
<a href={hub} target="_blank" rel="noreferrer" className="underline">
Open on Hugging Face
</a>
</p>
)}
</div>
)}
{tab === "files" && (
<FilesTab
modelId={model.id}
repoId={model.repoId}
sha={model.pinnedSha}
selected={selected}
others={others}
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
busy={model.status === "downloading"}
hubMissing={hubMissing}
/>
)}
{tab === "jobs" && (
<div className="px-2 pb-2">
<JobsTab modelId={model.id} />
</div>
)}
</Panel>
<aside className="flex flex-col gap-4">
<SideCard>
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
</SideCard>
{(modelDeployments.length > 0 || canDeploy) && (
<SideCard title="Deployments" icon={RocketIcon}>
<div className="flex flex-col gap-2">
{modelDeployments.length === 0 ? (
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
) : (
modelDeployments.map((d) => (
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{d.name}</span>
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
</span>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</Link>
))
)}
{canDeploy && (
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
<PlusIcon className="size-3.5" />
New deployment
</Link>
)}
</div>
</SideCard>
)}
<SideCard title="Local copy" icon={ListChecksIcon}>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Selection</dt>
<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>
<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}>
{shortSha(model.pinnedSha)}
</a>
<span className="text-muted-foreground">on {model.trackedRevision}</span>
<CopyButton value={model.pinnedSha} label="Copy commit SHA" />
</dd>
<dt className="text-muted-foreground">Downloaded</dt>
<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}`}>
{model.localPath}
</span>
<CopyButton value={model.localPath} label="Copy path" />
</dd>
{model.includePatterns.length > 0 && (
<>
<dt className="text-muted-foreground">Include</dt>
<dd className="flex flex-col font-mono text-xs">{model.includePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
</>
)}
{model.excludePatterns.length > 0 && (
<>
<dt className="text-muted-foreground">Exclude</dt>
<dd className="flex flex-col font-mono text-xs">{model.excludePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
</>
)}
<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")}>
{model.hubState === "available"
? update
? "Update available"
: "Up to date"
: model.hubState === "repo_missing"
? "Repo deleted"
: model.hubState === "commit_missing"
? "Commit deleted"
: "Not checked yet"}
</span>
{model.lastCheckedAt && (
<span className="text-xs text-muted-foreground" title={model.lastCheckError ?? undefined}>
checked <LocalTime value={model.lastCheckedAt} />
</span>
)}
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
<HubCheckButton modelId={model.id} />
</dd>
<dt className="text-muted-foreground">Added</dt>
<dd>
<LocalTime value={model.createdAt} />
</dd>
</dl>
</SideCard>
<SideCard title="Model tree" icon={SparklesIcon}>
<ModelTree
repoId={model.repoId}
baseModels={baseModels}
relation={model.baseRelation}
families={modelFamilies(model.repoId, baseModels)}
/>
{related.length > 0 && (
<div className="mt-4 flex flex-col gap-1.5 border-t pt-3">
<span className="text-xs text-muted-foreground">Also in your library</span>
{related.map((r) => (
<Link key={r.repoId} href={`/${r.repoId}`} className="flex items-center justify-between gap-2 text-sm hover:underline">
<span className="truncate">{r.repoId}</span>
<span className="shrink-0 text-xs text-muted-foreground">{r.quants.join(", ")}</span>
</Link>
))}
</div>
)}
</SideCard>
</aside>
</div>
</div>
);
}
function Avatar({ url, name }: { url: string | null; name: string }) {
if (url) {
// eslint-disable-next-line @next/next/no-img-element
return <img src={url} alt="" className="size-6 rounded-md object-cover" referrerPolicy="no-referrer" />;
}
return (
<span className="grid size-6 place-items-center rounded-md bg-muted text-xs font-semibold uppercase">
{name.slice(0, 1)}
</span>
);
}
function Pill({
icon: Icon,
accent,
muted,
children,
}: {
icon?: React.ComponentType<{ className?: string }>;
accent?: boolean;
muted?: boolean;
children: React.ReactNode;
}) {
return (
<span
className={cn(
"inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs",
accent && "border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300",
muted && "text-muted-foreground",
)}
>
{Icon && <Icon className="size-3.5" />}
{children}
</span>
);
}
function ExternalButton({ href, children }: { href: string; children: React.ReactNode }) {
return (
<a href={href} target="_blank" rel="noreferrer" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}>
{children}
<ExternalLinkIcon className="opacity-60" />
</a>
);
}
/** Card surface shared by header, content and sidebar. */
function Panel({ className, children }: { className?: string; children: React.ReactNode }) {
return <div className={cn("rounded-xl bg-card text-card-foreground ring-1 ring-foreground/10", className)}>{children}</div>;
}
function SideCard({
title,
icon: Icon,
children,
}: {
title?: string;
icon?: React.ComponentType<{ className?: string }>;
children: React.ReactNode;
}) {
return (
<Panel className="p-4">
{title && (
<h3 className="mb-3 flex items-center gap-1.5 text-sm font-semibold">
{Icon && <Icon className="size-4 text-muted-foreground" />}
{title}
</h3>
)}
{children}
</Panel>
);
}
function ModelTree({
repoId,
baseModels,
relation,
families,
}: {
repoId: string;
baseModels: string[];
relation: string | null;
families: string[];
}) {
if (baseModels.length === 0) {
return <p className="text-sm text-muted-foreground">Original model, family {families.join(", ")}.</p>;
}
return (
<ol className="flex flex-col items-start gap-1 text-sm">
{baseModels.map((b) => (
<li key={b}>
<a href={`https://huggingface.co/${b}`} target="_blank" rel="noreferrer" className="hover:underline">
{b}
</a>
</li>
))}
<li className="flex items-center gap-1 pl-2 text-xs text-muted-foreground">
<ArrowDownIcon className="size-3.5" />
{relation ? (RELATION_LABEL[relation] ?? titleCase(relation)) : "Derived"}
</li>
<li className="font-medium">{repoId}</li>
</ol>
);
}
+50
View File
@@ -0,0 +1,50 @@
"use client";
import { XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { TagBadge } from "@/components/tag-badge";
import { TagPicker } from "@/components/tag-picker";
import type { Tag } from "@/lib/tags";
/** Add/remove user tags on a model. */
export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function add(name: string) {
setBusy(true);
const res = await fetch(`/api/models/${modelId}/tags`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
setBusy(false);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Could not add tag (${res.status})`);
return;
}
router.refresh();
}
async function remove(tag: Tag) {
const res = await fetch(`/api/models/${modelId}/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not remove tag (${res.status})`);
router.refresh();
}
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.id} name={t.name} color={t.color}>
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)} className="opacity-60 hover:opacity-100">
<XIcon className="size-3" />
</button>
</TagBadge>
))}
<TagPicker exclude={tags.map((t) => t.name)} onPick={add} disabled={busy} />
</div>
);
}
@@ -0,0 +1,121 @@
"use client";
import { ArrowUpCircleIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { startUpdate } from "@/components/job-actions";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
function FileGroup({ title, files, tone }: { title: string; files: UpdateDiffFile[]; tone: string }) {
if (files.length === 0) return null;
return (
<div className="flex flex-col gap-0.5">
<span className={`text-xs font-medium ${tone}`}>
{title} ({files.length})
</span>
<ul className="flex flex-col gap-0.5 text-xs">
{files.slice(0, 20).map((f) => (
<li key={f.path} className="flex justify-between gap-3">
<span className="font-mono break-all">{f.path}</span>
<span className="shrink-0 text-muted-foreground tabular-nums">
{f.oldSize != null && f.oldSize !== f.size ? `${formatBytes(f.oldSize)} → ` : ""}
{formatBytes(f.size)}
</span>
</li>
))}
{files.length > 20 && <li className="text-muted-foreground">… {files.length - 20} more</li>}
</ul>
</div>
);
}
/** "Update available": what would change in the selection, and the deliberate Update action. */
export function UpdateBanner({
modelId,
revision,
pinnedSha,
diff,
hubUrl,
}: {
modelId: string;
revision: string;
pinnedSha: string;
diff: UpdateDiff;
hubUrl: string;
}) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const changes = diff.changed.length + diff.added.length + diff.removed.length;
const download = [...diff.changed, ...diff.added].reduce((s, f) => s + f.size, 0);
async function update() {
setBusy(true);
try {
if (await startUpdate(modelId)) router.refresh();
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-col gap-3 rounded-xl border border-sky-500/30 bg-sky-500/10 px-4 py-3 text-sm">
<div className="flex flex-wrap items-start gap-3">
<ArrowUpCircleIcon className="mt-0.5 size-4 shrink-0 text-sky-600 dark:text-sky-400" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="font-medium text-sky-900 dark:text-sky-100">
Update available: {revision} is at{" "}
<a href={`${hubUrl}/commit/${diff.sha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline">
{shortSha(diff.sha)}
</a>
</p>
<p className="text-muted-foreground">
You have <span className="font-mono">{shortSha(pinnedSha)}</span>.{" "}
{changes === 0
? "None of your selected files changed; updating only moves the pin."
: `${changes} of your selected files would change (${formatBytes(download)} to download).`}{" "}
Checked <LocalTime value={diff.checkedAt} />.
</p>
</div>
<AlertDialog>
<AlertDialogTrigger render={<Button size="sm" disabled={busy} />}>Update</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Update to {shortSha(diff.sha)}?</AlertDialogTitle>
<AlertDialogDescription>
The model is pinned to the new commit (the old one stays in the history) and changed or new files are
downloaded. Files that are no longer part of your selection are deleted after the download succeeded.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={update} disabled={busy}>
Update
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
{changes > 0 && (
<div className="grid gap-3 rounded-lg bg-background/60 px-3 py-2.5 md:grid-cols-3">
<FileGroup title="Changed" files={diff.changed} tone="text-amber-700 dark:text-amber-300" />
<FileGroup title="Added" files={diff.added} tone="text-emerald-700 dark:text-emerald-300" />
<FileGroup title="Removed" files={diff.removed} tone="text-destructive" />
</div>
)}
</div>
);
}
+197 -76
View File
@@ -1,8 +1,13 @@
"use client";
import { XIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { TagBadge } from "@/components/tag-badge";
import { TagPicker } from "@/components/tag-picker";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@@ -10,6 +15,8 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, shortSha } from "@/lib/format";
import type { LookupResult } from "@/lib/hub/lookup";
import { escapeGlob, matchesAny, parsePatternList, quantGroup } from "@/lib/selection";
@@ -27,15 +34,21 @@ async function postJson<T>(url: string, body: unknown): Promise<T> {
return json;
}
/** A folder from the models folder to import (found by the worker's scan). */
export type ImportFolder = { path: string; commit: string | null; files: { path: string; size: number }[]; fileCount: number };
export function AddModelForm({
freeBytes,
onAdded,
importFolder,
}: {
freeBytes: number | null;
onAdded: (modelId: string) => void;
/** Import mode: look up this folder's repo and preselect the files that are already there. */
importFolder?: ImportFolder;
}) {
const [repo, setRepo] = useState("");
const [revision, setRevision] = useState("main");
const [repo, setRepo] = useState(importFolder?.path ?? "");
const [revision, setRevision] = useState(importFolder?.commit ?? "main");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<LookupResult | null>(null);
@@ -44,28 +57,41 @@ export function AddModelForm({
const [includeText, setIncludeText] = useState("");
const [excludeText, setExcludeText] = useState("");
const [submitting, setSubmitting] = useState(false);
const [tagsText, setTagsText] = useState("");
const [knownTags, setKnownTags] = useState<string[]>([]);
const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]);
useEffect(() => {
fetch("/api/tags")
.then((r) => (r.ok ? r.json() : []))
.then((all: { name: string }[]) => setKnownTags(all.map((t) => t.name)))
.catch(() => {});
}, []);
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
async function lookup(e: React.FormEvent) {
e.preventDefault();
const repoFiles = useMemo(() => result?.files ?? [], [result]);
const isExcluded = useCallback((path: string) => matchesAny(path, excludePatterns), [excludePatterns]);
// Picked by checkbox or include pattern; recommended companions come on top.
const picked = useMemo(
() => repoFiles.filter((f) => (checked.has(f.path) || matchesAny(f.path, includePatterns)) && !isExcluded(f.path)).map((f) => f.path),
[repoFiles, checked, includePatterns, isExcluded],
);
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(
repoFiles,
picked,
{ isExcluded },
);
// Local files of the imported folder by path.
const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]);
async function lookup(e?: React.FormEvent) {
e?.preventDefault();
setLoading(true);
setError(null);
try {
const r = await postJson<LookupResult>("/api/hub/lookup", { repo, revision });
setResult(r);
setRevision(r.revision);
setChecked(new Set());
// Import: preselect every repo file that's already in the folder.
setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path)));
resetRecommended();
setIncludeText("");
setExcludeText("");
setTagsText("");
setTags([]);
} catch (err) {
setResult(null);
setError(err instanceof Error ? err.message : String(err));
@@ -74,23 +100,31 @@ export function AddModelForm({
}
}
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const autoLookup = useRef(false);
useEffect(() => {
if (importFolder && !autoLookup.current) {
autoLookup.current = true;
void lookup();
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported
}, [importFolder]);
const files = useMemo(() => {
if (!result) return [];
return result.files.map((f) => {
const pickedSet = new Set(picked);
return repoFiles.map((f) => {
const byPattern = matchesAny(f.path, includePatterns);
const excluded = matchesAny(f.path, excludePatterns);
const excluded = isExcluded(f.path);
return {
...f,
group: quantGroup(f.path),
byPattern,
excluded,
selected: (checked.has(f.path) || byPattern) && !excluded,
recommended: recAll.includes(f.path),
selected: pickedSet.has(f.path) || recActive.has(f.path),
};
});
}, [result, checked, includePatterns, excludePatterns]);
}, [repoFiles, picked, includePatterns, isExcluded, recAll, recActive]);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
@@ -105,14 +139,26 @@ export function AddModelForm({
}, [files]);
const selected = files.filter((f) => f.selected);
// Split files are one row; its checkbox covers all parts.
const entries = useMemo(() => groupSplitFiles(files), [files]);
const selectedEntries = entries.filter((e) => e.parts.every((f) => f.selected)).length;
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
// Files already on disk with the right size are verified by hf, not downloaded again.
const present = selected.filter((f) => onDisk.get(f.path) === f.size);
const toDownload = totalBytes - present.reduce((s, f) => s + f.size, 0);
const notEnoughSpace = freeBytes != null && toDownload > freeBytes;
const repoPaths = useMemo(() => new Set(result?.files.map((f) => f.path)), [result]);
const sizeDiffers = selected.filter((f) => onDisk.has(f.path) && onDisk.get(f.path) !== f.size).length;
const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0;
function toggle(path: string, on: boolean) {
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setChecked((prev) => {
const next = new Set(prev);
if (on) next.add(path);
else next.delete(path);
for (const path of paths) {
if (on) next.add(path);
else next.delete(path);
}
return next;
});
}
@@ -137,11 +183,12 @@ export function AddModelForm({
repoId: result.repoId,
revision: result.revision,
sha: result.sha,
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
include: [...includePatterns, ...[...new Set([...checked, ...recActive])].sort().map(escapeGlob)],
exclude: excludePatterns,
tags: parsePatternList(tagsText),
tags: tags.map((t) => t.name),
localPath: importFolder?.path,
});
toast.success(`${result.repoId} added, download queued`);
toast.success(importFolder ? `${result.repoId} imported, verifying files` : `${result.repoId} added, download queued`);
onAdded(id);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
@@ -154,8 +201,12 @@ export function AddModelForm({
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Hugging Face repository</CardTitle>
<CardDescription>Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL.</CardDescription>
<CardTitle>{importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"}</CardTitle>
<CardDescription>
{importFolder
? `The folder's files are matched against this Hub repo${importFolder.commit ? " at the commit hf recorded when it downloaded them" : ""}. Change the repo or revision if they don't fit.`
: "Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL."}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={lookup} className="flex flex-col gap-3 sm:flex-row sm:items-end">
@@ -218,10 +269,27 @@ export function AddModelForm({
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{importFolder && !result.existingModelId && (
<div className="rounded-md bg-muted px-3 py-2 text-sm">
<p>
<span className="font-medium">
{present.length} of {selected.length} selected files are already on disk
</span>{" "}
and are verified by hash (hf only downloads files that are missing or different).
{sizeDiffers > 0 && ` ${sizeDiffers} differ in size and will be downloaded again.`}
</p>
{notInRepo > 0 && (
<p className="mt-1 text-muted-foreground">
{notInRepo} file{notInRepo === 1 ? " in the folder isn't" : "s in the folder aren't"} part of the repo at this
commit; {notInRepo === 1 ? "it stays" : "they stay"} untouched.
</p>
)}
</div>
)}
{result.existingModelId && (
<p className="rounded-md bg-muted px-3 py-2 text-sm">
This repo is already in the library.{" "}
<Link href={`/models/${result.existingModelId}`} className="underline">
<Link href={`/${result.repoId}`} className="underline">
Open it
</Link>
</p>
@@ -251,6 +319,8 @@ export function AddModelForm({
</div>
)}
<RecommendedStrip files={repoFiles} paths={recAll} active={recActive} onToggle={toggle} />
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="include">Include patterns</Label>
@@ -282,20 +352,32 @@ export function AddModelForm({
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="tags">Tags</Label>
<Input
id="tags"
value={tagsText}
onChange={(e) => setTagsText(e.target.value)}
placeholder="roleplay, security"
list="known-tags"
/>
<datalist id="known-tags">
{knownTags.map((t) => (
<option key={t} value={t} />
<Label>Tags</Label>
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<TagBadge key={t.name.toLowerCase()} name={t.name} color={t.color}>
<button
type="button"
aria-label={`Remove tag ${t.name}`}
onClick={() => setTags((prev) => prev.filter((x) => x !== t))}
className="opacity-60 hover:opacity-100"
>
<XIcon className="size-3" />
</button>
</TagBadge>
))}
</datalist>
<p className="text-xs text-muted-foreground">Optional, comma-separated. Editable later on the model page.</p>
<TagPicker
exclude={tags.map((t) => t.name)}
onPick={(name, tag) =>
setTags((prev) =>
prev.some((x) => x.name.toLowerCase() === name.toLowerCase())
? prev
: [...prev, { name, color: tag?.color }],
)
}
/>
</div>
<p className="text-xs text-muted-foreground">Optional. Editable later on the model page.</p>
</div>
</CardContent>
</Card>
@@ -311,44 +393,62 @@ export function AddModelForm({
</TableRow>
</TableHeader>
<TableBody>
{files.map((f) => (
<TableRow key={f.path} data-state={f.selected ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={f.selected}
disabled={f.byPattern || f.excluded}
onCheckedChange={(v) => toggle(f.path, v === true)}
aria-label={`Select ${f.path}`}
title={
f.excluded
? "Excluded by a pattern"
: f.byPattern
? "Selected by an include pattern"
: undefined
}
/>
</TableCell>
<TableCell className="font-mono text-xs break-all whitespace-normal">
{f.path}
{f.excluded && <span className="ml-2 text-muted-foreground">(excluded)</span>}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{f.lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
))}
{entries.map((e) => {
const parts = e.parts;
const all = parts.every((f) => f.selected);
const some = !all && parts.some((f) => f.selected);
const byPattern = parts.every((f) => f.byPattern);
const excluded = parts.every((f) => f.excluded);
const isRecommended = parts.every((f) => f.recommended);
return (
<TableRow key={e.path} data-state={all ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={all}
indeterminate={some}
disabled={byPattern || excluded}
onCheckedChange={(v) => toggle(parts.map((f) => f.path), v === true)}
aria-label={`Select ${e.path}`}
title={excluded ? "Excluded by a pattern" : byPattern ? "Selected by an include pattern" : undefined}
/>
</TableCell>
<TableCell className="whitespace-normal">
<span className="flex items-center gap-2" title={e.totalParts > 1 ? parts.map((f) => f.path).join("\n") : undefined}>
<FileRoleBadge path={e.path} />
<span className="font-mono text-xs break-all">{e.path}</span>
{e.totalParts > 1 && (
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">
{e.totalParts} parts
</span>
)}
{excluded && <span className="text-xs text-muted-foreground">(excluded)</span>}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
{importFolder && <DiskState parts={parts} onDisk={onDisk} />}
</span>
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(e.size)}</TableCell>
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">
{parts[0].lfsSha256 ? "LFS" : "git"}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
<div className="sticky bottom-0 -mx-4 border-t bg-background/95 px-4 py-3 backdrop-blur">
<div className="sticky bottom-3 z-10 rounded-xl bg-card/95 px-4 py-3 text-card-foreground shadow-lg ring-1 ring-foreground/10 backdrop-blur">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
{selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)}
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)}
</span>{" "}
selected
{importFolder && <span className="text-muted-foreground"> · {formatBytes(toDownload)} to download</span>}
{freeBytes != null && (
<span className={notEnoughSpace ? "ml-2 text-destructive" : "ml-2 text-muted-foreground"}>
({formatBytes(freeBytes)} free on the models volume)
@@ -356,7 +456,10 @@ export function AddModelForm({
)}
</div>
<div className="ml-auto flex gap-2">
<Button type="button" variant="ghost" onClick={() => setChecked(new Set())}>
<Button type="button" variant="ghost" onClick={() => {
setChecked(new Set());
resetRecommended();
}}>
Clear
</Button>
<Button
@@ -364,7 +467,7 @@ export function AddModelForm({
onClick={addToLibrary}
disabled={selected.length === 0 || submitting || !!result.existingModelId}
>
{submitting ? "Adding…" : "Add & download"}
{submitting ? "Adding…" : importFolder ? "Import & verify" : "Add & download"}
</Button>
</div>
</div>
@@ -374,3 +477,21 @@ export function AddModelForm({
</div>
);
}
/** Import mode: is this entry already in the folder (and the right size)? */
function DiskState({ parts, onDisk }: { parts: { path: string; size: number }[]; onDisk: Map<string, number> }) {
const here = parts.filter((f) => onDisk.has(f.path));
if (here.length === 0) return null;
const ok = here.every((f) => onDisk.get(f.path) === f.size) && here.length === parts.length;
return (
<span
className={
ok
? "shrink-0 rounded border border-emerald-500/30 bg-emerald-500/10 px-1 text-[10px] leading-4 text-emerald-700 dark:text-emerald-300"
: "shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300"
}
>
{ok ? "on disk" : here.length < parts.length ? `${here.length} of ${parts.length} parts on disk` : "on disk, size differs"}
</span>
);
}
+93 -5
View File
@@ -1,32 +1,120 @@
"use client";
import { FolderInputIcon, RefreshCwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { AddModelForm } from "./add-model-form";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { formatBytes, shortSha } from "@/lib/format";
import { cn } from "@/lib/utils";
import { AddModelForm, type ImportFolder } from "./add-model-form";
/** Library header with an "Add model" toggle that opens the lookup/selection form inline. */
export function AddModelPanel({ freeBytes, defaultOpen }: { freeBytes: number | null; defaultOpen: boolean }) {
type Folder = ImportFolder & { totalBytes: number };
/**
* Library header with an "Add model" toggle that opens the lookup/selection form inline, and the
* folders in the models folder that aren't in the library yet, each with "Import".
*/
export function AddModelPanel({
freeBytes,
defaultOpen,
folders,
}: {
freeBytes: number | null;
defaultOpen: boolean;
folders: Folder[];
}) {
const router = useRouter();
const [open, setOpen] = useState(defaultOpen);
const [importing, setImporting] = useState<Folder | null>(null);
const [scanning, setScanning] = useState(false);
function close() {
setOpen(false);
setImporting(null);
}
async function rescan() {
setScanning(true);
try {
const res = await fetch("/api/local-folders/scan", { method: "POST" });
if (!res.ok) {
toast.error(`Could not start a scan (${res.status})`);
return;
}
// The worker picks the request up with its next heartbeat (every 5 s).
await new Promise((r) => setTimeout(r, 7_000));
router.refresh();
} finally {
setScanning(false);
}
}
return (
<>
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Library</h1>
<Button variant={open ? "outline" : "default"} onClick={() => setOpen((o) => !o)}>
<Button variant={open ? "outline" : "default"} onClick={() => (open ? close() : setOpen(true))}>
{open ? "Close" : "Add model"}
</Button>
</div>
{open && (
<AddModelForm
key={importing?.path ?? "new"}
freeBytes={freeBytes}
importFolder={importing ?? undefined}
onAdded={() => {
setOpen(false);
close();
router.refresh();
}}
/>
)}
{!open && folders.length > 0 && (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FolderInputIcon className="size-4 text-muted-foreground" />
Found in the models folder
</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.
</CardDescription>
<CardAction>
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
<RefreshCwIcon className={cn(scanning && "animate-spin")} />
{scanning ? "Scanning…" : "Rescan"}
</Button>
</CardAction>
</CardHeader>
<CardContent>
<ul className="divide-y rounded-lg ring-1 ring-foreground/10">
{folders.map((f) => (
<li key={f.path} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-2">
<span className="min-w-0 flex-1 truncate font-mono text-sm" title={f.path}>
{f.path}
</span>
<span className="text-xs text-muted-foreground tabular-nums">
{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>
</li>
))}
</ul>
</CardContent>
</Card>
)}
</>
);
}
@@ -0,0 +1,421 @@
"use client";
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
type LogLine = { id: number; ts: number; stream: string; line: string };
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold tabular-nums">{value}</span>
{children}
</div>
);
}
export function DeploymentDetail({ initial }: { initial: Deployment }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
useEffect(() => {
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
if (res?.status === 404) router.push("/deployments");
else if (res?.ok) setD(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [d.id, router]);
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
const hostname = useHostname();
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
const webUi = webUiUrl(d, hostname);
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{d.name}</h1>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
{d.repoId}
</Link>
{file && ` · ${file}`}
{d.options.mmproj && " · vision"}
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
</p>
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
</div>
<div className="flex flex-wrap items-center gap-2">
{webUi && (
<a
href={webUi}
target="_blank"
rel="noreferrer"
className={cn(buttonVariants({ variant: "outline" }), d.state !== "running" && "pointer-events-none opacity-50")}
aria-disabled={d.state !== "running"}
>
<ExternalLinkIcon />
Web UI
</a>
)}
{active ? (
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
<SquareIcon />
Stop
</Button>
) : (
<Button onClick={() => startDeployment(d.id)}>
<PlayIcon />
Start
</Button>
)}
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
aria-disabled={active}
title={active ? "Stop it first" : undefined}
>
<PencilIcon />
Edit
</Link>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteDeployment(d.id)) router.push("/deployments");
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{d.state === "failed" && d.error && (
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
<div className="flex min-w-0 flex-col gap-4">
<Card>
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat
label="CPU"
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
>
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
</Stat>
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
{d.stats && d.state === "running" && d.memoryMb ? (
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
) : (
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
)}
</Stat>
<Stat
label={d.state === "starting" ? "Loading" : "Load time"}
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
>
<span className="text-xs text-muted-foreground">until /health answered</span>
</Stat>
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
<span className="text-xs text-muted-foreground">
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
</span>
</Stat>
</CardContent>
</Card>
<Logs id={d.id} />
</div>
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-xs">
{internal ? (
<div className="flex items-center justify-between gap-2">
<code className="font-mono break-all">{internal}</code>
<CopyButton value={internal} label="Copy URL" />
</div>
) : (
<span className="text-muted-foreground">Not started yet.</span>
)}
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
{published && (
<div className="flex items-center justify-between gap-2 border-t pt-2">
<code className="font-mono break-all">{published}</code>
<CopyButton value={published} label="Copy URL" />
</div>
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
{d.options.requireApiKey && (
<>
{" "}
Requires one of the{" "}
<Link href="/settings/api-keys" className="underline">
API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.
</>
)}
</span>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Container</dt>
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={d.startedAt} />
</dd>
<dt className="text-muted-foreground">Stopped</dt>
<dd>
<LocalTime value={d.stoppedAt} />
</dd>
{d.command && (
<>
<dt className="text-muted-foreground">Arguments</dt>
<dd className="flex items-start gap-1">
<code className="font-mono break-all">{d.command.join(" ")}</code>
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
</dd>
</>
)}
</dl>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
/** Live container log (polls new lines every 1.5 s). */
function Logs({ id }: { id: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`/api/deployments/${id}/logs?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [id]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className="min-w-0">
<CardHeader>
<CardTitle>Log</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
const [answer, setAnswer] = useState("");
const [busy, setBusy] = useState(false);
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
const [error, setError] = useState<string | null>(null);
async function send() {
setBusy(true);
setAnswer("");
setError(null);
setStats(null);
const t0 = performance.now();
let first: number | null = null;
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
let chunks = 0;
try {
const res = await fetch(`/api/deployments/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
});
if (!res.ok || !res.body) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const j = JSON.parse(data);
if (j.usage) usage = j.usage;
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
if (delta) {
first ??= performance.now();
chunks++;
setAnswer((a) => a + delta);
}
}
}
const total = (performance.now() - t0) / 1000;
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle>Try it</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
disabled={!running}
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
/>
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
<SendIcon />
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
</Button>
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
{stats && (
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div>
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
<div className="text-muted-foreground">first token</div>
</div>
<div>
<div className="font-semibold tabular-nums">
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
</div>
<div className="text-muted-foreground">generation</div>
</div>
<div>
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,26 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentForm } from "../../deployment-form";
import { formData } from "../../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Edit deployment" };
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
const { id } = await params;
const [d, data] = await Promise.all([getDeployment(id), formData()]);
if (!d) notFound();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
{d.state !== "stopped" && d.state !== "failed" && (
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
)}
<DeploymentForm
{...data}
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
/>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
const d = await getDeployment((await params).id);
return { title: d ? d.name : "Deployment" };
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const d = await getDeployment((await params).id);
if (!d) notFound();
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} />;
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string): Promise<boolean> {
const res = await fetch(url, { method });
if (res.ok) return true;
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
@@ -0,0 +1,612 @@
"use client";
import { BoxesIcon, CheckIcon, SearchIcon, TerminalIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { ArgsEditor } from "@/components/args-editor";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
export type FormRuntime = {
id: string;
name: string;
engine: RuntimeEngine;
image: string;
imageState: string;
env: Record<string, string>;
extraArgs: string[];
};
export type FormModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
export type FormHost = { cpus: number | null; memoryBytes: number | null; cpuFeatures: string[] } | null;
export type FormInitial = {
id?: string;
name: string;
runtimeId: string;
modelId: string;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
hostPort: number | null;
};
const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
const KV_TYPES = ["f16", "q8_0", "q4_0"];
const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
function Section({ step, title, description, children }: { step: number; title: string; description?: string; children: React.ReactNode }) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-primary text-xs text-primary-foreground">{step}</span>
{title}
</CardTitle>
{description && <CardDescription>{description}</CardDescription>}
</CardHeader>
<CardContent className="flex flex-col gap-4">{children}</CardContent>
</Card>
);
}
/** A titled block of related options inside the launch options card. */
function Group({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
return (
<div className="grid gap-3 border-t pt-5 first:border-t-0 first:pt-0 md:grid-cols-[11rem_1fr] md:gap-6">
<div className="flex flex-col gap-0.5">
<h3 className="text-sm font-medium">{title}</h3>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
</div>
<div className="grid content-start gap-4 sm:grid-cols-2">{children}</div>
</div>
);
}
/** `flag`: the command-line flag the field sets, shown next to the label. */
function Field({
label,
flag,
hint,
children,
htmlFor,
wide,
}: {
label: string;
flag?: string;
hint?: React.ReactNode;
children: React.ReactNode;
htmlFor?: string;
wide?: boolean;
}) {
return (
<div className={cn("flex flex-col gap-1.5", wide && "sm:col-span-2")}>
<div className="flex items-baseline justify-between gap-2">
<Label htmlFor={htmlFor}>{label}</Label>
{flag && <code className="font-mono text-[11px] text-muted-foreground">{flag}</code>}
</div>
{children}
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
);
}
/** Pick runtime → model and files → launch options. Used for "New deployment" and "Edit". */
export function DeploymentForm({
runtimes,
models,
host,
apiKeyCount,
initial,
}: {
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
apiKeyCount: number;
initial?: FormInitial;
}) {
const router = useRouter();
const editing = !!initial?.id;
const [runtimeId, setRuntimeId] = useState(initial?.runtimeId ?? runtimes.find((r) => r.imageState === "present")?.id ?? "");
const runtime = runtimes.find((r) => r.id === runtimeId) ?? null;
const engine = runtime?.engine ?? "llama.cpp";
const [query, setQuery] = useState("");
const [modelId, setModelId] = useState(initial?.modelId ?? "");
const servable = models.filter((m) => (engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm));
const shown = servable.filter((m) => m.repoId.toLowerCase().includes(query.trim().toLowerCase()));
const model = servable.find((m) => m.id === modelId) ?? null;
const o = initial?.options;
const [modelFile, setModelFile] = useState(o?.modelFile ?? "");
const [mmproj, setMmproj] = useState(o?.mmproj ?? "");
const [draftFile, setDraftFile] = useState(o?.draftFile ?? "");
const [name, setName] = useState(initial?.name ?? "");
const [contextSize, setContextSize] = useState(String(o?.contextSize ?? 4096));
const [threads, setThreads] = useState(o?.threads != null ? String(o.threads) : "");
const [parallel, setParallel] = useState(o?.parallel != null ? String(o.parallel) : "1");
const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? "");
const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
const [webui, setWebui] = useState(o?.webui !== false);
const [requireApiKey, setRequireApiKey] = useState(!!o?.requireApiKey);
const [batchSize, setBatchSize] = useState(o?.batchSize != null ? String(o.batchSize) : "");
const [ubatchSize, setUbatchSize] = useState(o?.ubatchSize != null ? String(o.ubatchSize) : "");
const [dtype, setDtype] = useState(o?.dtype ?? "");
const [maxNumSeqs, setMaxNumSeqs] = useState(o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "");
const [kvCacheGb, setKvCacheGb] = useState(o?.kvCacheGb != null ? String(o.kvCacheGb) : "");
const [argRows, setArgRows] = useState(() => argsToRows(o?.extraArgs ?? []));
const [cpus, setCpus] = useState(initial?.cpus != null ? String(initial.cpus) : "");
const [memoryMb, setMemoryMb] = useState(initial?.memoryMb != null ? String(initial.memoryMb) : "");
const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
const [hostPort, setHostPort] = useState(initial?.hostPort != null ? String(initial.hostPort) : "");
const [saving, setSaving] = useState(false);
function pickModel(m: FormModel) {
setModelId(m.id);
const first = m.candidates.gguf[0];
setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : "");
setMmproj(m.candidates.mmproj[0]?.path ?? "");
setDraftFile("");
if (!editing) setName(`${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim());
}
const options: DeploymentOptions = {
modelFile: engine === "llama.cpp" ? modelFile : "",
mmproj: engine === "llama.cpp" && mmproj ? mmproj : null,
draftFile: engine === "llama.cpp" && draftFile ? draftFile : null,
draftType: model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
contextSize: intOrNull(contextSize) ?? 4096,
threads: intOrNull(threads),
parallel: intOrNull(parallel),
batchSize: engine === "llama.cpp" ? intOrNull(batchSize) : null,
ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null,
cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null,
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
webui: engine === "llama.cpp" ? webui : null,
requireApiKey,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
extraArgs: rowsToArgs(argRows),
};
const fileBytes = model
? engine === "llama.cpp"
? (model.candidates.gguf.find((g) => g.path === modelFile)?.size ?? 0) +
(model.candidates.mmproj.find((g) => g.path === mmproj)?.size ?? 0) +
(model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0)
: (model.candidates.vllm?.size ?? 0)
: 0;
const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, options.kvCacheGb) : null;
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
runtime && model ? renderCommand(runtime.image, buildCommand({
engine,
options,
model,
runtime: { env: runtime.env, extraArgs: runtime.extraArgs },
apiKeys: Array.from({ length: apiKeyCount }, () => API_KEY_PLACEHOLDER),
})) : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
if (!runtime || !model) return;
setSaving(true);
try {
const body = {
name: name.trim() || model.repoId,
runtimeId: runtime.id,
modelId: model.id,
options,
cpus: numOrNull(cpus),
memoryMb: memory,
hostPort: intOrNull(hostPort),
start,
};
const res = await fetch(editing ? `/api/deployments/${initial!.id}` : "/api/deployments", {
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
return;
}
const id = editing ? initial!.id : json.id;
if (editing && start) await fetch(`/api/deployments/${id}/start`, { method: "POST" });
toast.success(start ? "Deployment starting" : "Deployment saved");
router.push(`/deployments/${id}`);
router.refresh();
} finally {
setSaving(false);
}
}
return (
<div className="flex flex-col gap-4">
<Section step={1} title="Runtime" description="The container image that serves the model.">
{runtimes.length === 0 ? (
<p className="text-sm text-muted-foreground">
No runtimes yet.{" "}
<Link href="/settings/runtimes" className="underline">
Add one in Settings
</Link>
.
</p>
) : (
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{runtimes.map((r) => {
const ready = r.imageState === "present";
return (
<button
key={r.id}
type="button"
disabled={!ready}
onClick={() => {
setRuntimeId(r.id);
if (r.engine !== engine) setModelId("");
}}
className={cn(
"flex flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50",
runtimeId === r.id ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/50",
)}
>
<span className="flex w-full items-center justify-between gap-2 text-sm font-medium">
<span className="flex items-center gap-1.5">
<BoxesIcon className="size-4 text-muted-foreground" />
{r.name}
</span>
{runtimeId === r.id && <CheckIcon className="size-4 text-primary" />}
</span>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
<span className="text-xs text-muted-foreground">
{r.engine === "vllm" ? "vLLM · safetensors" : "llama.cpp · GGUF"}
{!ready && " · image not pulled"}
</span>
</button>
);
})}
</div>
)}
{runtimes.some((r) => r.imageState !== "present") && (
<p className="text-xs text-muted-foreground">
Runtimes whose image isn&apos;t pulled yet can&apos;t be picked.{" "}
<Link href="/settings/runtimes" className="underline">
Pull them in Settings
</Link>
.
</p>
)}
</Section>
{runtime && (
<Section
step={2}
title="Model"
description={engine === "llama.cpp" ? "Downloaded GGUF models. Pick the quant and optional extras." : "Downloaded safetensors repos (with config.json)."}
>
{servable.length === 0 ? (
<p className="text-sm text-muted-foreground">
No downloaded model fits this runtime.{" "}
<Link href="/" className="underline">
Add one in the library
</Link>
{engine === "vllm" ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)." : "."}
</p>
) : (
<>
{servable.length > 6 && (
<div className="relative">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search models…" className="pl-8" />
</div>
)}
<div className="flex max-h-72 flex-col divide-y overflow-y-auto rounded-lg ring-1 ring-foreground/10">
{shown.map((m) => (
<button
key={m.id}
type="button"
onClick={() => pickModel(m)}
className={cn("flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50", modelId === m.id && "bg-primary/5")}
>
<span className="flex min-w-0 items-center gap-2">
{modelId === m.id ? <CheckIcon className="size-4 shrink-0 text-primary" /> : <span className="size-4 shrink-0" />}
<span className="truncate">{m.repoId}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{engine === "llama.cpp"
? `${m.candidates.gguf.length} GGUF${m.candidates.mmproj.length ? " · vision" : ""}${m.candidates.drafts.length ? " · MTP/draft" : ""}`
: formatBytes(m.candidates.vllm?.size ?? 0)}
</span>
</button>
))}
</div>
{model && engine === "llama.cpp" && (
<div className="grid gap-4 md:grid-cols-3">
<Field label="Model file" flag="-m">
<div className="flex flex-col gap-1">
{model.candidates.gguf.map((g) => (
<label key={g.path} className={cn("flex cursor-pointer items-center gap-2 rounded-md border px-2 py-1.5 text-xs", modelFile === g.path && "border-primary bg-primary/5")}>
<input type="radio" name="modelFile" checked={modelFile === g.path} onChange={() => setModelFile(g.path)} className="accent-primary" />
<span className="min-w-0 flex-1 truncate font-mono" title={g.path}>
{quantGroup(g.path) ?? g.path}
</span>
<span className="text-muted-foreground tabular-nums">{formatBytes(g.size)}</span>
</label>
))}
</div>
</Field>
<Field label="Vision (mmproj)" flag="--mmproj" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<NativeSelect value={mmproj} onChange={(e) => setMmproj(e.target.value)} disabled={model.candidates.mmproj.length === 0}>
<option value="">None</option>
{model.candidates.mmproj.map((m) => (
<option key={m.path} value={m.path}>
{m.path} ({formatBytes(m.size)})
</option>
))}
</NativeSelect>
</Field>
<Field
label="Speculative decoding"
flag="-md"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "Faster generation with an MTP head or draft model."}
>
<NativeSelect value={draftFile} onChange={(e) => setDraftFile(e.target.value)} disabled={model.candidates.drafts.length === 0}>
<option value="">Off</option>
{model.candidates.drafts.map((d) => (
<option key={d.path} value={d.path}>
{d.type === "draft-mtp" ? "MTP: " : "Draft: "}
{d.path} ({formatBytes(d.size)})
</option>
))}
</NativeSelect>
</Field>
</div>
)}
{model && (
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{[modelFile, mmproj, draftFile].filter(Boolean).map((p) => (
<span key={p} className="flex items-center gap-1">
<FileRoleBadge path={p} />
</span>
))}
<span>{formatBytes(fileBytes)} of model files</span>
</div>
)}
</>
)}
</Section>
)}
{runtime && model && (
<Section step={3} title="Launch options" description="Empty fields use the engine's defaults.">
<Group title="General" description="Name and how to reach the server.">
<Field label="Name" htmlFor="d-name">
<Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} />
</Field>
<Field label="Host port" htmlFor="d-port" hint={`Publishes container port ${ENGINE_PORT[engine]}; empty: only reachable inside Docker.`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={requireApiKey} onCheckedChange={(v) => setRequireApiKey(v === true)} className="mt-0.5" disabled={apiKeyCount === 0 && !requireApiKey} />
<span className="flex flex-col gap-0.5">
<span>Require an API key</span>
<span className="text-xs text-muted-foreground">
{apiKeyCount === 0 ? (
<>
No keys yet.{" "}
<Link href="/settings/api-keys" className="underline">
Add one in Settings
</Link>
.
</>
) : (
<>
Accepts any of the {apiKeyCount} key{apiKeyCount === 1 ? "" : "s"} from{" "}
<Link href="/settings/api-keys" className="underline">
Settings → API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.{engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
</>
)}
</span>
</span>
</label>
{engine === "llama.cpp" && (
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={webui} onCheckedChange={(v) => setWebui(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>Serve the llama.cpp web UI</span>
<span className="text-xs text-muted-foreground">
{webui
? hostPort
? `Opens at http://<server>:${hostPort}/ (no login on that port).`
: "Set a host port to open it."
: "Off: passes --no-webui; the API keeps working."}
</span>
</span>
</label>
)}
</Group>
<Group title="Context" description="How much text the model sees and how many requests run at once.">
<Field label="Context size (tokens)" flag={engine === "vllm" ? "--max-model-len" : "-c"} htmlFor="d-ctx" wide>
<div className="flex flex-wrap items-center gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-28" />
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c / 1024}k
</Button>
))}
</div>
</Field>
{engine === "vllm" ? (
<Field label="Max concurrent sequences" flag="--max-num-seqs" htmlFor="d-par">
<Input id="d-par" value={maxNumSeqs} onChange={(e) => setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
</Field>
) : (
<Field label="Parallel slots" flag="-np" htmlFor="d-par" hint="The context is split between slots.">
<Input id="d-par" value={parallel} onChange={(e) => setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
)}
</Group>
{engine === "llama.cpp" ? (
<Group title="Performance" description="CPU threads and prompt processing.">
<Field label="Threads" flag="-t / -tb" htmlFor="d-thr" hint={host?.cpus ? `Host has ${host.cpus} threads.` : undefined}>
<Input id="d-thr" value={threads} onChange={(e) => setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
<Field label="Flash attention" flag="-fa" htmlFor="d-fa">
<NativeSelect id="d-fa" value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)}>
<option value="">auto</option>
<option value="on">on</option>
<option value="off">off</option>
</NativeSelect>
</Field>
<Field label="Batch size" flag="-b" htmlFor="d-b">
<Input id="d-b" value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" />
</Field>
<Field label="Micro-batch size" flag="-ub" htmlFor="d-ub">
<Input id="d-ub" value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" />
</Field>
</Group>
) : (
<Group title="Performance" description="vLLM binds its CPU threads itself; limit cores under Resources.">
<Field
label="Data type"
flag="--dtype"
htmlFor="d-dtype"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster." : "Overrides the runtime's default."}
>
<NativeSelect id="d-dtype" value={dtype} onChange={(e) => setDtype(e.target.value)}>
<option value="">runtime default</option>
<option value="bfloat16">bfloat16</option>
<option value="float32">float32</option>
<option value="float16">float16</option>
<option value="auto">auto</option>
</NativeSelect>
</Field>
</Group>
)}
<Group title="KV cache" description="Memory for the context of running requests.">
{engine === "llama.cpp" ? (
<>
<Field label="K type" flag="-ctk" htmlFor="d-ctk" hint="q8_0 halves the memory.">
<NativeSelect id="d-ctk" value={cacheTypeK} onChange={(e) => setCacheTypeK(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
<Field label="V type" flag="-ctv" htmlFor="d-ctv">
<NativeSelect id="d-ctv" value={cacheTypeV} onChange={(e) => setCacheTypeV(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
</>
) : (
<Field label="KV cache size (GiB)" flag="VLLM_CPU_KVCACHE_SPACE" htmlFor="d-kv" hint="Reserved up front; must fit in the memory limit.">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
)}
</Group>
<Group title="Resources" description="Container limits.">
<Field label="CPU cores" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus}).` : "Empty: no limit."}>
<Input id="d-cpus" value={cpus} onChange={(e) => setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
</Field>
<Field
label="Memory (MiB)"
htmlFor="d-mem"
hint={
<>
Estimate: {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
{host?.memoryBytes ? ` · host: ${formatBytes(host.memoryBytes)}` : ""}
{memoryTouched && (
<button type="button" className="ml-1 underline" onClick={() => setMemoryTouched(false)}>
use estimate
</button>
)}
</>
}
>
<Input
id="d-mem"
value={memoryTouched ? memoryMb : String(estimate ?? "")}
onChange={(e) => {
setMemoryTouched(true);
setMemoryMb(e.target.value.replace(/\D/g, ""));
}}
inputMode="numeric"
/>
</Field>
</Group>
<Group
title="Extra arguments"
description={`Any other ${engine === "vllm" ? "vllm serve" : "llama-server"} flag. Added after the runtime's own arguments.`}
>
<div className="sm:col-span-2">
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--enforce-eager", value: "value (optional)" } : { flag: "--temp", value: "0.7" }} />
</div>
</Group>
</Section>
)}
{runtime && model && (
<Section step={4} title="Command" description="What Kaname runs, including the runtime's environment and arguments.">
{preview && (
<div className="relative">
<pre className="overflow-x-auto rounded-lg bg-muted/60 py-2.5 pr-12 pl-3 font-mono text-xs break-all whitespace-pre-wrap">
<TerminalIcon className="mr-1.5 inline size-3.5 align-[-2px] text-muted-foreground" />
{preview}
</pre>
<div className="absolute top-1.5 right-1.5">
<CopyButton value={preview} label="Copy command" />
</div>
</div>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => router.back()}>
Cancel
</Button>
<Button type="button" variant="outline" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(false)}>
{editing ? "Save" : "Create"}
</Button>
<Button type="button" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(true)}>
{editing ? "Save & start" : "Create & start"}
</Button>
</div>
</Section>
)}
</div>
);
}
@@ -0,0 +1,107 @@
"use client";
import { ExternalLinkIcon, PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { startDeployment, stopDeployment } from "./actions";
type Row = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
const isActive = (r: Row) => r.desiredState === "running" || r.state === "starting" || r.state === "running" || r.state === "stopping";
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
const hostname = useHostname();
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
async function reload() {
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(() => null);
if (res?.ok) setRows(await res.json());
}
useEffect(() => {
const t = setInterval(reload, busy ? 2_000 : 5_000);
return () => clearInterval(t);
}, [busy]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<RocketIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">No deployments yet. Pick a runtime and a downloaded model to start one.</p>
<Link href="/deployments/new" className="text-sm underline">
New deployment
</Link>
</Card>
);
}
return (
<div className="grid gap-3 md:grid-cols-2">
{rows.map((r) => {
const file = r.options.modelFile ? (quantGroup(r.options.modelFile) ?? r.options.modelFile) : null;
const loadSecs = r.readyAt && r.startedAt ? (new Date(r.readyAt).getTime() - new Date(r.startedAt).getTime()) / 1000 : null;
return (
<Card key={r.id} className="gap-3 px-4 py-3">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-0.5">
<Link href={`/deployments/${r.id}`} className="truncate font-medium hover:underline">
{r.name}
</Link>
<span className="truncate text-xs text-muted-foreground">
{r.repoId}
{file && ` · ${file}`}
{r.options.mmproj && " · vision"}
{r.options.draftFile && " · MTP/draft"}
</span>
<span className="text-xs text-muted-foreground">{r.runtimeName}</span>
</div>
<DeploymentStateBadge state={r.state} desiredState={r.desiredState} />
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="tabular-nums">
{r.state === "running" && r.stats
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
: r.state === "failed"
? (r.error?.split("\n")[0] ?? "failed")
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
{r.state === "running" && loadSecs != null && ` · loaded in ${loadSecs.toFixed(1)} s`}
</span>
<span className="flex items-center gap-1.5">
{r.state === "running" && webUiUrl(r, hostname) && (
<a href={webUiUrl(r, hostname)!} target="_blank" rel="noreferrer" className={buttonVariants({ size: "xs", variant: "outline" })}>
<ExternalLinkIcon />
Web UI
</a>
)}
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
</span>
</div>
</Card>
);
})}
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
apiKeyCount: keys.length,
};
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { deployPreset } from "@/lib/deployments";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
const { model } = await searchParams;
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} initial={preset ?? undefined} />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { listDeployments } from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { DeploymentList } from "./deployment-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Deployments" };
export default async function DeploymentsPage() {
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Deployments</h1>
<Link href="/deployments/new" className={buttonVariants()}>
New deployment
</Link>
</div>
{!docker?.connected && (
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
<Link href="/settings/runtimes" className="underline">
Settings → Runtimes
</Link>
.
</p>
)}
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
+4
View File
@@ -16,12 +16,15 @@ export function FacetFilter({
selected,
onChange,
format = (v) => v,
marker,
}: {
label: string;
values: [string, number][];
selected: string[];
onChange: (next: string[]) => void;
format?: (value: string) => string;
/** Optional element before each value, e.g. a tag's color dot. */
marker?: (value: string) => React.ReactNode;
}) {
const active = selected.length > 0;
return (
@@ -41,6 +44,7 @@ export function FacetFilter({
closeOnClick={false}
onCheckedChange={(on) => onChange(on ? [...selected, value] : selected.filter((v) => v !== value))}
>
{marker?.(value)}
<span className="flex-1">{format(value)}</span>
<span className="ml-4 text-xs text-muted-foreground tabular-nums">{count}</span>
</DropdownMenuCheckboxItem>
+3 -2
View File
@@ -10,6 +10,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useLive } from "@/hooks/use-live";
import { formatDuration } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { jobLabel } from "@/lib/job-labels";
import type { JobSnapshot } from "@/lib/jobs";
const OPEN = ["queued", "downloading", "verifying"];
@@ -40,8 +41,8 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold">
{job.kind === "download" ? "Download" : job.kind} ·{" "}
<Link href={`/models/${job.modelId}`} className="hover:underline">
{jobLabel(job)} ·{" "}
<Link href={`/${job.repoId}`} className="hover:underline">
{job.repoId}
</Link>
</h1>
+23 -22
View File
@@ -1,48 +1,49 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
import { Button } from "@/components/ui/button";
import { AppNav } from "@/components/app-nav";
import { LabelSettingsProvider } from "@/components/labels";
import { UserMenu } from "@/components/user-menu";
import { WorkerIndicator } from "@/components/worker-indicator";
import { 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 = await getWorkerStatus();
const [worker, fileRoles, recommendedRoles] = await Promise.all([
getWorkerStatus(),
getFileRoleStyles(),
getRecommendedRoles(),
]);
return (
<div className="flex min-h-screen flex-col">
<div className="flex min-h-screen flex-col overflow-x-clip">
<header className="border-b">
<div className="mx-auto flex h-14 max-w-6xl items-center gap-6 px-4">
<Link href="/" className="flex items-baseline gap-1.5 font-semibold">
<div className="mx-auto flex h-14 max-w-7xl items-center gap-3 px-4 sm:gap-6">
<Link href="/" className="flex items-center gap-2 font-semibold">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/icon.svg" alt="" className="size-6" />
Kaname
<span className="text-xs font-normal text-muted-foreground">{process.env.APP_VERSION ?? "dev"}</span>
<span className="hidden text-xs font-normal text-muted-foreground sm:inline">{process.env.APP_VERSION ?? "dev"}</span>
</Link>
<nav className="flex items-center gap-4 text-sm text-muted-foreground">
<Link href="/" className="hover:text-foreground">
Library
</Link>
</nav>
<AppNav />
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
<span className="hidden text-sm text-muted-foreground sm:inline">
{session.user.name ?? session.user.email}
</span>
<form
action={async () => {
<UserMenu
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
signOutAction={async () => {
"use server";
await signOut({ redirectTo: "/login" });
}}
>
<Button type="submit" variant="ghost" size="sm">
Sign out
</Button>
</form>
/>
</div>
</div>
</header>
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-6">{children}</main>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
</main>
</div>
);
}
+58 -5
View File
@@ -1,14 +1,16 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -17,6 +19,7 @@ import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
@@ -54,6 +57,12 @@ function toSearchable(r: LibraryRow): SearchableModel {
pipelineTag: r.pipelineTag,
license: r.license,
status: r.status,
hubStatus:
r.hubState && r.hubState !== "available"
? HUB_STATE_LABEL[r.hubState].label
: r.updateAvailable
? "update available"
: null,
};
}
@@ -92,6 +101,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
};
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 anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
@@ -122,6 +132,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : undefined}
/>
))}
</div>
@@ -134,6 +145,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{FACETS.flatMap((facet) =>
filters[facet].map((v) => (
<Badge key={`${facet}:${v}`} variant="secondary" className="gap-1">
{facet === "tag" && <TagDot name={v} color={tagColors.get(v)} />}
{FACET_LABEL[facet]}: {facet === "status" ? statusLabel(v) : v}
<button
type="button"
@@ -169,6 +181,9 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
<TableHead className="w-24">
<span className="sr-only">Deploy</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -178,19 +193,36 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
return (
<TableRow key={r.id}>
<TableCell className="whitespace-normal">
<Link href={`/models/${r.id}`} className="font-medium hover:underline">
<Link href={`/${r.repoId}`} className="font-medium hover:underline">
{r.repoId}
</Link>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
<Link
key={d.id}
href={`/deployments/${d.id}`}
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
>
<RocketIcon className="size-3" />
<span className="max-w-40 truncate">{d.name}</span>
<span
className={cn(
"size-1.5 rounded-full",
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
)}
/>
</Link>
))}
{r.tags.map((t) => (
<button
key={t.id}
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<Badge variant="outline">{t.name}</Badge>
<TagBadge name={t.name} color={t.color} />
</button>
))}
</div>
@@ -214,7 +246,28 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<ModelStatusBadge status={r.status} />
<span className="flex flex-wrap gap-1">
<ModelStatusBadge status={r.status} />
<HubStateBadge state={r.hubState} />
{r.updateAvailable && (r.hubState === "available" || !r.hubState) && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium whitespace-nowrap text-sky-700 dark:text-sky-300">
update available
</span>
)}
</span>
)}
</TableCell>
<TableCell>
{r.deployable && (
<Link
href={`/deployments/new?model=${r.id}`}
className={buttonVariants({ variant: "outline", size: "xs" })}
title="Serve this model with a runtime"
aria-label={`Deploy ${r.repoId}`}
>
<RocketIcon />
Deploy
</Link>
)}
</TableCell>
</TableRow>
-136
View File
@@ -1,136 +0,0 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { cancelJob, startDownload } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import type { JobSnapshot } from "@/lib/jobs";
const OPEN = ["queued", "downloading", "verifying"];
export function ModelLive({ modelId, status }: { modelId: string; status: ModelStatus }) {
const { snapshot } = useLive({ model: modelId });
const [busy, setBusy] = useState(false);
const jobs = snapshot?.jobs ?? [];
const latest = jobs[0] as JobSnapshot | undefined;
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const workerOffline = snapshot && !snapshot.worker.online;
async function run(fn: () => Promise<void>) {
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
}
return (
<>
<Card>
<CardHeader>
<CardTitle className="flex flex-wrap items-center gap-2">
Download
{latest && <JobStateBadge job={latest} />}
</CardTitle>
<CardDescription>
{open
? open.state === "queued"
? workerOffline
? "Queued, but the worker is offline."
: "Queued, waiting for a free download slot."
: "Running in the background; you can close this page."
: status === "ready"
? "All selected files are present."
: "Downloads the selected files at the pinned SHA."}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{latest && !(latest.state === "completed" && status === "ready") && <JobProgress job={latest} compact />}
{latest?.errorMessage && latest.state === "failed" && (
<pre className="rounded-md bg-destructive/10 px-3 py-2 text-xs whitespace-pre-wrap text-destructive">
{latest.errorMessage}
</pre>
)}
<div className="flex flex-wrap gap-2">
{open ? (
<Button
variant="destructive"
size="sm"
disabled={busy || open.cancelRequested}
onClick={() => run(() => cancelJob(open.id))}
>
{open.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
status !== "ready" &&
snapshot && (
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
{latest ? "Download again" : "Download"}
</Button>
)
)}
{latest && (
<Link
href={`/jobs/${latest.id}`}
className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted"
>
View log
</Link>
)}
</div>
</CardContent>
{open && snapshot && snapshot.files.length > 0 && <JobFilesTable files={snapshot.files} />}
</Card>
{jobs.length > 0 && (
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>Jobs</CardTitle>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>Started</TableHead>
<TableHead>Kind</TableHead>
<TableHead>State</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden sm:table-cell">Finished</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<Link href={`/jobs/${j.id}`} className="hover:underline">
<LocalTime value={j.startedAt ?? j.createdAt} />
</Link>
</TableCell>
<TableCell className="text-sm">
{j.kind}
{j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""}
</TableCell>
<TableCell>
<JobStateBadge job={j} />
</TableCell>
<TableCell className="text-right text-sm tabular-nums">{formatBytes(j.totalBytes)}</TableCell>
<TableCell className="hidden text-sm text-muted-foreground sm:table-cell">
<LocalTime value={j.finishedAt} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
)}
</>
);
}
+9 -118
View File
@@ -1,123 +1,14 @@
import { notFound } from "next/navigation";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatBytes } from "@/lib/format";
import { LocalTime } from "@/components/local-time";
import { modelFamilies } from "@/lib/hub/metadata";
import { getModel } from "@/lib/library";
import { modelTagList } from "@/lib/tags";
import { ModelLive } from "./model-live";
import { RemoveModelButton } from "./remove-model-button";
import { TagEditor } from "./tag-editor";
import { eq } from "drizzle-orm";
import { notFound, permanentRedirect } from "next/navigation";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
export const dynamic = "force-dynamic";
export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
/** Old URL scheme (/models/<id>): redirect to /<org>/<name>. */
export default async function LegacyModelPage({ params }: PageProps<"/models/[id]">) {
const { id } = await params;
const data = await getModel(id);
if (!data) notFound();
const { model, files } = data;
const modelTags = await modelTagList(model.id);
const selected = files.filter((f) => f.selected);
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold break-all">{model.repoId}</h1>
<ModelStatusBadge status={model.status} />
<div className="ml-auto">{model.status === "pending" && <RemoveModelButton id={model.id} />}</div>
</div>
<TagEditor modelId={model.id} tags={modelTags} />
<Card>
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm">
<dt className="text-muted-foreground">Hub</dt>
<dd>
<a
href={`https://huggingface.co/${model.repoId}/tree/${model.pinnedSha}`}
target="_blank"
rel="noreferrer"
className="underline"
>
huggingface.co/{model.repoId}
</a>
</dd>
<dt className="text-muted-foreground">Author</dt>
<dd>{model.repoId.split("/")[0]}</dd>
<dt className="text-muted-foreground">Family</dt>
<dd>{modelFamilies(model.repoId, model.baseModels).join(", ")}</dd>
<dt className="text-muted-foreground">Base model</dt>
<dd className="flex flex-col">
{(model.baseModels ?? []).length === 0
? "–"
: model.baseModels!.map((b) => (
<a key={b} href={`https://huggingface.co/${b}`} target="_blank" rel="noreferrer" className="underline">
{b}
</a>
))}
</dd>
<dt className="text-muted-foreground">Architecture</dt>
<dd>{model.architecture ?? "–"}</dd>
<dt className="text-muted-foreground">License</dt>
<dd>{model.license ?? "–"}</dd>
{(model.hubTags ?? []).length > 0 && (
<>
<dt className="text-muted-foreground">Hub tags</dt>
<dd className="text-xs text-muted-foreground">{model.hubTags!.join(", ")}</dd>
</>
)}
<dt className="text-muted-foreground">Tracked revision</dt>
<dd className="font-mono">{model.trackedRevision}</dd>
<dt className="text-muted-foreground">Pinned SHA</dt>
<dd className="font-mono break-all">{model.pinnedSha}</dd>
<dt className="text-muted-foreground">Local path</dt>
<dd className="font-mono break-all">$MODELS_DIR/{model.localPath}</dd>
<dt className="text-muted-foreground">Include</dt>
<dd className="font-mono text-xs break-all">{model.includePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Exclude</dt>
<dd className="font-mono text-xs break-all">{model.excludePatterns.join(", ") || "–"}</dd>
<dt className="text-muted-foreground">Added</dt>
<dd><LocalTime value={model.createdAt} /></dd>
</dl>
</CardContent>
</Card>
<ModelLive modelId={model.id} status={model.status} />
<Card className="py-0">
<CardHeader className="pt-4">
<CardTitle>
Selected files · {selected.length} · {formatBytes(totalBytes)}
</CardTitle>
<CardDescription>
{files.length - selected.length} other files in the repo are not selected.
</CardDescription>
</CardHeader>
<Table>
<TableHeader>
<TableRow>
<TableHead>File</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead>State</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{selected.map((f) => (
<TableRow key={f.id}>
<TableCell className="font-mono text-xs break-all whitespace-normal">{f.path}</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
<TableCell className="text-sm text-muted-foreground">{f.state}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</div>
);
const model = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.id, id) });
if (!model) notFound();
permanentRedirect(`/${model.repoId}`);
}
@@ -1,57 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
/** Removes a not-yet-downloaded model from the library (DB only, no files exist yet). */
export function RemoveModelButton({ id }: { id: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function remove() {
setBusy(true);
const res = await fetch(`/api/models/${id}`, { method: "DELETE" });
if (res.ok) {
toast.success("Removed from library");
router.push("/");
router.refresh();
} else {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Remove failed (${res.status})`);
setBusy(false);
}
}
return (
<AlertDialog>
<AlertDialogTrigger render={<Button variant="destructive" size="sm" />}>Remove</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove from library?</AlertDialogTitle>
<AlertDialogDescription>
Nothing has been downloaded yet, so this only removes the entry.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove} disabled={busy}>
Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
-87
View File
@@ -1,87 +0,0 @@
"use client";
import { XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useId, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import type { Tag } from "@/lib/tags";
/** Add/remove user tags on a model; suggests existing tags. */
export function TagEditor({ modelId, tags }: { modelId: string; tags: Tag[] }) {
const router = useRouter();
const listId = useId();
const [value, setValue] = useState("");
const [busy, setBusy] = useState(false);
const [suggestions, setSuggestions] = useState<string[]>([]);
useEffect(() => {
fetch("/api/tags")
.then((r) => (r.ok ? r.json() : []))
.then((all: Tag[]) => setSuggestions(all.map((t) => t.name)))
.catch(() => {});
}, [tags]);
async function add(name: string) {
if (!name.trim()) return;
setBusy(true);
const res = await fetch(`/api/models/${modelId}/tags`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
setBusy(false);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Could not add tag (${res.status})`);
return;
}
setValue("");
router.refresh();
}
async function remove(tag: Tag) {
const res = await fetch(`/api/models/${modelId}/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not remove tag (${res.status})`);
router.refresh();
}
const current = new Set(tags.map((t) => t.name.toLowerCase()));
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((t) => (
<Badge key={t.id} variant="secondary" className="gap-1">
{t.name}
<button type="button" aria-label={`Remove tag ${t.name}`} onClick={() => remove(t)}>
<XIcon className="size-3" />
</button>
</Badge>
))}
<form
onSubmit={(e) => {
e.preventDefault();
void add(value);
}}
>
<Input
value={value}
onChange={(e) => setValue(e.target.value)}
list={listId}
placeholder="Add tag…"
disabled={busy}
maxLength={40}
className="h-6 w-36 text-xs"
aria-label="Add tag"
/>
<datalist id={listId}>
{suggestions
.filter((s) => !current.has(s.toLowerCase()))
.map((s) => (
<option key={s} value={s} />
))}
</datalist>
</form>
</div>
);
}
+8 -3
View File
@@ -1,4 +1,5 @@
import { listLibrary } from "@/lib/library";
import { listLocalFolders } from "@/lib/local-folders";
import { getWorkerStatus } from "@/lib/worker-status";
import { AddModelPanel } from "./add-model-panel";
import { LibraryView } from "./library-view";
@@ -6,12 +7,16 @@ import { LibraryView } from "./library-view";
export const dynamic = "force-dynamic";
export default async function LibraryPage() {
const [rows, worker] = await Promise.all([listLibrary(), getWorkerStatus()]);
const [rows, worker, folders] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders()]);
return (
<div className="flex flex-col gap-4">
{/* Opens by default while the library is empty. */}
<AddModelPanel freeBytes={worker.online ? worker.modelsDirFreeBytes : null} defaultOpen={rows.length === 0} />
{/* Opens by default while the library is empty and there's nothing on disk to import. */}
<AddModelPanel
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
defaultOpen={rows.length === 0 && folders.length === 0}
folders={folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes }))}
/>
{rows.length > 0 && <LibraryView rows={rows} />}
</div>
);
@@ -0,0 +1,172 @@
"use client";
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { ApiKeyRow } from "@/lib/api-keys";
/** Keys that deployments with "Require an API key" accept. */
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewKeyRow onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">API key &ldquo;{created.name}&rdquo; added. You can show it again from the list.</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.key}</code>
<CopyButton value={created.key} label="Copy API key" />
</div>
</div>
)}
{keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{keys.map((k) => (
<KeyRow key={k.id} apiKey={k} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, key: key.trim() || undefined }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
return;
}
onCreated({ name: json.name, key: json.key });
setName("");
setKey("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
<Input
value={key}
maxLength={256}
disabled={busy}
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
placeholder="Key (empty: generate one)"
aria-label="Key value"
spellCheck={false}
autoComplete="off"
className="font-mono text-xs md:text-xs"
/>
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
<PlusIcon />
Add
</Button>
</form>
);
}
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
const router = useRouter();
const [shown, setShown] = useState<string | null>(null);
async function toggle() {
if (shown) return setShown(null);
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
else setShown(json.key);
}
async function remove() {
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`API key "${apiKey.name}" deleted`);
router.refresh();
}
return (
<div className="flex items-center gap-3 px-4 py-2.5">
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
{shown ? (
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
{shown}
</code>
<CopyButton value={shown} label="Copy API key" />
</span>
) : (
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
)}
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
{shown ? <EyeOffIcon /> : <EyeIcon />}
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
<LocalTime value={apiKey.createdAt} />
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API key &ldquo;{apiKey.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { getRecommendedRoles } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Downloads · Settings" };
export default async function DownloadSettingsPage() {
return <RecommendedSettings initial={await getRecommendedRoles()} />;
}
@@ -0,0 +1,96 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { FILE_ROLES, type FileRole } from "@/lib/file-roles";
import { RECOMMENDABLE_ROLES } from "@/lib/recommend";
/** Example file name per kind, so the badge shows the configured label and color. */
const EXAMPLE: Partial<Record<FileRole, string>> = {
template: "chat_template.jinja",
mtp: "mtp-model.gguf",
vision: "mmproj-F16.gguf",
draft: "model-draft.gguf",
config: "config.json",
tokenizer: "tokenizer.json",
imatrix: "imatrix.dat",
adapter: "adapter_model.safetensors",
docs: "README.md",
};
const HINT: Partial<Record<FileRole, string>> = {
mtp: "The variant with the same quant as your model file, otherwise the closest one.",
vision: "One mmproj file: same quant if there is one, otherwise F16, BF16, Q8_0, F32.",
draft: "One draft model, picked like MTP.",
imatrix: "Only needed to make your own quants.",
config: "GGUF files already contain it; useful for safetensors repos.",
tokenizer: "GGUF files already contain it; useful for safetensors repos.",
};
/** Which file kinds are selected automatically when you pick model weights. Saves on change. */
export function RecommendedSettings({ initial }: { initial: FileRole[] }) {
const router = useRouter();
const [roles, setRoles] = useState(new Set(initial));
const [saving, setSaving] = useState(false);
async function toggle(role: FileRole, on: boolean) {
const before = roles;
const next = new Set(roles);
if (on) next.add(role);
else next.delete(role);
setRoles(next);
setSaving(true);
try {
const res = await fetch("/api/settings/downloads", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ recommendedRoles: [...next] }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Could not save (${res.status})`);
setRoles(before);
return;
}
router.refresh();
} finally {
setSaving(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Recommended files</CardTitle>
<CardDescription>
When you pick model weights (a quant) in Add model or Download more, files of these kinds are selected along
with them. You can still uncheck them before downloading.
</CardDescription>
</CardHeader>
<CardContent>
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{RECOMMENDABLE_ROLES.map((role) => (
<label key={role} className="flex cursor-pointer items-start gap-3 px-4 py-3 hover:bg-muted/40">
<Checkbox
checked={roles.has(role)}
disabled={saving}
onCheckedChange={(v) => void toggle(role, v === true)}
className="mt-0.5"
aria-label={FILE_ROLES[role].label}
/>
<FileRoleBadge path={EXAMPLE[role] ?? role} />
<span className="flex min-w-0 flex-col">
<span className="text-sm">{FILE_ROLES[role].description}</span>
{HINT[role] && <span className="text-xs text-muted-foreground">{HINT[role]}</span>}
</span>
</label>
))}
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,46 @@
"use client";
import { ChevronDownIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DOT_CLASS, LABEL_COLORS, type LabelColor } from "@/lib/colors";
import { cn } from "@/lib/utils";
/** Dropdown of the named label colors; optional "Automatic" entry (value null). */
export function ColorPicker({
value,
onChange,
allowAuto = false,
autoColor,
}: {
value: LabelColor | null;
onChange: (color: LabelColor | null) => void;
allowAuto?: boolean;
/** Color shown for the automatic option. */
autoColor?: LabelColor;
}) {
const shown = value ?? autoColor ?? "gray";
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="outline" size="sm" className="w-32 justify-start" />}>
<span className={cn("size-3 rounded-full", DOT_CLASS[shown])} />
<span className="flex-1 text-left capitalize">{value ?? "Automatic"}</span>
<ChevronDownIcon className="opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-72 min-w-40">
{allowAuto && (
<DropdownMenuItem onClick={() => onChange(null)}>
<span className={cn("size-3 rounded-full", DOT_CLASS[autoColor ?? "gray"])} />
Automatic
</DropdownMenuItem>
)}
{LABEL_COLORS.map((c) => (
<DropdownMenuItem key={c} onClick={() => onChange(c)}>
<span className={cn("size-3 rounded-full", DOT_CLASS[c])} />
<span className="capitalize">{c}</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,112 @@
"use client";
import { RotateCcwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { BADGE_CLASS } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRoleStyles } from "@/lib/file-roles";
import { cn } from "@/lib/utils";
import { ColorPicker } from "./color-picker";
/** Edit the label text and color shown in front of file names. */
export function FileLabelSettings({ initial }: { initial: FileRoleStyles }) {
const router = useRouter();
const [styles, setStyles] = useState(initial);
const [saving, setSaving] = useState(false);
const dirty = JSON.stringify(styles) !== JSON.stringify(initial);
function update(role: keyof FileRoleStyles, patch: Partial<FileRoleStyles[keyof FileRoleStyles]>) {
setStyles((prev) => ({ ...prev, [role]: { ...prev[role], ...patch } }));
}
async function save(next = styles) {
setSaving(true);
try {
const res = await fetch("/api/settings/labels", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileRoles: next }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not save (${res.status})`);
return;
}
setStyles(body.fileRoles);
toast.success("File labels saved");
router.refresh();
} finally {
setSaving(false);
}
}
const defaults = Object.fromEntries(
FILE_ROLE_ORDER.map((r) => [r, { label: FILE_ROLES[r].label, color: FILE_ROLES[r].color }]),
) as FileRoleStyles;
return (
<Card>
<CardHeader>
<CardTitle>File labels</CardTitle>
<CardDescription>
Shown in front of file names (Files tab, Add model). Kaname detects the type from the file name; here you
choose how each type is labeled and colored.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{FILE_ROLE_ORDER.map((role) => {
const s = styles[role];
const changed = s.label !== defaults[role].label || s.color !== defaults[role].color;
return (
<div key={role} className="grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[6rem_minmax(0,1fr)_10rem_8rem_2rem]">
<span
className={cn(
"inline-flex h-5 justify-self-start rounded-md border px-1.5 text-[11px] leading-[18px] font-medium",
BADGE_CLASS[s.color],
)}
>
{s.label || "…"}
</span>
<span className="min-w-0 text-xs text-muted-foreground">{FILE_ROLES[role].description}</span>
<Input
value={s.label}
maxLength={24}
onChange={(e) => update(role, { label: e.target.value })}
aria-label={`Label for ${FILE_ROLES[role].label}`}
className="h-8"
/>
<ColorPicker value={s.color} onChange={(c) => c && update(role, { color: c })} />
<Button
variant="ghost"
size="icon-sm"
disabled={!changed}
title="Reset to default"
aria-label="Reset to default"
onClick={() => update(role, defaults[role])}
>
<RotateCcwIcon />
</Button>
</div>
);
})}
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button variant="ghost" onClick={() => setStyles(initial)} disabled={!dirty || saving}>
Discard changes
</Button>
<Button variant="outline" onClick={() => save(defaults)} disabled={saving}>
Reset all to defaults
</Button>
<Button onClick={() => save()} disabled={!dirty || saving}>
{saving ? "Saving…" : "Save"}
</Button>
</div>
</CardContent>
</Card>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { getFileRoleStyles } from "@/lib/settings";
import { FileLabelSettings } from "./file-label-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "File labels · Settings" };
export default async function LabelSettingsPage() {
return <FileLabelSettings initial={await getFileRoleStyles()} />;
}
+22
View File
@@ -0,0 +1,22 @@
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Settings</h1>
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
<SettingsNav sections={SECTIONS} />
<div className="min-w-0">{children}</div>
</div>
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function SettingsPage() {
redirect("/settings/labels");
}
+12
View File
@@ -0,0 +1,12 @@
import type { Metadata } from "next";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import { getWorkerStatus } from "@/lib/worker-status";
import { RuntimesView } from "./runtimes-view";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Runtimes · Settings" };
export default async function RuntimesPage() {
const [runtimes, docker, worker] = await Promise.all([listRuntimes(), getDockerInfo(), getWorkerStatus()]);
return <RuntimesView runtimes={runtimes} docker={docker} workerOnline={worker.online} />;
}
@@ -0,0 +1,180 @@
"use client";
import { useState } from "react";
import { ArgsEditor } from "@/components/args-editor";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
{ id: "llama.cpp", label: "llama.cpp-compatible", hint: "llama-server command line, GGUF models" },
{ id: "vllm", label: "vLLM-compatible", hint: "vllm serve command line, safetensors models" },
];
const textareaClass =
"min-h-20 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
/** Create/edit a runtime. Validates locally with the same rules as the server. */
export function RuntimeForm({
initial,
submitLabel,
onSubmit,
onCancel,
}: {
initial: RuntimeInput;
submitLabel: string;
onSubmit: (value: RuntimeInput) => Promise<boolean>;
onCancel: () => void;
}) {
const [name, setName] = useState(initial.name);
const [engine, setEngine] = useState<RuntimeEngine>(initial.engine);
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
const [numa, setNuma] = useState(!!initial.numaTuning);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
async function submit(e: React.FormEvent) {
e.preventDefault();
let value: RuntimeInput;
try {
value = validateRuntime({
name,
engine,
image,
description,
env: parseEnvLines(envText),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
shmSizeMb: shm.trim() ? Number(shm) : null,
numaTuning: numa,
});
} catch (err) {
setError(err instanceof RuntimeValidationError ? err.message : String(err));
return;
}
setError(null);
setSaving(true);
try {
await onSubmit(value);
} finally {
setSaving(false);
}
}
return (
<form onSubmit={submit} className="flex flex-col gap-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-name">Name</Label>
<Input id="rt-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="vLLM XPU (Arc patches)" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-image">Image</Label>
<Input
id="rt-image"
value={image}
onChange={(e) => setImage(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="registry.example.com/org/image:tag"
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label>Engine type</Label>
<div className="grid gap-2 sm:grid-cols-2">
{ENGINES.map((e) => (
<button
key={e.id}
type="button"
onClick={() => setEngine(e.id)}
className={cn(
"flex flex-col items-start rounded-lg border px-3 py-2 text-left text-sm transition-colors",
engine === e.id ? "border-primary bg-primary/5" : "hover:bg-muted/50",
)}
>
<span className="font-medium">{e.label}</span>
<span className="text-xs text-muted-foreground">{e.hint}</span>
</button>
))}
</div>
<p className="text-xs text-muted-foreground">
Decides how Kaname builds the command line. Forks with the same CLI (e.g. patched vLLM builds) use the same type.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-desc">Description</Label>
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label>Extra arguments</Label>
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--dtype", value: "bfloat16" } : { flag: "--temp", value: "0.7" }} />
<p className="text-xs text-muted-foreground">Added to every deployment&apos;s command; a deployment can override them.</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-shm">Shared memory (MiB)</Label>
<Input id="rt-shm" value={shm} onChange={(e) => setShm(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric" placeholder="Docker default (64)" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-devices">Devices</Label>
<Input
id="rt-devices"
value={devicesText}
onChange={(e) => setDevicesText(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="/dev/dri (Intel/AMD GPUs, later)"
/>
</div>
</div>
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg bg-muted/50 px-3 py-2.5 text-sm">
<Checkbox checked={numa} onCheckedChange={(v) => setNuma(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>NUMA tuning</span>
<span className="text-xs text-muted-foreground">
Adds <code>CAP_SYS_NICE</code> and <code>seccomp=unconfined</code>, as vLLM recommends for its CPU build. This relaxes
the container&apos;s isolation; leave it off unless you need the extra speed.
</span>
</span>
</label>
{error && <p className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</p>}
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button type="submit" disabled={saving}>
{saving ? "Saving…" : submitLabel}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,352 @@
"use client";
import { ChevronDownIcon, CopyIcon, DownloadCloudIcon, PencilIcon, PlusIcon, ServerIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Progress } from "@/components/ui/progress";
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
import { formatBytes, percent } from "@/lib/format";
import { RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
import { RuntimeForm } from "./runtime-form";
type Runtime = typeof runtimes.$inferSelect;
const FEATURE_LABEL: Record<string, string> = {
avx2: "AVX2",
avx512f: "AVX-512",
avx512_bf16: "AVX-512 BF16",
avx512_vnni: "AVX-512 VNNI",
avx512bw: "AVX-512 BW",
amx_bf16: "AMX BF16",
amx_int8: "AMX INT8",
f16c: "F16C",
fma: "FMA",
};
async function send(url: string, method: string, body?: unknown): Promise<boolean> {
const res = await fetch(url, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
if (res.ok) return true;
const json = await res.json().catch(() => ({}));
toast.error(json.error?.message ?? `Request failed (${res.status})`);
return false;
}
const toInput = (r: Runtime): RuntimeInput => ({
name: r.name,
engine: r.engine,
image: r.image,
description: r.description,
env: r.env,
extraArgs: r.extraArgs,
devices: r.devices,
shmSizeMb: r.shmSizeMb,
numaTuning: r.numaTuning,
});
export function RuntimesView({ runtimes, docker, workerOnline }: { runtimes: Runtime[]; docker: DockerHostInfo | null; workerOnline: boolean }) {
const router = useRouter();
const [creating, setCreating] = useState<(RuntimeInput & { preset?: string }) | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const anyPulling = runtimes.some((r) => r.imageState === "pulling" || (r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt)));
// While a pull runs, refresh the server data every 2 s for its progress.
useEffect(() => {
if (!anyPulling) return;
const t = setInterval(() => router.refresh(), 2_000);
return () => clearInterval(t);
}, [anyPulling, router]);
return (
<div className="flex flex-col gap-4">
<HostCard docker={docker} workerOnline={workerOnline} />
<Card>
<CardHeader>
<CardTitle>Runtimes</CardTitle>
<CardDescription>
Container images that serve models: official llama.cpp and vLLM builds, or your own forks from any registry. Kaname
only starts images registered here, with the models mounted read-only.
</CardDescription>
<CardAction>
<DropdownMenu>
<DropdownMenuTrigger render={<Button size="sm" />}>
<PlusIcon />
Add runtime
<ChevronDownIcon className="opacity-70" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-72">
<DropdownMenuGroup>
<DropdownMenuLabel>From a preset</DropdownMenuLabel>
{RUNTIME_PRESETS.map((p) => (
<DropdownMenuItem key={p.id} onClick={() => setCreating({ ...p, name: p.name, preset: p.id })} className="flex-col items-start gap-0">
<span>{p.name}</span>
<span className="text-xs text-muted-foreground">{p.summary}</span>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setCreating({ name: "", engine: "vllm", image: "" })}>Custom image (fork)…</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardAction>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{creating && (
<div className="rounded-lg p-4 ring-1 ring-primary/40">
<RuntimeForm
initial={creating}
submitLabel="Add runtime"
onCancel={() => setCreating(null)}
onSubmit={async (value) => {
const ok = await send("/api/runtimes", "POST", { ...value, preset: creating.preset });
if (ok) {
toast.success(`Runtime "${value.name}" added`);
setCreating(null);
router.refresh();
}
return ok;
}}
/>
</div>
)}
{runtimes.length === 0 && !creating && <p className="text-sm text-muted-foreground">No runtimes yet. Add one from a preset.</p>}
{runtimes.map((r) =>
editing === r.id ? (
<div key={r.id} className="rounded-lg p-4 ring-1 ring-primary/40">
<RuntimeForm
initial={toInput(r)}
submitLabel="Save"
onCancel={() => setEditing(null)}
onSubmit={async (value) => {
const ok = await send(`/api/runtimes/${r.id}`, "PUT", value);
if (ok) {
setEditing(null);
router.refresh();
}
return ok;
}}
/>
</div>
) : (
<RuntimeRow
key={r.id}
runtime={r}
dockerReady={!!docker?.connected}
onEdit={() => setEditing(r.id)}
onDuplicate={() => setCreating({ ...toInput(r), name: `${r.name} (copy)` })}
/>
),
)}
</CardContent>
</Card>
</div>
);
}
function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; workerOnline: boolean }) {
return (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ServerIcon className="size-4 text-muted-foreground" />
Docker host
</CardTitle>
<CardDescription>
{!workerOnline
? "The worker is offline; these facts may be outdated."
: !docker
? "Not connected. Runtimes need the worker to reach Docker through the socket proxy (DOCKER_HOST)."
: docker.connected
? `Docker ${docker.serverVersion} on ${docker.os} (${docker.architecture})`
: `Can't reach Docker: ${docker.error}`}
</CardDescription>
</CardHeader>
{docker && (
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">CPU</dt>
<dd>
{docker.cpuModel ?? "unknown"}
{docker.cpus != null && <span className="text-muted-foreground"> · {docker.cpus} threads</span>}
</dd>
<dt className="text-muted-foreground">Features</dt>
<dd className="flex flex-wrap gap-1">
{docker.cpuFeatures.length === 0 ? (
<span className="text-muted-foreground">unknown</span>
) : (
docker.cpuFeatures.map((f) => (
<span
key={f}
className={cn(
"rounded border px-1.5 text-xs",
f.startsWith("avx512") || f.startsWith("amx") ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground",
)}
>
{FEATURE_LABEL[f] ?? f}
</span>
))
)}
</dd>
<dt className="text-muted-foreground">Memory</dt>
<dd>{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}</dd>
<dt className="text-muted-foreground">Network</dt>
<dd className={cn("font-mono text-xs", !docker.network && "text-amber-700 dark:text-amber-300")}>
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
</dd>
<dt className="text-muted-foreground">Models</dt>
<dd className={cn("font-mono text-xs break-all", !docker.modelsSource && "text-amber-700 dark:text-amber-300")}>
{docker.modelsSource ? `${docker.modelsSource.source} (${docker.modelsSource.type}, mounted read-only)` : "not detected (set KANAME_MODELS_SOURCE)"}
</dd>
<dt className="text-muted-foreground">Checked</dt>
<dd>
<LocalTime value={docker.checkedAt} />
</dd>
</dl>
</CardContent>
)}
</Card>
);
}
function ImageState({ r }: { r: Runtime }) {
const requested = !!r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt);
if (r.imageState === "pulling" || requested) {
const p = r.pullProgress;
return (
<div className="flex min-w-48 flex-col gap-1">
<span className="text-xs text-muted-foreground">
{p ? `${p.status} · ${formatBytes(p.doneBytes)}${p.totalBytes ? ` / ${formatBytes(p.totalBytes)}` : ""}` : "Pull queued…"}
</span>
<Progress value={p && p.totalBytes ? percent(p.doneBytes, p.totalBytes) : 0} />
</div>
);
}
if (r.imageState === "present") {
return (
<span className="text-xs text-emerald-700 dark:text-emerald-400">
Pulled · {r.imageSize != null ? formatBytes(r.imageSize) : "?"}
{r.imageCreated && (
<span className="text-muted-foreground">
{" "}
· built <LocalTime value={r.imageCreated} />
</span>
)}
</span>
);
}
if (r.imageState === "failed") return <span className="text-xs break-all text-destructive">Pull failed: {r.pullError}</span>;
if (r.imageState === "missing") return <span className="text-xs text-muted-foreground">Not pulled yet</span>;
return <span className="text-xs text-muted-foreground">Not checked yet</span>;
}
function RuntimeRow({
runtime: r,
dockerReady,
onEdit,
onDuplicate,
}: {
runtime: Runtime;
dockerReady: boolean;
onEdit: () => void;
onDuplicate: () => void;
}) {
const router = useRouter();
const pulling = r.imageState === "pulling";
const envCount = Object.keys(r.env).length;
return (
<div className="flex flex-col gap-3 rounded-lg px-4 py-3 ring-1 ring-foreground/10">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{r.name}</span>
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">{r.engine === "vllm" ? "vLLM" : "llama.cpp"}</span>
{r.numaTuning && <span className="rounded-md border border-amber-500/30 px-1.5 text-xs text-amber-700 dark:text-amber-300">NUMA tuning</span>}
</div>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
{r.description && <p className="text-xs text-muted-foreground">{r.description}</p>}
</div>
<div className="flex items-center gap-1">
<Button
size="sm"
variant={r.imageState === "present" ? "ghost" : "outline"}
disabled={!dockerReady || pulling}
title={!dockerReady ? "Docker isn't connected" : r.imageState === "present" ? "Pull again to update the tag" : undefined}
onClick={async () => {
if (await send(`/api/runtimes/${r.id}/pull`, "POST")) router.refresh();
}}
>
<DownloadCloudIcon />
{r.imageState === "present" ? "Update" : "Pull"}
</Button>
<Button size="icon-sm" variant="ghost" onClick={onEdit} aria-label={`Edit ${r.name}`}>
<PencilIcon />
</Button>
<Button size="icon-sm" variant="ghost" onClick={onDuplicate} aria-label={`Duplicate ${r.name}`}>
<CopyIcon />
</Button>
<AlertDialog>
<AlertDialogTrigger render={<Button size="icon-sm" variant="ghost" aria-label={`Delete ${r.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete runtime &ldquo;{r.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>The pulled image stays in Docker; remove it there if you need the space.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1 text-xs text-muted-foreground">
<ImageState r={r} />
<span>
{envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
{r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
{r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
{r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
</span>
</div>
</div>
);
}
+26
View File
@@ -0,0 +1,26 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
export function SettingsNav({ sections }: { sections: { href: string; label: string; icon: React.ReactNode }[] }) {
const pathname = usePathname();
return (
<nav className="flex gap-1 rounded-xl bg-card p-2 ring-1 ring-foreground/10 md:flex-col">
{sections.map((s) => (
<Link
key={s.href}
href={s.href}
className={cn(
"flex items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",
pathname === s.href ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:text-foreground",
)}
>
{s.icon}
{s.label}
</Link>
))}
</nav>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { listTags } from "@/lib/tags";
import { TagSettings } from "./tag-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Tags · Settings" };
export default async function TagSettingsPage() {
return <TagSettings tags={await listTags()} />;
}
@@ -0,0 +1,181 @@
"use client";
import { PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { TagBadge } from "@/components/tag-badge";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { autoTagColor, isLabelColor, type LabelColor } from "@/lib/colors";
import type { Tag } from "@/lib/tags";
import { ColorPicker } from "../labels/color-picker";
/** Create, rename, recolor or delete user tags. Changes save immediately. */
export function TagSettings({ tags }: { tags: (Tag & { count: number })[] }) {
return (
<Card>
<CardHeader>
<CardTitle>Tags</CardTitle>
<CardDescription>
Your own tags, to attach on a model page or when adding a model. Tags without a color get an automatic one.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewTagRow />
{tags.length === 0 ? (
<p className="text-sm text-muted-foreground">No tags yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tags.map((t) => (
<TagRow key={t.id} tag={t} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewTagRow() {
const router = useRouter();
const [name, setName] = useState("");
const [color, setColor] = useState<LabelColor | null>(null);
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/tags", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, color }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not create tag (${res.status})`);
return;
}
toast.success(`Tag "${json.name}" created`);
setName("");
setColor(null);
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form
onSubmit={create}
className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[8rem_minmax(0,1fr)_8rem_6rem_2rem]"
>
{name.trim() ? (
<TagBadge name={name.trim()} color={color} className="justify-self-start" />
) : (
<span className="text-xs text-muted-foreground">New tag</span>
)}
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. roleplay"
aria-label="New tag name"
className="h-8"
/>
<ColorPicker value={color} onChange={setColor} allowAuto autoColor={autoTagColor(name.trim())} />
<Button type="submit" size="sm" disabled={busy || !name.trim()} className="sm:col-span-2">
<PlusIcon />
Add
</Button>
</form>
);
}
function TagRow({ tag }: { tag: Tag & { count: number } }) {
const router = useRouter();
const [name, setName] = useState(tag.name);
const [busy, setBusy] = useState(false);
async function patch(body: { name?: string; color?: string | null }) {
setBusy(true);
try {
const res = await fetch(`/api/tags/${tag.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
setName(tag.name);
return;
}
router.refresh();
} finally {
setBusy(false);
}
}
async function remove() {
const res = await fetch(`/api/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`Tag "${tag.name}" deleted`);
router.refresh();
}
const color = isLabelColor(tag.color) ? tag.color : null;
return (
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[8rem_minmax(0,1fr)_8rem_6rem_2rem]">
<TagBadge name={name || tag.name} color={tag.color} className="justify-self-start" />
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) => setName(e.target.value)}
onBlur={() => name.trim() && name !== tag.name && patch({ name })}
onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
aria-label={`Rename tag ${tag.name}`}
className="h-8"
/>
<ColorPicker value={color} onChange={(c) => patch({ color: c })} allowAuto autoColor={autoTagColor(tag.name)} />
<span className="text-xs text-muted-foreground tabular-nums">
{tag.count} model{tag.count === 1 ? "" : "s"}
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete tag ${tag.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete tag &ldquo;{tag.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>
It is removed from {tag.count} model{tag.count === 1 ? "" : "s"}. The models themselves are not touched.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** The key's value ("show key" in Settings). */
export const GET = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Remove a key; running deployments keep accepting it until they restart. */
export const DELETE = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteApiKey(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** Keys without their values (only the last characters). */
export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
/** Add a key (generated when `key` is missing); the response carries the full key once. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,45 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { apiKeyValues } from "@/lib/api-keys";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
const Body = z.object({
messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100),
maxTokens: z.number().int().min(1).max(8192).default(256),
});
/**
* Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and
* streams the server-sent events back unchanged.
*/
export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (req, { params }) => {
try {
const d = await getDeployment((await params).id);
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
// Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest.
const [key] = d.options.requireApiKey ? await apiKeyValues() : [];
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`);
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys.");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listDeploymentLogs } from "@/lib/deployments";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/deployments/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listDeploymentLogs((await params).id, after));
});
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentBody, DeploymentError, getDeployment, requestDelete, updateDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
const d = await getDeployment((await params).id);
return d ? NextResponse.json(d) : apiError(404, "not_found", "Deployment not found.");
});
export const PUT = withAuth<RouteContext<"/api/deployments/[id]">>(async (req, { params }) => {
try {
await updateDeployment((await params).id, DeploymentBody.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Stop the container (if running) and delete the deployment. */
export const DELETE = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
try {
await requestDelete((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/start">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "running");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/stop">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "stopped");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createDeployment, DeploymentBody, DeploymentError, listDeployments } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listDeployments()));
/** Create a deployment; `start: true` starts it right away. */
export const POST = withAuth(async (req) => {
try {
const body = DeploymentBody.extend({ start: z.boolean().default(true) }).parse(await req.json());
return NextResponse.json(await createDeployment(body, body.start), { status: 201 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+9
View File
@@ -0,0 +1,9 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { requestFolderScan } from "@/lib/local-folders";
/** Ask the worker to rescan the models folder for importable folders. */
export const POST = withAuth(async () => {
await requestFolderScan();
return new NextResponse(null, { status: 202 });
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { addFilesToModel, ModelError } from "@/lib/models";
const Body = z.object({ add: z.array(z.string().min(1).max(1024)).min(1).max(10_000) });
/** Add files to a model's selection and queue their download. */
export const POST = withAuth<RouteContext<"/api/models/[id]/files">>(async (req, { params }) => {
const { id } = await params;
try {
const { add } = Body.parse(await req.json());
return NextResponse.json(await addFilesToModel(id, add), { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { checkHub, getCheckedModel } from "@/lib/hub/availability";
/** Check right now whether the repo and pinned commit are still on the Hub. */
export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (_req, { params }) => {
const { id } = await params;
const model = await getCheckedModel(id);
if (!model) return apiError(404, "not_found", "Model not found.");
return NextResponse.json(await checkHub(model));
});
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError, queueDownload } from "@/lib/jobs";
/** Download again what's missing or broken (the worker deletes broken files first). */
export const POST = withAuth<RouteContext<"/api/models/[id]/repair">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await queueDownload(id, "repair"), { status: 201 });
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+6 -4
View File
@@ -1,13 +1,15 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { ModelError, removeModel } from "@/lib/models";
import { deleteModel, ModelError } from "@/lib/models";
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (_req, { params }) => {
/** Delete a model; `?files=1` also deletes its files from disk (queued for the worker). */
export const DELETE = withAuth<RouteContext<"/api/models/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
await removeModel(id);
return new NextResponse(null, { status: 204 });
const deleteFiles = new URL(req.url).searchParams.get("files") === "1";
const { queued } = await deleteModel(id, { deleteFiles });
return queued ? NextResponse.json({ queued }, { status: 202 }) : new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
throw err;
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { applyUpdate, ModelError } from "@/lib/models";
/** Update to the newer commit found by the last Hub check (deliberate, never automatic). */
export const POST = withAuth<RouteContext<"/api/models/[id]/update">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await applyUpdate(id), { status: 201 });
} catch (err) {
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError, queueVerify } from "@/lib/jobs";
/** Queue a verify (`?deep=1`: hash every file) of the model's selected files. */
export const POST = withAuth<RouteContext<"/api/models/[id]/verify">>(async (req, { params }) => {
const { id } = await params;
try {
const deep = new URL(req.url).searchParams.get("deep") === "1";
return NextResponse.json(await queueVerify(id, deep), { status: 201 });
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+4 -1
View File
@@ -15,6 +15,8 @@ const Body = z.object({
exclude: z.array(z.string().min(1).max(1024)).max(1_000),
download: z.boolean().default(true),
tags: z.array(z.string()).max(50).default([]),
/** Import an existing folder from the models folder (as found by the worker's scan). */
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. */
@@ -27,9 +29,10 @@ export const POST = withAuth(async (req) => {
revision: body.revision,
sha: body.sha,
rule: { include: body.include, exclude: body.exclude },
localPath: body.localPath,
});
for (const tag of body.tags) await addTag(id, tag);
const job = body.download ? await queueDownload(id) : null;
const job = body.download ? await queueDownload(id, body.localPath ? "import" : "initial") : null;
return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 });
} catch (err) {
if (err instanceof ModelError || err instanceof TagError) return apiError(err.status, err.code, err.message);
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { requestPull, RuntimeError } from "@/lib/runtimes";
/** Ask the worker to pull the image (again; updates moving tags like :server). */
export const POST = withAuth<RouteContext<"/api/runtimes/[id]/pull">>(async (_req, { params }) => {
const { id } = await params;
try {
await requestPull(id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteRuntime, RuntimeBody, RuntimeError, updateRuntime } from "@/lib/runtimes";
export const PUT = withAuth<RouteContext<"/api/runtimes/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await updateRuntime(id, RuntimeBody.parse(await req.json())));
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
export const DELETE = withAuth<RouteContext<"/api/runtimes/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteRuntime(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createRuntime, getDockerInfo, listRuntimes, RuntimeBody, RuntimeError } from "@/lib/runtimes";
export const dynamic = "force-dynamic";
/** Runtimes plus the Docker facts the worker reported. */
export const GET = withAuth(async () => NextResponse.json({ runtimes: await listRuntimes(), docker: await getDockerInfo() }));
export const POST = withAuth(async (req) => {
try {
const body = RuntimeBody.extend({ preset: z.string().optional() }).parse(await req.json());
return NextResponse.json(await createRuntime(body), { status: 201 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+22
View File
@@ -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 { getRecommendedRoles, saveRecommendedRoles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Download settings: which file kinds are picked along with model weights. */
export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() }));
const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) });
export const PUT = withAuth(async (req) => {
try {
const { recommendedRoles } = Body.parse(await req.json());
return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) });
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getFileRoleStyles, saveFileRoleStyles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Label text and color per file role (defaults merged with saved overrides). */
export const GET = withAuth(async () => NextResponse.json({ fileRoles: await getFileRoleStyles() }));
const Body = z.object({
fileRoles: z.record(z.string(), z.object({ label: z.string().optional(), color: z.string().optional() })),
});
/** Replace the saved overrides; send the full set (values equal to the default are dropped). */
export const PUT = withAuth(async (req) => {
try {
const { fileRoles } = Body.parse(await req.json());
return NextResponse.json({ fileRoles: await saveFileRoleStyles(fileRoles) });
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteTag, TagError, updateTag } from "@/lib/tags";
const Body = z.object({ name: z.string().optional(), color: z.string().nullable().optional() });
/** Rename a tag and/or change its color (null = automatic). */
export const PATCH = withAuth<RouteContext<"/api/tags/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await updateTag(id, Body.parse(await req.json())));
} catch (err) {
if (err instanceof TagError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Delete a tag everywhere. */
export const DELETE = withAuth<RouteContext<"/api/tags/[id]">>(async (_req, { params }) => {
const { id } = await params;
await deleteTag(id);
return new NextResponse(null, { status: 204 });
});
+15 -1
View File
@@ -1,8 +1,22 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { listTags } from "@/lib/tags";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createTag, listTags, TagError } from "@/lib/tags";
export const dynamic = "force-dynamic";
/** All user tags with usage counts. */
export const GET = withAuth(async () => NextResponse.json(await listTags()));
const Body = z.object({ name: z.string(), color: z.string().nullable().optional() });
/** Create a tag that isn't on any model yet. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createTag(Body.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof TagError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+8
View File
@@ -1,6 +1,7 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@plugin "@tailwindcss/typography";
@custom-variant dark (&:is(.dark *));
@@ -126,4 +127,11 @@
html {
@apply font-sans;
}
/* Native controls (select popups, scrollbars, date pickers) follow the theme. */
.dark {
color-scheme: dark;
}
option {
@apply bg-popover text-popover-foreground;
}
}
+11
View File
@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#7c5cff"/>
<stop offset="1" stop-color="#14b8a6"/>
</linearGradient>
</defs>
<rect width="64" height="64" rx="14" fill="url(#g)"/>
<text x="32" y="45" text-anchor="middle" font-size="38" font-weight="700" fill="#fff"
font-family="'Yu Gothic','Meiryo','Noto Sans JP','Hiragino Sans',sans-serif">要</text>
</svg>

After

Width:  |  Height:  |  Size: 497 B

+43
View File
@@ -0,0 +1,43 @@
"use client";
import { LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
const LINKS = [
{
href: "/",
label: "Library",
icon: LibraryIcon,
active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/deployments"),
},
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
/** Main navigation; model and job pages count as part of the library. */
export function AppNav() {
const pathname = usePathname();
return (
<nav className="flex items-center gap-1 text-sm">
{LINKS.map((l) => {
const active = l.active(pathname);
return (
<Link
key={l.href}
href={l.href}
aria-current={active ? "page" : undefined}
className={cn(
"flex items-center gap-1.5 rounded-md px-2.5 py-1.5 transition-colors",
active ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:bg-muted/60 hover:text-foreground",
)}
>
<l.icon className="size-4" />
<span className="hidden sm:inline">{l.label}</span>
</Link>
);
})}
</nav>
);
}
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ArgRow } from "@/lib/extra-args";
const GENERIC = { flag: "--flag", value: "value (optional)" };
/** Extra command-line arguments as flag/value rows (controlled). `placeholder` is the first row's example. */
export function ArgsEditor({
rows,
onChange,
placeholder = GENERIC,
addLabel = "Add argument",
}: {
rows: ArgRow[];
onChange: (rows: ArgRow[]) => void;
placeholder?: { flag: string; value: string };
addLabel?: string;
}) {
const set = (i: number, patch: Partial<ArgRow>) => onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const single = (s: string) => s.replace(/[\r\n]/g, "");
return (
<div className="flex flex-col gap-1.5">
{rows.map((r, i) => (
<div key={i} className="flex items-center gap-1.5">
<Input
value={r.flag}
onChange={(e) => set(i, { flag: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).flag}
spellCheck={false}
aria-label={`Argument ${i + 1} flag`}
className="font-mono text-xs md:text-xs"
/>
<Input
value={r.value}
onChange={(e) => set(i, { value: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).value}
spellCheck={false}
aria-label={`Argument ${i + 1} value`}
className="font-mono text-xs md:text-xs"
/>
<Button type="button" variant="ghost" size="icon-sm" aria-label={`Remove argument ${i + 1}`} onClick={() => onChange(rows.filter((_, j) => j !== i))}>
<XIcon />
</Button>
</div>
))}
<Button type="button" variant="outline" size="sm" className="self-start" onClick={() => onChange([...rows, { flag: "", value: "" }])}>
<PlusIcon />
{addLabel}
</Button>
</div>
);
}
+24
View File
@@ -0,0 +1,24 @@
"use client";
import { CheckIcon, CopyIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
export function CopyButton({ value, label = "Copy" }: { value: string; label?: string }) {
const [copied, setCopied] = useState(false);
return (
<Button
variant="ghost"
size="icon-xs"
aria-label={label}
title={label}
onClick={async () => {
await navigator.clipboard.writeText(value);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
}}
>
{copied ? <CheckIcon /> : <CopyIcon />}
</Button>
);
}
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more