Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
930126c5eb | ||
|
|
b68b4a2b23 | ||
|
|
76683ffd7b | ||
|
|
7864a492c9 |
No files matched your search
+1
-1
@@ -37,7 +37,7 @@ KANAME_VERSION=
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MAX_CONCURRENT_DOWNLOADS=1
|
||||
# How often the worker checks every model on the Hub (still there? later: newer commits); 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.
|
||||
|
||||
@@ -6,6 +6,55 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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,
|
||||
|
||||
@@ -76,8 +76,15 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
"Found in the models folder"; **Import** matches them with the Hub repo and verifies the files
|
||||
instead of downloading them again. See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models).
|
||||
- **Deleted on the Hub:** if a repo (or its pinned commit) disappears from Hugging Face, the model
|
||||
is flagged and your local copy is kept.
|
||||
- **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
|
||||
|
||||
@@ -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:
|
||||
@@ -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
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `jobs` ADD `result` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `update_diff` text;
|
||||
@@ -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;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,20 @@
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.7.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
"@libsql/client": "^0.18.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.5.0",
|
||||
"version": "0.7.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
|
||||
@@ -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's files in <code className="font-mono">{localPath}</code>. Files you put there yourself are
|
||||
kept. Unchecked, the folder stays and shows up under “Found in the models folder”.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove} disabled={pending}>
|
||||
{mayHaveFiles && deleteFiles ? "Delete with files" : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { cancelJob, startDownload } from "@/components/job-actions";
|
||||
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 download state, actions and (while running) per-file progress. */
|
||||
/** Sidebar card: current job with progress, the last verify result, and the model's actions. */
|
||||
export function DownloadCard({
|
||||
modelId,
|
||||
status,
|
||||
@@ -27,11 +30,18 @@ export function DownloadCard({
|
||||
}) {
|
||||
const { snapshot } = useLive({ model: modelId });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const latest = snapshot?.jobs[0];
|
||||
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<void>) {
|
||||
async function run(fn: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
@@ -40,24 +50,40 @@ export function DownloadCard({
|
||||
}
|
||||
}
|
||||
|
||||
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 download slot." : "Queued, but the worker is offline.";
|
||||
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.";
|
||||
else if (hubMissing) hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
|
||||
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" />
|
||||
Download
|
||||
{open ? jobLabel(open) : "Download"}
|
||||
</h3>
|
||||
{latest && <JobStateBadge job={latest} />}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
|
||||
{latest && !(latest.state === "completed" && status === "ready") && <JobProgress job={latest} compact />}
|
||||
{showProgress && <JobProgress job={latest} compact />}
|
||||
|
||||
{latest?.state === "failed" && latest.errorMessage && (
|
||||
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
|
||||
@@ -82,30 +108,58 @@ export function DownloadCard({
|
||||
</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))}
|
||||
>
|
||||
<Button variant="destructive" size="sm" disabled={busy || open.cancelRequested} onClick={() => run(() => cancelJob(open.id))}>
|
||||
{open.cancelRequested ? "Cancelling…" : "Cancel"}
|
||||
</Button>
|
||||
) : (
|
||||
status !== "ready" &&
|
||||
!hubMissing &&
|
||||
snapshot && (
|
||||
<Button size="sm" disabled={busy} onClick={() => run(() => startDownload(modelId))}>
|
||||
{latest ? "Download again" : "Download"}
|
||||
</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 && (
|
||||
<Link
|
||||
href={`/jobs/${latest.id}`}
|
||||
className="inline-flex h-7 items-center rounded-md px-2.5 text-[0.8rem] hover:bg-muted"
|
||||
>
|
||||
{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>
|
||||
)}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Re-check right now whether the repo and pinned commit are still on the Hub. */
|
||||
/** 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);
|
||||
@@ -18,7 +18,8 @@ export function HubCheckButton({ modelId, label = "Check now" }: { modelId: stri
|
||||
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") toast.success("Still available on Hugging Face");
|
||||
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"}`);
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 }) {
|
||||
@@ -35,8 +36,7 @@ export function JobsTab({ modelId }: { modelId: string }) {
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{j.kind}
|
||||
{j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""}
|
||||
{jobLabel(j)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<JobStateBadge job={j} />
|
||||
|
||||
@@ -25,6 +25,7 @@ import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
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";
|
||||
@@ -35,8 +36,9 @@ import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCard } from "./model-card";
|
||||
import { RemoveModelButton } from "./remove-model-button";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -95,12 +97,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const hubTags = model.hubTags ?? [];
|
||||
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
|
||||
|
||||
const [tags, related, card, worker] = await Promise.all([
|
||||
const [tags, related, card, worker, recentJobs] = 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),
|
||||
]);
|
||||
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);
|
||||
@@ -130,8 +137,18 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<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">
|
||||
{model.status === "pending" && <RemoveModelButton id={model.id} />}
|
||||
<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>
|
||||
@@ -190,6 +207,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</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">
|
||||
@@ -305,9 +326,11 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
)}
|
||||
<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")}>
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
|
||||
{model.hubState === "available"
|
||||
? "Available"
|
||||
? update
|
||||
? "Update available"
|
||||
: "Up to date"
|
||||
: model.hubState === "repo_missing"
|
||||
? "Repo deleted"
|
||||
: model.hubState === "commit_missing"
|
||||
@@ -316,9 +339,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</span>
|
||||
{model.lastCheckedAt && (
|
||||
<span className="text-xs text-muted-foreground" title={model.lastCheckError ?? undefined}>
|
||||
{model.lastCheckError ? "check failed" : "checked"} <LocalTime value={model.lastCheckedAt} />
|
||||
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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,7 +41,7 @@ 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} ·{" "}
|
||||
{jobLabel(job)} ·{" "}
|
||||
<Link href={`/${job.repoId}`} className="hover:underline">
|
||||
{job.repoId}
|
||||
</Link>
|
||||
|
||||
@@ -56,7 +56,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 : null,
|
||||
hubStatus:
|
||||
r.hubState && r.hubState !== "available"
|
||||
? HUB_STATE_LABEL[r.hubState].label
|
||||
: r.updateAvailable
|
||||
? "update available"
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -223,6 +228,11 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
<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>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { BoxesIcon, DownloadIcon, 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" /> },
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
|
||||
|
||||
@@ -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,187 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
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 { 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 [argsText, setArgsText] = useState((initial.extraArgs ?? []).join("\n"));
|
||||
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: argsText.split("\n"),
|
||||
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="grid gap-4 sm:grid-cols-2">
|
||||
<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 htmlFor="rt-args">Extra arguments</Label>
|
||||
<textarea
|
||||
id="rt-args"
|
||||
value={argsText}
|
||||
onChange={(e) => setArgsText(e.target.value)}
|
||||
spellCheck={false}
|
||||
className={textareaClass}
|
||||
placeholder={"--dtype=bfloat16"}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">One per line, appended to the generated command.</p>
|
||||
</div>
|
||||
</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'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 “{r.name}”?</AlertDialogTitle>
|
||||
<AlertDialogDescription>The pulled image stays in Docker; remove it there if you need the space.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1 text-xs text-muted-foreground">
|
||||
<ImageState r={r} />
|
||||
<span>
|
||||
{envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
|
||||
{r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
|
||||
{r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
|
||||
{r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { checkHubAvailability, getCheckedModel } from "@/lib/hub/availability";
|
||||
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 checkHubAvailability(model));
|
||||
return NextResponse.json(await checkHub(model));
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -17,3 +17,17 @@ export async function startDownload(modelId: string) {
|
||||
export async function cancelJob(jobId: string) {
|
||||
if (await post(`/api/jobs/${jobId}/cancel`)) toast.info("Cancelling…");
|
||||
}
|
||||
|
||||
export async function startVerify(modelId: string, deep: boolean) {
|
||||
if (await post(`/api/models/${modelId}/verify${deep ? "?deep=1" : ""}`)) toast.success(deep ? "Deep verify queued" : "Verify queued");
|
||||
}
|
||||
|
||||
export async function startRepair(modelId: string) {
|
||||
if (await post(`/api/models/${modelId}/repair`)) toast.success("Repair queued");
|
||||
}
|
||||
|
||||
export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
const ok = await post(`/api/models/${modelId}/update`);
|
||||
if (ok) toast.success("Update queued");
|
||||
return ok;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { BoxesIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useTransition } from "react";
|
||||
@@ -67,6 +67,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
|
||||
<TagsIcon />
|
||||
Tags
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem render={<Link href="/settings/runtimes" />}>
|
||||
<BoxesIcon />
|
||||
Runtimes
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { CircleAlertIcon, CircleCheckIcon } from "lucide-react";
|
||||
import type { JobResult } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function PathList({ title, paths, tone }: { title: string; paths: string[]; tone: "bad" | "muted" }) {
|
||||
if (paths.length === 0) return null;
|
||||
return (
|
||||
<details className="text-xs">
|
||||
<summary className={cn("cursor-pointer select-none", tone === "bad" ? "text-destructive" : "text-muted-foreground")}>
|
||||
{title} ({paths.length})
|
||||
</summary>
|
||||
<ul className="mt-1 ml-3 flex flex-col gap-0.5 font-mono break-all text-muted-foreground">
|
||||
{paths.slice(0, 50).map((p) => (
|
||||
<li key={p}>{p}</li>
|
||||
))}
|
||||
{paths.length > 50 && <li>… {paths.length - 50} more</li>}
|
||||
</ul>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
/** Outcome of a (deep) verify: problems per kind, plus extra files in the folder. */
|
||||
export function VerifyResult({ result, deep }: { result: JobResult; deep: boolean }) {
|
||||
const missing = result.missing ?? [];
|
||||
const sizeMismatch = result.sizeMismatch ?? [];
|
||||
const hashMismatch = result.hashMismatch ?? [];
|
||||
const extra = result.extra ?? [];
|
||||
const problems = missing.length + sizeMismatch.length + hashMismatch.length;
|
||||
const extraBytes = extra.reduce((s, e) => s + e.size, 0);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className={cn("flex items-center gap-1.5 text-xs", problems > 0 ? "text-destructive" : "text-emerald-700 dark:text-emerald-400")}>
|
||||
{problems > 0 ? <CircleAlertIcon className="size-3.5" /> : <CircleCheckIcon className="size-3.5" />}
|
||||
{problems > 0
|
||||
? `${problems} of ${result.checked ?? 0} files need repair`
|
||||
: `All ${result.checked ?? 0} files OK${deep ? ", hashes match the Hub" : ""}`}
|
||||
</p>
|
||||
<PathList title="Missing" paths={missing} tone="bad" />
|
||||
<PathList title="Wrong size" paths={sizeMismatch} tone="bad" />
|
||||
<PathList title={deep ? "Hash mismatch" : "Different version (hf metadata)"} paths={hashMismatch} tone="bad" />
|
||||
{extra.length > 0 && (
|
||||
<PathList
|
||||
title={`Extra files in the folder, ${formatBytes(extraBytes)}`}
|
||||
paths={extra.map((e) => (e.inRepo ? `${e.path} (repo file, not selected)` : e.path))}
|
||||
tone="muted"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+91
-1
@@ -50,6 +50,30 @@ export type ModelStatus = (typeof MODEL_STATUSES)[number];
|
||||
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
|
||||
export type HubState = (typeof HUB_STATES)[number];
|
||||
|
||||
export type UpdateDiffFile = { path: string; size: number; oldSize?: number };
|
||||
export type UpdateDiff = {
|
||||
/** Commit the diff was computed against (the tracked revision's head on the Hub). */
|
||||
sha: string;
|
||||
changed: UpdateDiffFile[];
|
||||
added: UpdateDiffFile[];
|
||||
removed: UpdateDiffFile[];
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
/** Outcome of a verify job, or extra instructions for a job (`removePaths` after an update). */
|
||||
export type JobResult = {
|
||||
checked?: number;
|
||||
missing?: string[];
|
||||
sizeMismatch?: string[];
|
||||
hashMismatch?: string[];
|
||||
/** Files in the model folder that aren't selected repo files. */
|
||||
extra?: { path: string; size: number; inRepo: boolean }[];
|
||||
/** Update jobs: files of the old revision to delete once the download succeeded. */
|
||||
removePaths?: string[];
|
||||
/** Delete jobs: files that were kept because they don't belong to the repo. */
|
||||
kept?: string[];
|
||||
};
|
||||
|
||||
export const models = sqliteTable(
|
||||
"models",
|
||||
{
|
||||
@@ -81,6 +105,8 @@ export const models = sqliteTable(
|
||||
hubState: text("hub_state", { enum: HUB_STATES }),
|
||||
/** When the repo or pinned commit was first seen missing; cleared when it's back. */
|
||||
hubMissingSince: ts("hub_missing_since"),
|
||||
/** What updating to `remoteSha` would change in the selection; null when up to date. */
|
||||
updateDiff: text("update_diff", { mode: "json" }).$type<UpdateDiff>(),
|
||||
lastVerifiedAt: ts("last_verified_at"),
|
||||
downloadedAt: ts("downloaded_at"),
|
||||
// Hub metadata (for search/filters), refreshed by the worker. Null until fetched.
|
||||
@@ -190,7 +216,7 @@ export const modelFiles = sqliteTable(
|
||||
// Jobs (executed by the worker)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const;
|
||||
@@ -239,6 +265,7 @@ export const jobs = sqliteTable(
|
||||
exitCode: integer("exit_code"),
|
||||
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
|
||||
errorMessage: text("error_message"),
|
||||
result: text("result", { mode: "json" }).$type<JobResult>(),
|
||||
/** Set by the web app; the worker picks it up and stops the job. */
|
||||
cancelRequestedAt: ts("cancel_requested_at"),
|
||||
startedAt: ts("started_at"),
|
||||
@@ -315,6 +342,69 @@ export const workerState = sqliteTable("worker_state", {
|
||||
heartbeatAt: ts("heartbeat_at").notNull(),
|
||||
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
|
||||
scanRequestedAt: ts("scan_requested_at"),
|
||||
/** Docker connection and host facts, reported by the worker (null: no DOCKER_HOST). */
|
||||
docker: text("docker", { mode: "json" }).$type<DockerHostInfo>(),
|
||||
});
|
||||
|
||||
export type DockerHostInfo = {
|
||||
connected: boolean;
|
||||
error: string | null;
|
||||
serverVersion: string | null;
|
||||
os: string | null;
|
||||
architecture: string | null;
|
||||
cpus: number | null;
|
||||
memoryBytes: number | null;
|
||||
cpuModel: string | null;
|
||||
/** Relevant CPU features (avx2, avx512f, avx512_bf16, amx_bf16, …). */
|
||||
cpuFeatures: string[];
|
||||
/** Docker network inference containers join, so the worker can reach them. */
|
||||
network: string | null;
|
||||
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
|
||||
modelsSource: { type: "bind" | "volume"; source: string } | null;
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** How Kaname builds the command line and talks to the server. */
|
||||
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
|
||||
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
|
||||
|
||||
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
|
||||
export type ImageState = (typeof IMAGE_STATES)[number];
|
||||
|
||||
export const runtimes = sqliteTable("runtimes", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
|
||||
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
|
||||
image: text("image").notNull(),
|
||||
description: text("description"),
|
||||
/** Environment variables for the container. */
|
||||
env: text("env", { mode: "json" }).$type<Record<string, string>>().notNull().default(sql`'{}'`),
|
||||
/** Appended to the generated command line (fork-specific flags). */
|
||||
extraArgs: text("extra_args", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
|
||||
/** Host devices to pass through, e.g. "/dev/dri" (later: Intel GPUs). */
|
||||
devices: text("devices", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
|
||||
shmSizeMb: integer("shm_size_mb"),
|
||||
/** vLLM's NUMA optimizations: adds CAP_SYS_NICE and seccomp=unconfined. Off unless enabled. */
|
||||
numaTuning: integer("numa_tuning", { mode: "boolean" }).notNull().default(false),
|
||||
/** Preset this runtime was created from, if any. */
|
||||
preset: text("preset"),
|
||||
imageState: text("image_state", { enum: IMAGE_STATES }).notNull().default("unknown"),
|
||||
imageId: text("image_id"),
|
||||
imageSize: integer("image_size"),
|
||||
imageCreated: text("image_created"),
|
||||
/** Set by "Pull"; the worker pulls when this is newer than the last pull. */
|
||||
pullRequestedAt: ts("pull_requested_at"),
|
||||
pullStartedAt: ts("pull_started_at"),
|
||||
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
|
||||
pullError: text("pull_error"),
|
||||
imageCheckedAt: ts("image_checked_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,6 +22,14 @@ const coreSchema = z.object({
|
||||
),
|
||||
/** hf CLI home (token cache, Xet logs/cache). Not the model storage. */
|
||||
HF_HOME: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/**
|
||||
* Docker API for runtimes (worker only), e.g. tcp://docker-proxy:2375 or unix:///var/run/docker.sock.
|
||||
* Unset: runtimes are disabled.
|
||||
*/
|
||||
DOCKER_HOST: z.preprocess(emptyToUndefined, z.string().regex(/^(tcp|unix):\/\//, "must start with tcp:// or unix://").optional()),
|
||||
/** Override the auto-detected Docker network / models source (needed when the worker isn't a container). */
|
||||
KANAME_DOCKER_NETWORK: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
KANAME_MODELS_SOURCE: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
});
|
||||
|
||||
const authSchema = z.object({
|
||||
|
||||
+90
-24
@@ -1,9 +1,28 @@
|
||||
import { asc, eq, isNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models, type HubState } from "@/lib/db/schema";
|
||||
import { getRepoInfo, HubError } from "./client";
|
||||
// Hub checks per model: is the repo (and the pinned commit) still there, and is there a newer
|
||||
// commit on the tracked revision? Run periodically by the worker and on "Check now". Results are
|
||||
// stored on the model; nothing local is ever changed by a check.
|
||||
|
||||
type CheckedModel = Pick<typeof models.$inferSelect, "id" | "repoId" | "pinnedSha" | "hubMissingSince">;
|
||||
import { and, asc, eq, isNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema";
|
||||
import { computeUpdateDiff } from "@/lib/update-diff";
|
||||
import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client";
|
||||
|
||||
type CheckedModel = Pick<
|
||||
typeof models.$inferSelect,
|
||||
"id" | "repoId" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
|
||||
>;
|
||||
|
||||
const CHECKED_COLUMNS = {
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
pinnedSha: models.pinnedSha,
|
||||
trackedRevision: models.trackedRevision,
|
||||
hubMissingSince: models.hubMissingSince,
|
||||
updateDiff: models.updateDiff,
|
||||
includePatterns: models.includePatterns,
|
||||
excludePatterns: models.excludePatterns,
|
||||
};
|
||||
|
||||
/** Why new downloads are impossible, or null if the Hub still has the repo at the pinned commit. */
|
||||
export function hubMissingMessage(model: { repoId: string; hubState: HubState | null }): string | null {
|
||||
@@ -16,25 +35,73 @@ export function hubMissingMessage(model: { repoId: string; hubState: HubState |
|
||||
return null;
|
||||
}
|
||||
|
||||
export type HubCheckResult = { state: HubState } | { state: null; error: string };
|
||||
export type HubCheckResult =
|
||||
| { state: HubState; remoteSha: string | null; update: UpdateDiff | null; warning: string | null }
|
||||
| { state: null; error: string };
|
||||
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
const isGated = (err: unknown) => err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access");
|
||||
|
||||
/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */
|
||||
async function resolve(repoId: string, revision: string): Promise<string | null> {
|
||||
try {
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "revision_not_found") return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(model: CheckedModel): Promise<HubCheckResult> {
|
||||
// 1. Head of the tracked revision (a full SHA as revision means "pinned for good").
|
||||
let remoteSha: string | null;
|
||||
let warning: string | null = null;
|
||||
if (SHA_RE.test(model.trackedRevision)) {
|
||||
remoteSha = model.trackedRevision;
|
||||
} else {
|
||||
remoteSha = await resolve(model.repoId, model.trackedRevision);
|
||||
if (!remoteSha) warning = `Revision "${model.trackedRevision}" no longer exists on the Hub; can't check for updates.`;
|
||||
}
|
||||
|
||||
// 2. Is the pinned commit still there? (Known if it's the head.)
|
||||
const pinnedExists = remoteSha === model.pinnedSha || (await resolve(model.repoId, model.pinnedSha)) !== null;
|
||||
const state: HubState = pinnedExists ? "available" : "commit_missing";
|
||||
|
||||
// 3. Newer commit: what would change in the selection? Only recomputed when the head moved.
|
||||
let update: UpdateDiff | null = null;
|
||||
if (remoteSha && remoteSha !== model.pinnedSha) {
|
||||
update = model.updateDiff?.sha === remoteSha ? model.updateDiff : null;
|
||||
if (!update) {
|
||||
const [next, current] = await Promise.all([
|
||||
listFiles(model.repoId, remoteSha),
|
||||
db()
|
||||
.select({ path: modelFiles.path, size: modelFiles.size, blobOid: modelFiles.blobOid, lfsSha256: modelFiles.lfsSha256 })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, model.id), eq(modelFiles.selected, true))),
|
||||
]);
|
||||
update = computeUpdateDiff(remoteSha, current, next, { include: model.includePatterns, exclude: model.excludePatterns });
|
||||
}
|
||||
}
|
||||
return { state, remoteSha, update, warning };
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the repo, and the pinned commit, still on the Hub? Stores the result on the model. Only a
|
||||
* definite answer changes `hubState`; network errors, rate limits or a bad token are kept as
|
||||
* `lastCheckError`. Never touches local files.
|
||||
* Check one model against the Hub and store the result. Only a definite answer changes the stored
|
||||
* state; network errors, rate limits or a bad token are kept as `lastCheckError`.
|
||||
*/
|
||||
export async function checkHubAvailability(model: CheckedModel): Promise<HubCheckResult> {
|
||||
export async function checkHub(model: CheckedModel): Promise<HubCheckResult> {
|
||||
let result: HubCheckResult;
|
||||
try {
|
||||
await getRepoInfo(model.repoId, model.pinnedSha);
|
||||
result = { state: "available" };
|
||||
result = await run(model);
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "repo_not_found") result = { state: "repo_missing" };
|
||||
else if (err instanceof HubError && err.code === "revision_not_found") result = { state: "commit_missing" };
|
||||
// Gated repos exist; access is a download concern, not availability.
|
||||
else if (err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access")) {
|
||||
result = { state: "available" };
|
||||
} else result = { state: null, error: err instanceof Error ? err.message : String(err) };
|
||||
if (err instanceof HubError && err.code === "repo_not_found") {
|
||||
result = { state: "repo_missing", remoteSha: null, update: null, warning: null };
|
||||
} else if (isGated(err)) {
|
||||
// Gated repos exist; access is a download concern.
|
||||
result = { state: "available", remoteSha: null, update: model.updateDiff ?? null, warning: message(err) };
|
||||
} else {
|
||||
result = { state: null, error: message(err) };
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
@@ -45,9 +112,10 @@ export async function checkHubAvailability(model: CheckedModel): Promise<HubChec
|
||||
? { lastCheckedAt: now, lastCheckError: result.error }
|
||||
: {
|
||||
lastCheckedAt: now,
|
||||
lastCheckError: null,
|
||||
lastCheckError: result.warning,
|
||||
hubState: result.state,
|
||||
hubMissingSince: result.state === "available" ? null : (model.hubMissingSince ?? now),
|
||||
...(result.state === "repo_missing" ? {} : { remoteSha: result.remoteSha, updateDiff: result.update }),
|
||||
},
|
||||
)
|
||||
.where(eq(models.id, model.id));
|
||||
@@ -58,7 +126,7 @@ export async function checkHubAvailability(model: CheckedModel): Promise<HubChec
|
||||
export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Promise<CheckedModel[]> {
|
||||
const cutoff = new Date(Date.now() - intervalMs);
|
||||
return db()
|
||||
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha, hubMissingSince: models.hubMissingSince })
|
||||
.select(CHECKED_COLUMNS)
|
||||
.from(models)
|
||||
.where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff)))
|
||||
.orderBy(asc(models.lastCheckedAt))
|
||||
@@ -66,8 +134,6 @@ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Prom
|
||||
}
|
||||
|
||||
export async function getCheckedModel(id: string): Promise<CheckedModel | undefined> {
|
||||
return db().query.models.findFirst({
|
||||
columns: { id: true, repoId: true, pinnedSha: true, hubMissingSince: true },
|
||||
where: eq(models.id, id),
|
||||
});
|
||||
const [row] = await db().select(CHECKED_COLUMNS).from(models).where(eq(models.id, id));
|
||||
return row;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Human-readable job names (shared by UI components).
|
||||
|
||||
const DOWNLOAD_PURPOSE: Record<string, string> = {
|
||||
initial: "Download",
|
||||
add: "Download more",
|
||||
import: "Import",
|
||||
repair: "Repair",
|
||||
update: "Update",
|
||||
};
|
||||
|
||||
const KIND: Record<string, string> = { download: "Download", verify: "Verify", deep_verify: "Deep verify", delete: "Delete" };
|
||||
|
||||
export function jobLabel(job: { kind: string; purpose: string | null }): string {
|
||||
if (job.kind === "download") return DOWNLOAD_PURPOSE[job.purpose ?? "initial"] ?? "Download";
|
||||
return KIND[job.kind] ?? job.kind;
|
||||
}
|
||||
+54
-8
@@ -6,6 +6,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import {
|
||||
ACTIVE_JOB_STATES,
|
||||
type JobPurpose,
|
||||
type JobResult,
|
||||
jobFiles,
|
||||
jobLogs,
|
||||
jobs,
|
||||
@@ -26,19 +27,31 @@ export class JobError extends Error {
|
||||
const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
|
||||
const INSERT_CHUNK = 500;
|
||||
|
||||
/** Queue a download of all selected files of a model at its pinned SHA. */
|
||||
export async function queueDownload(modelId: string, purpose: JobPurpose = "initial"): Promise<{ jobId: string }> {
|
||||
/** True if the model has a queued or running job (only one job per model at a time). */
|
||||
export async function hasOpenJob(modelId: string): Promise<boolean> {
|
||||
const open = await db().query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
|
||||
});
|
||||
return !!open;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a download of all selected files of a model at its pinned SHA. hf skips files that are
|
||||
* already complete, so this also serves as resume and repair. `removePaths`: files of an older
|
||||
* revision to delete once the download succeeded (updates).
|
||||
*/
|
||||
export async function queueDownload(
|
||||
modelId: string,
|
||||
purpose: JobPurpose = "initial",
|
||||
options: { removePaths?: string[] } = {},
|
||||
): Promise<{ jobId: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new JobError("hub_missing", missing, 409);
|
||||
|
||||
const open = await d.query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
|
||||
});
|
||||
if (open) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
@@ -57,6 +70,7 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init
|
||||
purpose,
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: files.reduce((s, f) => s + f.size, 0),
|
||||
result: options.removePaths?.length ? { removePaths: options.removePaths } : null,
|
||||
}),
|
||||
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
|
||||
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
|
||||
@@ -64,6 +78,36 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init
|
||||
return { jobId };
|
||||
}
|
||||
|
||||
/** Queue a verify (size + hf metadata) or deep verify (hashes) of the selected files. Local only. */
|
||||
export async function queueVerify(modelId: string, deep: boolean): Promise<{ jobId: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true)))
|
||||
.orderBy(asc(modelFiles.path));
|
||||
if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400);
|
||||
|
||||
const jobId = ulid();
|
||||
await d.batch([
|
||||
d.insert(jobs).values({
|
||||
id: jobId,
|
||||
modelId,
|
||||
kind: deep ? "deep_verify" : "verify",
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: files.reduce((s, f) => s + f.size, 0),
|
||||
}),
|
||||
...chunk(
|
||||
files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })),
|
||||
INSERT_CHUNK,
|
||||
).map((c) => d.insert(jobFiles).values(c)),
|
||||
]);
|
||||
return { jobId };
|
||||
}
|
||||
|
||||
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
|
||||
export async function requestCancel(jobId: string): Promise<void> {
|
||||
const res = await db()
|
||||
@@ -97,6 +141,7 @@ export type JobSnapshot = {
|
||||
exitCode: number | null;
|
||||
errorCode: string | null;
|
||||
errorMessage: string | null;
|
||||
result: JobResult | null;
|
||||
cancelRequested: boolean;
|
||||
createdAt: number;
|
||||
startedAt: number | null;
|
||||
@@ -128,6 +173,7 @@ const jobColumns = {
|
||||
exitCode: jobs.exitCode,
|
||||
errorCode: jobs.errorCode,
|
||||
errorMessage: jobs.errorMessage,
|
||||
result: jobs.result,
|
||||
cancelRequestedAt: jobs.cancelRequestedAt,
|
||||
createdAt: jobs.createdAt,
|
||||
startedAt: jobs.startedAt,
|
||||
|
||||
+3
-1
@@ -21,6 +21,7 @@ export async function listLibrary() {
|
||||
remoteSha: models.remoteSha,
|
||||
status: models.status,
|
||||
hubState: models.hubState,
|
||||
updateDiff: models.updateDiff,
|
||||
createdAt: models.createdAt,
|
||||
downloadedAt: models.downloadedAt,
|
||||
baseModels: models.baseModels,
|
||||
@@ -51,8 +52,9 @@ export async function listLibrary() {
|
||||
const tagsByModel = new Map<string, Tag[]>();
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
|
||||
|
||||
return rows.map((r) => ({
|
||||
return rows.map(({ updateDiff, ...r }) => ({
|
||||
...r,
|
||||
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
|
||||
author: r.repoId.split("/")[0],
|
||||
families: modelFamilies(r.repoId, r.baseModels),
|
||||
baseModels: r.baseModels ?? [],
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Remove a model and everything that references it from the database (not its files).
|
||||
// Shared by the web app and the worker, so no "server-only" import here.
|
||||
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobFiles, jobLogs, jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
|
||||
export async function purgeModelRows(modelId: string): Promise<void> {
|
||||
const d = db();
|
||||
const jobIds = d.select({ id: jobs.id }).from(jobs).where(eq(jobs.modelId, modelId));
|
||||
await d.batch([
|
||||
d.delete(jobLogs).where(inArray(jobLogs.jobId, jobIds)),
|
||||
d.delete(jobFiles).where(inArray(jobFiles.jobId, jobIds)),
|
||||
d.delete(jobs).where(eq(jobs.modelId, modelId)),
|
||||
d.delete(modelTags).where(eq(modelTags.modelId, modelId)),
|
||||
d.delete(modelFiles).where(eq(modelFiles.modelId, modelId)),
|
||||
d.delete(modelRevisions).where(eq(modelRevisions.modelId, modelId)),
|
||||
d.delete(models).where(eq(models.id, modelId)),
|
||||
]);
|
||||
}
|
||||
+97
-22
@@ -1,18 +1,20 @@
|
||||
import "server-only";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, localFolders, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from "@/lib/db/schema";
|
||||
import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder } from "@/lib/local-folders";
|
||||
import { hasOpenJob, queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { contentId } from "@/lib/update-diff";
|
||||
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy" | "hub_missing",
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -88,28 +90,100 @@ export async function addModel(input: {
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/** Remove a model from the library. Only allowed before anything was downloaded (for now). */
|
||||
export async function removeModel(id: string): Promise<void> {
|
||||
/**
|
||||
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
|
||||
* files that aren't part of the repo are kept); without, only the library entry goes and the
|
||||
* folder shows up under "Found in the models folder" again.
|
||||
*/
|
||||
export async function deleteModel(id: string, options: { deleteFiles: boolean }): Promise<{ queued: boolean }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
const [{ n }] = await d
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(jobs)
|
||||
.where(eq(jobs.modelId, id));
|
||||
if (model.status !== "pending" || n > 0) {
|
||||
throw new ModelError(
|
||||
"not_removable",
|
||||
"Only models that were never downloaded can be removed yet. Deleting downloaded models comes in a later milestone.",
|
||||
409,
|
||||
);
|
||||
if (await hasOpenJob(id)) {
|
||||
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
|
||||
}
|
||||
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
|
||||
const neverDownloaded = model.status === "pending" && n === 0;
|
||||
if (!options.deleteFiles || neverDownloaded) {
|
||||
await purgeModelRows(id);
|
||||
if (!neverDownloaded) await requestFolderScan();
|
||||
return { queued: false };
|
||||
}
|
||||
await d.batch([
|
||||
d.delete(modelTags).where(eq(modelTags.modelId, id)),
|
||||
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
|
||||
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
|
||||
d.delete(models).where(eq(models.id, id)),
|
||||
d.insert(jobs).values({ id: ulid(), modelId: id, kind: "delete", targetSha: model.pinnedSha }),
|
||||
d.update(models).set({ status: "deleting" }).where(eq(models.id, id)),
|
||||
]);
|
||||
return { queued: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a model to the newer commit found by the last Hub check: pin it (the old commit stays in
|
||||
* the revision history), refresh the file list, re-apply the selection rule and queue a download.
|
||||
* Unchanged files are kept; changed ones are downloaded again; files that are no longer selected are
|
||||
* deleted after the download succeeded.
|
||||
*/
|
||||
export async function applyUpdate(id: string): Promise<{ jobId: string; sha: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new ModelError("hub_missing", missing, 409);
|
||||
if (await hasOpenJob(id)) {
|
||||
throw new ModelError("busy", "A job for this model is still queued or running. Try again when it has finished.", 409);
|
||||
}
|
||||
const target = model.updateDiff?.sha;
|
||||
if (!target || target !== model.remoteSha || target === model.pinnedSha) {
|
||||
throw new ModelError("no_update", "No update available. Check the Hub again.", 409);
|
||||
}
|
||||
|
||||
const info = await getRepoInfo(model.repoId, target);
|
||||
const files = await listFiles(model.repoId, info.sha);
|
||||
const rule: SelectionRule = { include: model.includePatterns, exclude: model.excludePatterns };
|
||||
const existing = await d.select().from(modelFiles).where(eq(modelFiles.modelId, id));
|
||||
const byPath = new Map(existing.map((f) => [f.path, f]));
|
||||
const next = new Set(files.map((f) => f.path));
|
||||
|
||||
const now = new Date();
|
||||
const writes = [];
|
||||
for (const f of files) {
|
||||
const selected = isSelected(f.path, rule);
|
||||
const old = byPath.get(f.path);
|
||||
if (!old) {
|
||||
writes.push(d.insert(modelFiles).values({ modelId: id, path: f.path, size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected }));
|
||||
continue;
|
||||
}
|
||||
const same = contentId(old) === contentId(f);
|
||||
if (same && old.selected === selected) continue;
|
||||
writes.push(
|
||||
d
|
||||
.update(modelFiles)
|
||||
.set({ size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected, state: same ? old.state : "pending" })
|
||||
.where(eq(modelFiles.id, old.id)),
|
||||
);
|
||||
}
|
||||
// Files gone at the new commit: drop them (and their rows in old jobs' file lists).
|
||||
const gone = existing.filter((f) => !next.has(f.path));
|
||||
if (gone.length > 0) {
|
||||
const ids = gone.map((f) => f.id);
|
||||
writes.push(d.delete(jobFiles).where(inArray(jobFiles.modelFileId, ids)), d.delete(modelFiles).where(inArray(modelFiles.id, ids)));
|
||||
}
|
||||
// Selected before, not anymore (removed from the repo or no longer matching): delete after the download.
|
||||
const removePaths = existing.filter((f) => f.selected && (!next.has(f.path) || !isSelected(f.path, rule))).map((f) => f.path);
|
||||
|
||||
await d.batch([
|
||||
d
|
||||
.update(models)
|
||||
.set({ pinnedSha: info.sha, updateDiff: null, ...metadataColumns(info.metadata, model.authorAvatarUrl) })
|
||||
.where(eq(models.id, id)),
|
||||
d
|
||||
.update(modelRevisions)
|
||||
.set({ supersededAt: now })
|
||||
.where(and(eq(modelRevisions.modelId, id), isNull(modelRevisions.supersededAt))),
|
||||
d.insert(modelRevisions).values({ modelId: id, sha: info.sha }),
|
||||
...writes,
|
||||
]);
|
||||
const { jobId } = await queueDownload(id, "update", { removePaths });
|
||||
return { jobId, sha: info.sha };
|
||||
}
|
||||
|
||||
function chunk<T>(items: T[], size: number): T[][] {
|
||||
@@ -148,7 +222,8 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
|
||||
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
||||
|
||||
await d.batch([
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude }).where(eq(models.id, modelId)),
|
||||
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
|
||||
...changed.map((f) =>
|
||||
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { parseEnvLines, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "./runtimes-shared";
|
||||
|
||||
const base = { name: "x", engine: "vllm" as const, image: "vllm/vllm-openai-cpu:v0.31.0" };
|
||||
|
||||
describe("validateRuntime", () => {
|
||||
it("accepts the presets and common image references", () => {
|
||||
for (const p of RUNTIME_PRESETS) assert.doesNotThrow(() => validateRuntime(p));
|
||||
for (const image of [
|
||||
"ghcr.io/ggml-org/llama.cpp:server",
|
||||
"git.linxweiler.xyz/me/vllm-arc:0.9-patched",
|
||||
"localhost:5000/vllm",
|
||||
`vllm/vllm-openai-xpu@sha256:${"a".repeat(64)}`,
|
||||
]) {
|
||||
assert.equal(validateRuntime({ ...base, image }).image, image);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects bad images, env names, devices and multi-line values", () => {
|
||||
const bad = (patch: object) => assert.throws(() => validateRuntime({ ...base, ...patch }), RuntimeValidationError);
|
||||
bad({ image: "Vllm/Upper:tag" });
|
||||
bad({ image: "vllm/vllm --privileged" });
|
||||
bad({ env: { "BAD-KEY": "1" } });
|
||||
bad({ env: { OK: "a\nb" } });
|
||||
bad({ devices: ["/dev/sda"] });
|
||||
bad({ devices: ["/"] });
|
||||
bad({ extraArgs: ["--a\n--b"] });
|
||||
bad({ name: " " });
|
||||
assert.deepEqual(validateRuntime({ ...base, devices: ["/dev/dri", "/dev/dri/renderD128"] }).devices, [
|
||||
"/dev/dri",
|
||||
"/dev/dri/renderD128",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseEnvLines", () => {
|
||||
it("parses KEY=value lines, skipping blanks and comments", () => {
|
||||
assert.deepEqual(parseEnvLines("A=1\n\n# note\nB = x=y \n"), { A: "1", B: "x=y" });
|
||||
assert.throws(() => parseEnvLines("novalue"), RuntimeValidationError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
// Runtime presets and validation. Pure (no DB), shared by the web app, the worker and tests.
|
||||
|
||||
import type { RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
export type RuntimeInput = {
|
||||
name: string;
|
||||
engine: RuntimeEngine;
|
||||
image: string;
|
||||
description?: string | null;
|
||||
env?: Record<string, string>;
|
||||
extraArgs?: string[];
|
||||
devices?: string[];
|
||||
shmSizeMb?: number | null;
|
||||
numaTuning?: boolean;
|
||||
};
|
||||
|
||||
export type RuntimePreset = RuntimeInput & { id: string; summary: string };
|
||||
|
||||
/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0). */
|
||||
export const RUNTIME_PRESETS: RuntimePreset[] = [
|
||||
{
|
||||
id: "llama.cpp-cpu",
|
||||
name: "llama.cpp (CPU)",
|
||||
engine: "llama.cpp",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server",
|
||||
summary: "Official llama-server image, CPU build. Serves GGUF models.",
|
||||
description: "Official llama.cpp server, CPU build. Pin a build tag (e.g. server-b11429) for reproducible tests.",
|
||||
},
|
||||
{
|
||||
id: "vllm-cpu",
|
||||
name: "vLLM (CPU)",
|
||||
engine: "vllm",
|
||||
image: "vllm/vllm-openai-cpu:v0.31.0",
|
||||
summary: "Official vLLM CPU image. Serves safetensors models (BF16 recommended on AMD Zen).",
|
||||
description: "Official vLLM CPU build. VLLM_CPU_KVCACHE_SPACE is the KV cache size in GiB.",
|
||||
env: { VLLM_CPU_KVCACHE_SPACE: "4" },
|
||||
extraArgs: ["--dtype=bfloat16"],
|
||||
shmSizeMb: 4096,
|
||||
},
|
||||
];
|
||||
|
||||
export const RUNTIME_NAME_MAX = 60;
|
||||
// [registry[:port]/]path[:tag][@sha256:digest], lowercase path components as Docker requires.
|
||||
const IMAGE_RE =
|
||||
/^(?:[a-z0-9]+(?:[.-][a-z0-9]+)*(?::\d+)?\/)?[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*(?::[\w][\w.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$/;
|
||||
const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
/** Device passthrough is limited to GPU device nodes (Intel/AMD: /dev/dri, AMD: /dev/kfd). */
|
||||
const DEVICE_RE = /^\/dev\/(dri(\/[\w.-]+)?|kfd)$/;
|
||||
|
||||
export class RuntimeValidationError extends Error {}
|
||||
|
||||
/** Normalize and validate a runtime definition; throws RuntimeValidationError with a readable message. */
|
||||
export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
|
||||
const name = input.name.trim().replace(/\s+/g, " ");
|
||||
if (!name || name.length > RUNTIME_NAME_MAX) throw new RuntimeValidationError(`Name must be 1–${RUNTIME_NAME_MAX} characters.`);
|
||||
if (input.engine !== "llama.cpp" && input.engine !== "vllm") throw new RuntimeValidationError("Unknown engine type.");
|
||||
const image = input.image.trim();
|
||||
if (!IMAGE_RE.test(image)) throw new RuntimeValidationError(`"${image}" is not a valid image reference (e.g. ghcr.io/org/image:tag).`);
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(input.env ?? {})) {
|
||||
if (!ENV_KEY_RE.test(k)) throw new RuntimeValidationError(`Invalid environment variable name "${k}".`);
|
||||
if (/[\r\n\0]/.test(v)) throw new RuntimeValidationError(`Value of ${k} must be a single line.`);
|
||||
env[k] = v;
|
||||
}
|
||||
const extraArgs = (input.extraArgs ?? []).map((a) => a.trim()).filter(Boolean);
|
||||
for (const a of extraArgs) if (/[\r\n\0]/.test(a)) throw new RuntimeValidationError("Arguments must be single lines.");
|
||||
const devices = (input.devices ?? []).map((d) => d.trim()).filter(Boolean);
|
||||
for (const d of devices) {
|
||||
if (!DEVICE_RE.test(d)) throw new RuntimeValidationError(`Device "${d}" isn't allowed (only /dev/dri… and /dev/kfd).`);
|
||||
}
|
||||
const shm = input.shmSizeMb ?? null;
|
||||
if (shm != null && (!Number.isInteger(shm) || shm < 64 || shm > 262_144)) {
|
||||
throw new RuntimeValidationError("Shared memory must be between 64 MiB and 256 GiB.");
|
||||
}
|
||||
return {
|
||||
name,
|
||||
engine: input.engine,
|
||||
image,
|
||||
description: input.description?.trim() || null,
|
||||
env,
|
||||
extraArgs,
|
||||
devices,
|
||||
shmSizeMb: shm,
|
||||
numaTuning: !!input.numaTuning,
|
||||
};
|
||||
}
|
||||
|
||||
/** "KEY=value" lines ⇄ env object (for the editor). */
|
||||
export function parseEnvLines(text: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line || line.startsWith("#")) continue;
|
||||
const eq = line.indexOf("=");
|
||||
if (eq <= 0) throw new RuntimeValidationError(`"${line}" isn't KEY=value.`);
|
||||
out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const formatEnvLines = (env: Record<string, string>) =>
|
||||
Object.entries(env)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("\n");
|
||||
@@ -0,0 +1,97 @@
|
||||
import "server-only";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type DockerHostInfo, runtimes, workerState } from "@/lib/db/schema";
|
||||
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
|
||||
|
||||
export type Runtime = typeof runtimes.$inferSelect;
|
||||
|
||||
/** Request body for creating/updating a runtime (validated further by validateRuntime). */
|
||||
export const RuntimeBody = z.object({
|
||||
name: z.string().max(200),
|
||||
engine: z.enum(["llama.cpp", "vllm"]),
|
||||
image: z.string().max(512),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
env: z.record(z.string(), z.string().max(4000)).optional(),
|
||||
extraArgs: z.array(z.string().max(4000)).max(200).optional(),
|
||||
devices: z.array(z.string().max(200)).max(20).optional(),
|
||||
shmSizeMb: z.number().int().nullable().optional(),
|
||||
numaTuning: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export class RuntimeError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function validated(input: RuntimeInput) {
|
||||
try {
|
||||
return validateRuntime(input);
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeValidationError) throw new RuntimeError("invalid", err.message, 400);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listRuntimes(): Promise<Runtime[]> {
|
||||
return db().select().from(runtimes).orderBy(asc(runtimes.createdAt));
|
||||
}
|
||||
|
||||
export async function getRuntime(id: string): Promise<Runtime> {
|
||||
const r = await db().query.runtimes.findFirst({ where: eq(runtimes.id, id) });
|
||||
if (!r) throw new RuntimeError("not_found", "Runtime not found.", 404);
|
||||
return r;
|
||||
}
|
||||
|
||||
export async function createRuntime(input: RuntimeInput & { preset?: string }): Promise<Runtime> {
|
||||
const v = validated(input);
|
||||
const preset = input.preset && RUNTIME_PRESETS.some((p) => p.id === input.preset) ? input.preset : null;
|
||||
const [row] = await db()
|
||||
.insert(runtimes)
|
||||
.values({ ...v, preset })
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateRuntime(id: string, input: RuntimeInput): Promise<Runtime> {
|
||||
const current = await getRuntime(id);
|
||||
const v = validated(input);
|
||||
const imageChanged = v.image !== current.image;
|
||||
const [row] = await db()
|
||||
.update(runtimes)
|
||||
.set({
|
||||
...v,
|
||||
// A different image has to be looked up (and maybe pulled) again.
|
||||
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, pullError: null } : {}),
|
||||
})
|
||||
.where(eq(runtimes.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function deleteRuntime(id: string): Promise<void> {
|
||||
await getRuntime(id);
|
||||
await db().delete(runtimes).where(eq(runtimes.id, id));
|
||||
}
|
||||
|
||||
/** Ask the worker to pull (or re-pull, to update a moving tag) the runtime's image. */
|
||||
export async function requestPull(id: string): Promise<void> {
|
||||
await getRuntime(id);
|
||||
await db().update(runtimes).set({ pullRequestedAt: new Date(), pullError: null }).where(eq(runtimes.id, id));
|
||||
}
|
||||
|
||||
/** Docker facts as last reported by the worker; null when DOCKER_HOST isn't configured. */
|
||||
export async function getDockerInfo(): Promise<DockerHostInfo | null> {
|
||||
try {
|
||||
const row = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
|
||||
return row?.docker ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { computeUpdateDiff, diffHasChanges } from "./update-diff";
|
||||
|
||||
const f = (path: string, oid: string, size = 10, lfs = true) => ({
|
||||
path,
|
||||
size,
|
||||
blobOid: `blob-${oid}`,
|
||||
lfsSha256: lfs ? `sha-${oid}` : null,
|
||||
});
|
||||
|
||||
describe("computeUpdateDiff", () => {
|
||||
const current = [f("Q4_K_M.gguf", "a"), f("mmproj-F16.gguf", "b"), f("config.json", "c", 1, false)];
|
||||
const rule = { include: ["Q4_K_M.gguf", "mmproj-F16.gguf", "*.json"], exclude: [] };
|
||||
|
||||
it("finds changed, added and removed selected files", () => {
|
||||
const next = [
|
||||
f("Q4_K_M.gguf", "a2", 12), // re-quantized
|
||||
f("config.json", "c", 1, false), // unchanged
|
||||
f("generation_config.json", "d", 1, false), // new, matches *.json
|
||||
f("Q8_0.gguf", "e"), // new, not selected
|
||||
];
|
||||
const d = computeUpdateDiff("new", current, next, rule, new Date(0));
|
||||
assert.deepEqual(d.changed, [{ path: "Q4_K_M.gguf", size: 12, oldSize: 10 }]);
|
||||
assert.deepEqual(d.added, [{ path: "generation_config.json", size: 1 }]);
|
||||
assert.deepEqual(d.removed, [{ path: "mmproj-F16.gguf", size: 10 }]);
|
||||
assert.ok(diffHasChanges(d));
|
||||
});
|
||||
|
||||
it("reports nothing when the selected files are identical", () => {
|
||||
const d = computeUpdateDiff("new", current, [...current, f("README.md", "r", 1, false)], rule);
|
||||
assert.ok(!diffHasChanges(d));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
// What updating a model to a newer commit would change in its selection. Pure; used by the worker
|
||||
// (update checks) and the web app (applying an update).
|
||||
|
||||
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
|
||||
import { isSelected, type SelectionRule } from "@/lib/selection";
|
||||
|
||||
type RepoFile = { path: string; size: number; blobOid: string | null; lfsSha256: string | null };
|
||||
|
||||
/** Content identity of a file: the LFS SHA-256, else the git blob SHA-1. */
|
||||
export const contentId = (f: { blobOid: string | null; lfsSha256: string | null }) => f.lfsSha256 ?? f.blobOid ?? "";
|
||||
|
||||
/**
|
||||
* Compare the currently selected files with the files the same selection rule picks at the new
|
||||
* commit: changed content, newly matching files, and selected files that are gone.
|
||||
*/
|
||||
export function computeUpdateDiff(sha: string, current: RepoFile[], next: RepoFile[], rule: SelectionRule, now = new Date()): UpdateDiff {
|
||||
const before = new Map(current.map((f) => [f.path, f]));
|
||||
const after = new Map(next.filter((f) => isSelected(f.path, rule)).map((f) => [f.path, f]));
|
||||
const changed: UpdateDiffFile[] = [];
|
||||
const added: UpdateDiffFile[] = [];
|
||||
const removed: UpdateDiffFile[] = [];
|
||||
for (const [path, f] of after) {
|
||||
const old = before.get(path);
|
||||
if (!old) added.push({ path, size: f.size });
|
||||
else if (contentId(old) !== contentId(f)) changed.push({ path, size: f.size, oldSize: old.size });
|
||||
}
|
||||
for (const [path, f] of before) if (!after.has(path)) removed.push({ path, size: f.size });
|
||||
const byPath = (a: UpdateDiffFile, b: UpdateDiffFile) => a.path.localeCompare(b.path);
|
||||
return { sha, changed: changed.sort(byPath), added: added.sort(byPath), removed: removed.sort(byPath), checkedAt: now.toISOString() };
|
||||
}
|
||||
|
||||
/** True if updating would change anything in the selection. */
|
||||
export const diffHasChanges = (d: UpdateDiff | null | undefined) =>
|
||||
!!d && d.changed.length + d.added.length + d.removed.length > 0;
|
||||
@@ -0,0 +1,107 @@
|
||||
// Delete a model: its files on disk, then its database rows.
|
||||
// Only files that belong to the repo (any revision we know of) and hf's .cache folder are removed;
|
||||
// anything else in the folder is kept and logged, and the folder stays if it isn't empty.
|
||||
|
||||
import { readdir, rm, rmdir } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, models } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { HF_CACHE_DIR, listLocalFiles, modelDir, removeLocalFile } from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
|
||||
/** Remove empty directories below `dir` (deepest first), then `dir` itself if empty. */
|
||||
async function removeEmptyDirs(dir: string): Promise<void> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) if (e.isDirectory()) await removeEmptyDirs(join(dir, e.name));
|
||||
await rmdir(dir).catch(() => {}); // fails if not empty, which is fine
|
||||
}
|
||||
|
||||
export class DeleteRunner implements Runner {
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
/** Every file path of the model's repo we know of. */
|
||||
private repoPaths: string[],
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
// Deleting is quick and shouldn't stop halfway; cancel and shutdown wait for it.
|
||||
cancel() {}
|
||||
interrupt() {}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const root = resolve(coreEnv().MODELS_DIR);
|
||||
const dir = modelDir(root, this.model.localPath);
|
||||
const deleted: string[] = [];
|
||||
try {
|
||||
const before = await listLocalFiles(dir);
|
||||
const sizes = new Map(before.map((f) => [f.path, f.size]));
|
||||
for (const path of this.repoPaths) if (await removeLocalFile(dir, path)) deleted.push(path);
|
||||
await rm(join(dir, HF_CACHE_DIR), { recursive: true, force: true });
|
||||
await rmdir(join(dir, ".cache")).catch(() => {});
|
||||
|
||||
const kept = (await listLocalFiles(dir)).map((f) => f.path);
|
||||
await removeEmptyDirs(dir);
|
||||
// The org folder too, if this was its last model (never MODELS_DIR itself).
|
||||
const parent = dirname(dir);
|
||||
if (parent !== root) await rmdir(parent).catch(() => {});
|
||||
|
||||
const bytes = deleted.reduce((s, p) => s + (sizes.get(p) ?? 0), 0);
|
||||
log.info(
|
||||
`deleted ${this.model.repoId}: ${deleted.length} file(s), ${formatBytes(bytes)}` +
|
||||
(kept.length > 0 ? `; kept ${kept.length} file(s) that aren't part of the repo: ${kept.slice(0, 5).join(", ")}` : ""),
|
||||
);
|
||||
// The job and its log go with the model; the worker log above is the record.
|
||||
await purgeModelRows(this.model.id);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.jobLog.system(`Failed after deleting ${deleted.length} file(s): ${message}`);
|
||||
await this.jobLog.close();
|
||||
const d = db();
|
||||
await d.batch([
|
||||
d
|
||||
.update(jobs)
|
||||
.set({ state: "failed", finishedAt: new Date(), errorCode: "unknown", errorMessage: message })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
...(deleted.length > 0
|
||||
? [
|
||||
d
|
||||
.update(modelFiles)
|
||||
.set({ state: "missing", checkedAt: new Date() })
|
||||
.where(and(eq(modelFiles.modelId, this.model.id), inArray(modelFiles.path, deleted))),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
await settleModelStatus(this.model.id);
|
||||
log.error(`job ${this.job.id}: deleting ${this.model.repoId} failed`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Minimal Docker Engine API client (no dependencies): HTTP over TCP (socket proxy) or a unix socket.
|
||||
// Only the endpoints Kaname needs. Paths are unversioned, so the daemon's own API version is used.
|
||||
|
||||
import http from "node:http";
|
||||
|
||||
export class DockerError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status: number | null,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "DockerError";
|
||||
}
|
||||
}
|
||||
|
||||
type Target = { socketPath: string } | { host: string; port: number };
|
||||
|
||||
function parseHost(dockerHost: string): Target {
|
||||
if (dockerHost.startsWith("unix://")) return { socketPath: dockerHost.slice("unix://".length) };
|
||||
const url = new URL(dockerHost.replace(/^tcp:/, "http:"));
|
||||
return { host: url.hostname, port: Number(url.port || 2375) };
|
||||
}
|
||||
|
||||
export class DockerClient {
|
||||
private target: Target;
|
||||
|
||||
constructor(dockerHost: string) {
|
||||
this.target = parseHost(dockerHost);
|
||||
}
|
||||
|
||||
private raw(method: string, path: string, body?: unknown, timeoutMs = 30_000): Promise<http.IncomingMessage> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const payload = body === undefined ? undefined : JSON.stringify(body);
|
||||
const req = http.request(
|
||||
{
|
||||
...this.target,
|
||||
method,
|
||||
path,
|
||||
headers: { Host: "docker", ...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}) },
|
||||
timeout: timeoutMs,
|
||||
},
|
||||
resolve,
|
||||
);
|
||||
req.on("timeout", () => req.destroy(new DockerError(`Docker API ${method} ${path} timed out`, null)));
|
||||
req.on("error", (err) =>
|
||||
reject(err instanceof DockerError ? err : new DockerError(`Can't reach Docker (${err.message})`, null)),
|
||||
);
|
||||
if (payload) req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
private async json<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const res = await this.raw(method, path, body);
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const c of res) chunks.push(c as Buffer);
|
||||
const text = Buffer.concat(chunks).toString("utf8");
|
||||
if ((res.statusCode ?? 500) >= 400) {
|
||||
let message = text;
|
||||
try {
|
||||
message = JSON.parse(text).message ?? text;
|
||||
} catch {}
|
||||
if (res.statusCode === 403) message = `Docker API refused ${method} ${path} (socket proxy permissions?): ${message}`;
|
||||
throw new DockerError(message.trim() || `HTTP ${res.statusCode}`, res.statusCode ?? null);
|
||||
}
|
||||
return (text ? JSON.parse(text) : null) as T;
|
||||
}
|
||||
|
||||
version() {
|
||||
return this.json<{ Version: string; ApiVersion: string; Os: string; Arch: string }>("GET", "/version");
|
||||
}
|
||||
|
||||
info() {
|
||||
return this.json<{ NCPU: number; MemTotal: number; OperatingSystem: string; Architecture: string; ServerVersion: string }>(
|
||||
"GET",
|
||||
"/info",
|
||||
);
|
||||
}
|
||||
|
||||
/** Inspect a container; null if it doesn't exist. */
|
||||
async inspectContainer(id: string) {
|
||||
try {
|
||||
return await this.json<{
|
||||
Id: string;
|
||||
Name: string;
|
||||
Mounts: { Type: string; Source: string; Destination: string; Name?: string }[];
|
||||
NetworkSettings: { Networks: Record<string, unknown> };
|
||||
}>("GET", `/containers/${encodeURIComponent(id)}/json`);
|
||||
} catch (err) {
|
||||
if (err instanceof DockerError && err.status === 404) return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Inspect a local image; null if it isn't pulled. */
|
||||
async inspectImage(ref: string) {
|
||||
try {
|
||||
return await this.json<{ Id: string; Size: number; Created: string; RepoDigests: string[] }>(
|
||||
"GET",
|
||||
`/images/${encodeURIComponent(ref)}/json`,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof DockerError && err.status === 404) return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull an image. The daemon streams JSON lines per layer; `onProgress` gets the summed bytes of
|
||||
* all layers seen so far. Resolves when the pull finished, rejects on an error line.
|
||||
*/
|
||||
async pullImage(ref: string, onProgress: (p: { doneBytes: number; totalBytes: number; status: string }) => void): Promise<void> {
|
||||
const at = ref.lastIndexOf("@") > 0 ? ref.lastIndexOf("@") : -1;
|
||||
const colon = ref.lastIndexOf(":");
|
||||
const hasTag = at === -1 && colon > ref.lastIndexOf("/");
|
||||
const fromImage = at !== -1 ? ref : hasTag ? ref.slice(0, colon) : ref;
|
||||
const tag = at !== -1 ? "" : hasTag ? ref.slice(colon + 1) : "latest";
|
||||
const query = new URLSearchParams({ fromImage, ...(tag ? { tag } : {}) });
|
||||
const res = await this.raw("POST", `/images/create?${query}`, undefined, 60 * 60_000);
|
||||
if ((res.statusCode ?? 500) >= 400) {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const c of res) chunks.push(c as Buffer);
|
||||
const text = Buffer.concat(chunks).toString("utf8");
|
||||
let message = text;
|
||||
try {
|
||||
message = JSON.parse(text).message ?? text;
|
||||
} catch {}
|
||||
throw new DockerError(message.trim(), res.statusCode ?? null);
|
||||
}
|
||||
const layers = new Map<string, { current: number; total: number }>();
|
||||
let buffer = "";
|
||||
let status = "Pulling";
|
||||
for await (const chunk of res) {
|
||||
buffer += (chunk as Buffer).toString("utf8");
|
||||
let nl: number;
|
||||
while ((nl = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, nl).trim();
|
||||
buffer = buffer.slice(nl + 1);
|
||||
if (!line) continue;
|
||||
const msg = JSON.parse(line) as {
|
||||
id?: string;
|
||||
status?: string;
|
||||
error?: string;
|
||||
progressDetail?: { current?: number; total?: number };
|
||||
};
|
||||
if (msg.error) throw new DockerError(msg.error, null);
|
||||
if (msg.status) status = msg.status;
|
||||
if (msg.id && msg.status === "Downloading" && msg.progressDetail?.total) {
|
||||
layers.set(msg.id, { current: msg.progressDetail.current ?? 0, total: msg.progressDetail.total });
|
||||
} else if (msg.id && (msg.status === "Download complete" || msg.status === "Pull complete" || msg.status === "Already exists")) {
|
||||
const l = layers.get(msg.id);
|
||||
if (l) l.current = l.total;
|
||||
}
|
||||
let done = 0;
|
||||
let total = 0;
|
||||
for (const l of layers.values()) {
|
||||
done += l.current;
|
||||
total += l.total;
|
||||
}
|
||||
onProgress({ doneBytes: done, totalBytes: total, status });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-1
@@ -1,10 +1,12 @@
|
||||
import { type ChildProcess, spawn } from "node:child_process";
|
||||
import { mkdir, statfs } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import {
|
||||
type JobErrorCode,
|
||||
type JobState,
|
||||
type ModelFileState,
|
||||
jobFiles,
|
||||
jobs,
|
||||
modelFiles,
|
||||
@@ -17,12 +19,15 @@ import {
|
||||
bytesOnDisk,
|
||||
type ExpectedFile,
|
||||
listIncomplete,
|
||||
fileSize,
|
||||
modelDir,
|
||||
removeLocalFile,
|
||||
removeStaleIncomplete,
|
||||
} from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
import { SpeedMeter } from "./speed";
|
||||
|
||||
const SAMPLE_MS = 1_000;
|
||||
@@ -45,6 +50,8 @@ type FileRow = {
|
||||
doneBytes: number;
|
||||
lfsSha256: string | null;
|
||||
blobOid: string | null;
|
||||
/** Last known state of the file (deep verify may have found a hash mismatch). */
|
||||
state: ModelFileState;
|
||||
};
|
||||
|
||||
type Outcome =
|
||||
@@ -52,7 +59,7 @@ type Outcome =
|
||||
| { state: "cancelled" | "interrupted"; message: string }
|
||||
| { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null };
|
||||
|
||||
export class DownloadRunner {
|
||||
export class DownloadRunner implements Runner {
|
||||
private child?: ChildProcess;
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private killTimer?: NodeJS.Timeout;
|
||||
@@ -74,6 +81,10 @@ export class DownloadRunner {
|
||||
return this.model.id;
|
||||
}
|
||||
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
/** User cancel: stop hf, keep completed files. */
|
||||
cancel() {
|
||||
this.stop("cancelled");
|
||||
@@ -144,6 +155,18 @@ export class DownloadRunner {
|
||||
this.jobLog.system(`Removed ${stale.count} partial file(s) from an earlier run (${formatBytes(stale.bytes)}).`);
|
||||
}
|
||||
|
||||
// hf skips a file whose metadata matches without looking at its content or size, so broken
|
||||
// files (wrong size, or a hash mismatch found by deep verify) have to go first.
|
||||
const broken: string[] = [];
|
||||
for (const f of this.files) {
|
||||
const size = await fileSize(join(dir, f.path));
|
||||
const wrong = size != null && (size !== f.expectedBytes || f.state === "hash_mismatch");
|
||||
if (wrong && (await removeLocalFile(dir, f.path))) broken.push(f.path);
|
||||
}
|
||||
if (broken.length > 0) {
|
||||
this.jobLog.system(`Deleted ${broken.length} broken file(s) so hf downloads them again: ${broken.slice(0, 5).join(", ")}${broken.length > 5 ? ", …" : ""}`);
|
||||
}
|
||||
|
||||
const initial = await this.sample(dir, expected);
|
||||
const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0);
|
||||
const doneCount = initial.filter((p) => p.complete).length;
|
||||
@@ -199,6 +222,12 @@ export class DownloadRunner {
|
||||
.join(", ")}${bad.length > 5 ? ", …" : ""}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Update: files the new revision no longer has (or that are no longer selected).
|
||||
const remove = (this.job.result?.removePaths ?? []).filter((p) => !this.files.some((f) => f.path === p));
|
||||
let removed = 0;
|
||||
for (const path of remove) if (await removeLocalFile(dir, path)) removed++;
|
||||
if (removed > 0) this.jobLog.system(`Deleted ${removed} file(s) that are no longer part of the selection: ${remove.slice(0, 5).join(", ")}`);
|
||||
return { state: "completed" };
|
||||
}
|
||||
|
||||
|
||||
@@ -109,3 +109,31 @@ export async function bytesOnDisk(
|
||||
}
|
||||
return { done: Math.min(partial, file.size), complete: false };
|
||||
}
|
||||
|
||||
/** Delete a downloaded file and hf's metadata/lock for it, so the next `hf download` fetches it again. */
|
||||
export async function removeLocalFile(dir: string, path: string): Promise<boolean> {
|
||||
const full = join(dir, path);
|
||||
const existed = (await fileSize(full)) != null;
|
||||
await rm(full, { force: true });
|
||||
await rm(join(dir, DOWNLOAD_DIR, `${path}.metadata`), { force: true });
|
||||
await rm(join(dir, DOWNLOAD_DIR, `${path}.lock`), { force: true });
|
||||
return existed;
|
||||
}
|
||||
|
||||
/** All files under `dir` (relative, "/"-separated), skipping hf's .cache and .git folders. */
|
||||
export async function listLocalFiles(dir: string): Promise<{ path: string; size: number }[]> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: { path: string; size: number }[] = [];
|
||||
for (const e of entries) {
|
||||
if (!e.isFile()) continue;
|
||||
const rel = join(e.parentPath, e.name).slice(dir.length + 1).split(sep).join("/");
|
||||
if (rel.startsWith(".cache/") || rel.startsWith(".git/")) continue;
|
||||
out.push({ path: rel, size: (await fileSize(join(dir, rel))) ?? 0 });
|
||||
}
|
||||
return out.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
+87
-29
@@ -7,13 +7,17 @@ import { promisify } from "node:util";
|
||||
import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { runMigrations } from "@/lib/db/migrate";
|
||||
import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DeleteRunner } from "./delete";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import type { Runner } from "./runner";
|
||||
import { docker, handlePullRequests, refreshDockerInfo, resetStalePulls, seedRuntimePresets, syncImageStates } from "./runtimes";
|
||||
import { scanModelsDir } from "./scan";
|
||||
import { VerifyRunner } from "./verify";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
const HEARTBEAT_MS = 5_000;
|
||||
@@ -25,12 +29,15 @@ const SHUTDOWN_GRACE_MS = 8_000;
|
||||
const HUB_CHECK_SCAN_MS = 10 * 60_000;
|
||||
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
|
||||
const FOLDER_SCAN_MS = 2 * 60_000;
|
||||
const DOCKER_INFO_MS = 5 * 60_000;
|
||||
const IMAGE_SYNC_MS = 60_000;
|
||||
const PULL_CHECK_MS = 3_000;
|
||||
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
|
||||
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
const instanceId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
const runners = new Map<string, DownloadRunner>();
|
||||
const runners = new Map<string, Runner>();
|
||||
let hfVersion: string | null = null;
|
||||
let stopping = false;
|
||||
|
||||
@@ -168,13 +175,19 @@ async function handleCancelRequests() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Claim the oldest queued download whose model has no running job. */
|
||||
async function claimNextJob() {
|
||||
/** Downloads are limited by MAX_CONCURRENT_DOWNLOADS; verify and delete jobs by this. */
|
||||
const MAX_LOCAL_JOBS = 2;
|
||||
const LOCAL_KINDS = ["verify", "deep_verify", "delete"] as const;
|
||||
|
||||
const running = (local: boolean) => [...runners.values()].filter((r) => (r.kind === "download") !== local).length;
|
||||
|
||||
/** Claim the oldest queued job of the given kinds whose model has no running job. */
|
||||
async function claimNextJob(kinds: readonly JobKind[]) {
|
||||
const busyModels = [...runners.values()].map((r) => r.modelId);
|
||||
const candidates = await db()
|
||||
.select({ id: jobs.id, modelId: jobs.modelId })
|
||||
.select({ id: jobs.id, modelId: jobs.modelId, kind: jobs.kind })
|
||||
.from(jobs)
|
||||
.where(and(eq(jobs.state, "queued"), eq(jobs.kind, "download"), isNull(jobs.cancelRequestedAt)))
|
||||
.where(and(eq(jobs.state, "queued"), inArray(jobs.kind, [...kinds]), isNull(jobs.cancelRequestedAt)))
|
||||
.orderBy(asc(jobs.createdAt))
|
||||
.limit(20);
|
||||
const next = candidates.find((c) => !busyModels.includes(c.modelId));
|
||||
@@ -182,12 +195,33 @@ async function claimNextJob() {
|
||||
|
||||
const [job] = await db()
|
||||
.update(jobs)
|
||||
.set({ state: "downloading", startedAt: new Date(), finishedAt: null, attempt: sql`${jobs.attempt} + 1` })
|
||||
.set({
|
||||
state: next.kind === "download" ? "downloading" : "verifying",
|
||||
startedAt: new Date(),
|
||||
finishedAt: null,
|
||||
attempt: sql`${jobs.attempt} + 1`,
|
||||
})
|
||||
.where(and(eq(jobs.id, next.id), eq(jobs.state, "queued")))
|
||||
.returning();
|
||||
return job ?? null;
|
||||
}
|
||||
|
||||
async function jobFileRows(jobId: string) {
|
||||
return db()
|
||||
.select({
|
||||
modelFileId: jobFiles.modelFileId,
|
||||
path: jobFiles.path,
|
||||
expectedBytes: jobFiles.expectedBytes,
|
||||
doneBytes: jobFiles.doneBytes,
|
||||
lfsSha256: modelFiles.lfsSha256,
|
||||
blobOid: modelFiles.blobOid,
|
||||
state: modelFiles.state,
|
||||
})
|
||||
.from(jobFiles)
|
||||
.innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId))
|
||||
.where(eq(jobFiles.jobId, jobId));
|
||||
}
|
||||
|
||||
async function startJob(job: typeof jobs.$inferSelect) {
|
||||
const model = await db().query.models.findFirst({ where: eq(models.id, job.modelId) });
|
||||
if (!model) {
|
||||
@@ -197,41 +231,47 @@ async function startJob(job: typeof jobs.$inferSelect) {
|
||||
.where(eq(jobs.id, job.id));
|
||||
return;
|
||||
}
|
||||
const files = await db()
|
||||
.select({
|
||||
modelFileId: jobFiles.modelFileId,
|
||||
path: jobFiles.path,
|
||||
expectedBytes: jobFiles.expectedBytes,
|
||||
doneBytes: jobFiles.doneBytes,
|
||||
lfsSha256: modelFiles.lfsSha256,
|
||||
blobOid: modelFiles.blobOid,
|
||||
})
|
||||
.from(jobFiles)
|
||||
.innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId))
|
||||
.where(eq(jobFiles.jobId, job.id));
|
||||
|
||||
await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id));
|
||||
const runner = new DownloadRunner(job, model, files);
|
||||
let runner: Runner;
|
||||
if (job.kind === "download") {
|
||||
const files = await jobFileRows(job.id);
|
||||
await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id));
|
||||
runner = new DownloadRunner(job, model, files);
|
||||
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
|
||||
} else {
|
||||
const repoPaths = (await db().select({ path: modelFiles.path }).from(modelFiles).where(eq(modelFiles.modelId, model.id))).map(
|
||||
(f) => f.path,
|
||||
);
|
||||
if (job.kind === "delete") {
|
||||
runner = new DeleteRunner(job, model, repoPaths);
|
||||
log.info(`job ${job.id}: deleting ${model.repoId}`);
|
||||
} else {
|
||||
runner = new VerifyRunner(job, model, await jobFileRows(job.id), new Set(repoPaths));
|
||||
log.info(`job ${job.id}: ${job.kind === "deep_verify" ? "deep verify" : "verify"} ${model.repoId}`);
|
||||
}
|
||||
}
|
||||
|
||||
runners.set(job.id, runner);
|
||||
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
|
||||
runner
|
||||
.run()
|
||||
.then(async () => {
|
||||
if (job.kind !== "download") return;
|
||||
// A failed download may mean the repo or commit is gone from the Hub; find out right away.
|
||||
const done = await db().query.jobs.findFirst({ columns: { state: true }, where: eq(jobs.id, job.id) });
|
||||
if (done?.state === "failed") await reportHubCheck(model, await checkHubAvailability(model));
|
||||
if (done?.state === "failed") reportHubCheck(model, await checkHub(model));
|
||||
})
|
||||
.catch((err) => log.error(`job ${job.id} crashed`, err))
|
||||
.finally(() => runners.delete(job.id));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hub availability: flags models whose repo or pinned commit disappeared from the Hub
|
||||
// Hub checks: repo/commit still there, newer commit on the tracked revision
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<typeof checkHubAvailability>>) {
|
||||
function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<typeof checkHub>>) {
|
||||
if (result.state === null) log.warn(`Hub check for ${model.repoId} failed: ${result.error}`);
|
||||
else if (result.state !== "available") log.warn(`${model.repoId}: ${result.state.replace("_", " ")} on the Hub (local files kept)`);
|
||||
else if (result.update) log.info(`${model.repoId}: update available (${result.update.sha.slice(0, 7)})`);
|
||||
}
|
||||
|
||||
let scanning = false;
|
||||
@@ -258,7 +298,7 @@ async function checkHubDue() {
|
||||
try {
|
||||
for (const model of await modelsDueForHubCheck(hours * 3_600_000)) {
|
||||
if (stopping) break;
|
||||
reportHubCheck(model, await checkHubAvailability(model));
|
||||
reportHubCheck(model, await checkHub(model));
|
||||
await sleep(1_000); // be gentle with the Hub API
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -275,8 +315,13 @@ async function tick() {
|
||||
try {
|
||||
await handleCancelRequests();
|
||||
const max = coreEnv().MAX_CONCURRENT_DOWNLOADS;
|
||||
while (runners.size < max && !stopping) {
|
||||
const job = await claimNextJob();
|
||||
while (running(false) < max && !stopping) {
|
||||
const job = await claimNextJob(["download"]);
|
||||
if (!job) break;
|
||||
await startJob(job);
|
||||
}
|
||||
while (running(true) < MAX_LOCAL_JOBS && !stopping) {
|
||||
const job = await claimNextJob(LOCAL_KINDS);
|
||||
if (!job) break;
|
||||
await startJob(job);
|
||||
}
|
||||
@@ -336,6 +381,19 @@ async function main() {
|
||||
timers.push(setInterval(() => void tick(), TICK_MS));
|
||||
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
|
||||
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
|
||||
|
||||
// Runtimes (Docker): presets, host facts, image states, pulls.
|
||||
await resetStalePulls();
|
||||
await seedRuntimePresets().catch((err) => log.error("seeding runtime presets failed", err));
|
||||
if (docker()) log.info(`Docker API: ${coreEnv().DOCKER_HOST}`);
|
||||
else log.info("DOCKER_HOST not set; runtimes are disabled");
|
||||
const dockerInfo = () => refreshDockerInfo(instanceId).catch((err) => log.error("Docker info failed", err));
|
||||
const imageSync = () => syncImageStates().catch((err) => log.error("image sync failed", err));
|
||||
await dockerInfo();
|
||||
void imageSync();
|
||||
timers.push(setInterval(() => void dockerInfo(), DOCKER_INFO_MS));
|
||||
timers.push(setInterval(() => void imageSync(), IMAGE_SYNC_MS));
|
||||
timers.push(setInterval(() => void handlePullRequests().catch((err) => log.error("pull failed", err)), PULL_CHECK_MS));
|
||||
void scanFolders();
|
||||
void tick();
|
||||
setTimeout(() => void checkHubDue(), 15_000);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { JobKind } from "@/lib/db/schema";
|
||||
|
||||
/** A job the worker is executing (download, verify, delete). */
|
||||
export interface Runner {
|
||||
readonly jobId: string;
|
||||
readonly modelId: string;
|
||||
readonly kind: JobKind;
|
||||
/** User cancel. */
|
||||
cancel(): void;
|
||||
/** Worker shutdown; the job can be resumed later. */
|
||||
interrupt(): void;
|
||||
run(): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// Worker side of runtimes: Docker host facts, image state per runtime, pulling images.
|
||||
// The web app never talks to Docker; it reads what the worker reports in the DB.
|
||||
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { hostname } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
import { and, eq, isNotNull, ne } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type DockerHostInfo, runtimes, settings, workerState } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { RUNTIME_PRESETS } from "@/lib/runtimes-shared";
|
||||
import { DockerClient, DockerError } from "./docker/client";
|
||||
import { log } from "./log";
|
||||
|
||||
const PROGRESS_MS = 1_000;
|
||||
/** CPU flags that matter for inference engines. */
|
||||
const CPU_FEATURES = ["avx2", "avx512f", "avx512_bf16", "avx512_vnni", "avx512bw", "amx_bf16", "amx_int8", "f16c", "fma"];
|
||||
|
||||
let client: DockerClient | null | undefined;
|
||||
export function docker(): DockerClient | null {
|
||||
if (client === undefined) {
|
||||
const host = coreEnv().DOCKER_HOST;
|
||||
client = host ? new DockerClient(host) : null;
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
/** CPU model and features from /proc/cpuinfo (the host's, also inside a container). */
|
||||
async function cpuFacts(): Promise<{ model: string | null; features: string[] }> {
|
||||
try {
|
||||
const text = await readFile("/proc/cpuinfo", "utf8");
|
||||
const model = text.match(/^model name\s*:\s*(.+)$/m)?.[1]?.trim() ?? null;
|
||||
const flags = new Set(text.match(/^flags\s*:\s*(.+)$/m)?.[1]?.split(/\s+/) ?? []);
|
||||
return { model, features: CPU_FEATURES.filter((f) => flags.has(f)) };
|
||||
} catch {
|
||||
return { model: null, features: [] }; // not Linux (dev on Windows/macOS)
|
||||
}
|
||||
}
|
||||
|
||||
/** Find our own container to learn the network and where MODELS_DIR comes from on the host. */
|
||||
async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "network" | "modelsSource">> {
|
||||
const env = coreEnv();
|
||||
let network: string | null = env.KANAME_DOCKER_NETWORK ?? null;
|
||||
let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE
|
||||
? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE }
|
||||
: null;
|
||||
if (network && modelsSource) return { network, modelsSource };
|
||||
|
||||
const self = await c.inspectContainer(hostname()).catch(() => null);
|
||||
if (self) {
|
||||
network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null;
|
||||
const mount = self.Mounts.find((m) => resolve(m.Destination) === resolve(env.MODELS_DIR));
|
||||
if (!modelsSource && mount) {
|
||||
modelsSource = mount.Type === "volume" ? { type: "volume", source: mount.Name ?? mount.Source } : { type: "bind", source: mount.Source };
|
||||
}
|
||||
}
|
||||
return { network, modelsSource };
|
||||
}
|
||||
|
||||
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
|
||||
export async function refreshDockerInfo(instanceId: string): Promise<void> {
|
||||
const c = docker();
|
||||
let info: DockerHostInfo | null = null;
|
||||
if (c) {
|
||||
const cpu = await cpuFacts();
|
||||
const base = {
|
||||
cpuModel: cpu.model,
|
||||
cpuFeatures: cpu.features,
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
const [v, i] = await Promise.all([c.version(), c.info()]);
|
||||
info = {
|
||||
connected: true,
|
||||
error: null,
|
||||
serverVersion: v.Version,
|
||||
os: i.OperatingSystem,
|
||||
architecture: i.Architecture,
|
||||
cpus: i.NCPU,
|
||||
memoryBytes: i.MemTotal,
|
||||
...base,
|
||||
...(await selfDetect(c)),
|
||||
};
|
||||
} catch (err) {
|
||||
info = {
|
||||
connected: false,
|
||||
error: message(err),
|
||||
serverVersion: null,
|
||||
os: null,
|
||||
architecture: null,
|
||||
cpus: null,
|
||||
memoryBytes: null,
|
||||
network: null,
|
||||
modelsSource: null,
|
||||
...base,
|
||||
};
|
||||
}
|
||||
}
|
||||
await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
|
||||
}
|
||||
|
||||
const SEEDED_KEY = "runtimes.presetsSeeded";
|
||||
|
||||
/** Create the preset runtimes once (deleted presets don't come back). */
|
||||
export async function seedRuntimePresets(): Promise<void> {
|
||||
const d = db();
|
||||
const seeded = await d.query.settings.findFirst({ where: eq(settings.key, SEEDED_KEY) });
|
||||
if (seeded) return;
|
||||
const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1);
|
||||
if (existing.length === 0) {
|
||||
await d.insert(runtimes).values(
|
||||
RUNTIME_PRESETS.map((p) => ({
|
||||
name: p.name,
|
||||
engine: p.engine,
|
||||
image: p.image,
|
||||
description: p.description ?? null,
|
||||
env: p.env ?? {},
|
||||
extraArgs: p.extraArgs ?? [],
|
||||
devices: p.devices ?? [],
|
||||
shmSizeMb: p.shmSizeMb ?? null,
|
||||
numaTuning: p.numaTuning ?? false,
|
||||
preset: p.id,
|
||||
})),
|
||||
);
|
||||
log.info(`created ${RUNTIME_PRESETS.length} preset runtime(s)`);
|
||||
}
|
||||
await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing();
|
||||
}
|
||||
|
||||
/** Look up every runtime's image locally (present / missing), except ones being pulled. */
|
||||
export async function syncImageStates(): Promise<void> {
|
||||
const c = docker();
|
||||
if (!c) return;
|
||||
const rows = await db().select().from(runtimes).where(ne(runtimes.imageState, "pulling"));
|
||||
for (const r of rows) {
|
||||
try {
|
||||
const img = await c.inspectImage(r.image);
|
||||
await db()
|
||||
.update(runtimes)
|
||||
.set(
|
||||
img
|
||||
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageCheckedAt: new Date() }
|
||||
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageCheckedAt: new Date() },
|
||||
)
|
||||
.where(eq(runtimes.id, r.id));
|
||||
} catch (err) {
|
||||
log.warn(`image check for ${r.image} failed: ${message(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pulls interrupted by a worker restart can't still be running. */
|
||||
export async function resetStalePulls(): Promise<void> {
|
||||
await db().update(runtimes).set({ imageState: "unknown", pullProgress: null }).where(eq(runtimes.imageState, "pulling"));
|
||||
}
|
||||
|
||||
let pulling = false;
|
||||
/** Pull images whose "Pull" was requested after the last pull started. One at a time. */
|
||||
export async function handlePullRequests(): Promise<void> {
|
||||
const c = docker();
|
||||
if (!c || pulling) return;
|
||||
const rows = await db().select().from(runtimes).where(isNotNull(runtimes.pullRequestedAt));
|
||||
const next = rows.find((r) => r.imageState !== "pulling" && (!r.pullStartedAt || r.pullRequestedAt! > r.pullStartedAt));
|
||||
if (!next) return;
|
||||
|
||||
pulling = true;
|
||||
const d = db();
|
||||
await d
|
||||
.update(runtimes)
|
||||
.set({ imageState: "pulling", pullStartedAt: new Date(), pullError: null, pullProgress: { doneBytes: 0, totalBytes: 0, status: "Starting" } })
|
||||
.where(eq(runtimes.id, next.id));
|
||||
log.info(`pulling ${next.image}`);
|
||||
let lastWrite = 0;
|
||||
try {
|
||||
await c.pullImage(next.image, (p) => {
|
||||
if (Date.now() - lastWrite < PROGRESS_MS) return;
|
||||
lastWrite = Date.now();
|
||||
void d.update(runtimes).set({ pullProgress: p }).where(eq(runtimes.id, next.id));
|
||||
});
|
||||
const img = await c.inspectImage(next.image);
|
||||
await d
|
||||
.update(runtimes)
|
||||
.set({
|
||||
imageState: img ? "present" : "failed",
|
||||
imageId: img?.Id ?? null,
|
||||
imageSize: img?.Size ?? null,
|
||||
imageCreated: img?.Created ?? null,
|
||||
pullProgress: null,
|
||||
pullError: img ? null : "Pull finished but the image isn't there.",
|
||||
imageCheckedAt: new Date(),
|
||||
})
|
||||
.where(eq(runtimes.id, next.id));
|
||||
log.info(`pulled ${next.image}`);
|
||||
} catch (err) {
|
||||
const msg = err instanceof DockerError ? err.message : message(err);
|
||||
await d.update(runtimes).set({ imageState: "failed", pullProgress: null, pullError: msg }).where(eq(runtimes.id, next.id));
|
||||
log.warn(`pulling ${next.image} failed: ${msg}`);
|
||||
} finally {
|
||||
pulling = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Verify a model's local files against the file list of its pinned commit.
|
||||
// verify: existence, size, and hf's recorded etag (fast)
|
||||
// deep_verify: additionally hashes every file: SHA-256 for LFS files, git blob SHA-1 for small
|
||||
// files, compared with the hashes from the Hub API (slow, with progress)
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type JobResult, jobFiles, jobs, type ModelFileState, modelFiles, models } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { fileSize, listLocalFiles, modelDir, readMetadata } from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
import { SpeedMeter } from "./speed";
|
||||
|
||||
const PROGRESS_MS = 1_000;
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
export type VerifyFile = { modelFileId: string; path: string; expectedBytes: number; lfsSha256: string | null; blobOid: string | null };
|
||||
|
||||
class Stopped extends Error {}
|
||||
|
||||
export class VerifyRunner implements Runner {
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
private files: VerifyFile[],
|
||||
/** Every path of the repo at the pinned commit (selected or not), to classify extra files. */
|
||||
private repoPaths: Set<string>,
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
cancel() {
|
||||
this.stopReason ??= "cancelled";
|
||||
}
|
||||
interrupt() {
|
||||
this.stopReason ??= "interrupted";
|
||||
}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const deep = this.job.kind === "deep_verify";
|
||||
const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath);
|
||||
const result: Required<Pick<JobResult, "checked" | "missing" | "sizeMismatch" | "hashMismatch" | "extra">> = {
|
||||
checked: 0,
|
||||
missing: [],
|
||||
sizeMismatch: [],
|
||||
hashMismatch: [],
|
||||
extra: [],
|
||||
};
|
||||
this.jobLog.system(
|
||||
`${deep ? "Deep verify (hashing every file)" : "Verify (existence, size, hf metadata)"}: ${this.files.length} selected file(s), ${formatBytes(this.job.totalBytes)} in ${dir}`,
|
||||
);
|
||||
|
||||
const speed = new SpeedMeter();
|
||||
let doneBytes = 0;
|
||||
let lastWrite = 0;
|
||||
const writeProgress = async (force = false) => {
|
||||
if (!force && Date.now() - lastWrite < PROGRESS_MS) return;
|
||||
lastWrite = Date.now();
|
||||
speed.add(Date.now(), doneBytes);
|
||||
const bps = speed.bytesPerSecond();
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ doneBytes, speedBps: bps == null ? null : Math.round(bps), etaSeconds: speed.eta(this.job.totalBytes - doneBytes) })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
await this.jobLog.flush();
|
||||
};
|
||||
|
||||
let failure: string | null = null;
|
||||
try {
|
||||
for (const f of this.files) {
|
||||
if (this.stopReason) throw new Stopped();
|
||||
const state = await this.check(dir, f, deep, async (n) => {
|
||||
doneBytes += n;
|
||||
await writeProgress();
|
||||
});
|
||||
if (!deep) doneBytes += f.expectedBytes;
|
||||
result.checked++;
|
||||
if (state === "missing") result.missing.push(f.path);
|
||||
if (state === "size_mismatch") result.sizeMismatch.push(f.path);
|
||||
if (state === "hash_mismatch") result.hashMismatch.push(f.path);
|
||||
if (state !== "present" && state !== "verified") this.jobLog.system(`${state.replace("_", " ")}: ${f.path}`);
|
||||
await this.markFile(f, state);
|
||||
await writeProgress();
|
||||
}
|
||||
|
||||
// Anything else in the folder: unselected repo files, or files that aren't in the repo at all.
|
||||
const selected = new Set(this.files.map((f) => f.path));
|
||||
for (const local of await listLocalFiles(dir)) {
|
||||
if (!selected.has(local.path)) result.extra.push({ ...local, inRepo: this.repoPaths.has(local.path) });
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Stopped)) failure = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const problems = result.missing.length + result.sizeMismatch.length + result.hashMismatch.length;
|
||||
if (this.stopReason) {
|
||||
this.jobLog.system(this.stopReason === "cancelled" ? "Cancelled by user." : "Interrupted by worker shutdown.");
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: this.stopReason, finishedAt: now, speedBps: null, etaSeconds: null, result })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
} else if (failure) {
|
||||
this.jobLog.system(`Failed: ${failure}`);
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "failed", finishedAt: now, speedBps: null, etaSeconds: null, errorCode: "unknown", errorMessage: failure, result })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
} else {
|
||||
const extraLine =
|
||||
result.extra.length > 0
|
||||
? ` ${result.extra.length} extra file(s) in the folder (${formatBytes(result.extra.reduce((s, e) => s + e.size, 0))}).`
|
||||
: "";
|
||||
this.jobLog.system(
|
||||
problems === 0
|
||||
? `All ${result.checked} file(s) OK${deep ? " (hashes match the Hub)" : ""}.${extraLine}`
|
||||
: `${problems} problem(s): ${result.missing.length} missing, ${result.sizeMismatch.length} size mismatch, ${result.hashMismatch.length} hash mismatch.${extraLine} Use Repair to download them again.`,
|
||||
);
|
||||
await db().batch([
|
||||
db()
|
||||
.update(jobs)
|
||||
.set({ state: "completed", finishedAt: now, speedBps: null, etaSeconds: 0, doneBytes: this.job.totalBytes, result })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
db().update(models).set({ lastVerifiedAt: now }).where(eq(models.id, this.model.id)),
|
||||
]);
|
||||
}
|
||||
await this.jobLog.close();
|
||||
await settleModelStatus(this.model.id);
|
||||
log.info(`job ${this.job.id} (${this.job.kind} ${this.model.repoId}) ${this.stopReason ?? (failure ? "failed" : "completed")}`);
|
||||
}
|
||||
|
||||
private async check(dir: string, f: VerifyFile, deep: boolean, onBytes: (n: number) => Promise<void>): Promise<ModelFileState> {
|
||||
const full = join(dir, f.path);
|
||||
const size = await fileSize(full);
|
||||
if (size == null) return "missing";
|
||||
if (size !== f.expectedBytes) return "size_mismatch";
|
||||
if (!deep) {
|
||||
// hf records the etag it downloaded; a different one means another version of the file.
|
||||
const meta = await readMetadata(dir, f.path);
|
||||
const etags = [f.lfsSha256, f.blobOid].filter(Boolean);
|
||||
return meta && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
}
|
||||
const actual = await this.hash(full, f, onBytes);
|
||||
const expected = f.lfsSha256 ?? f.blobOid;
|
||||
return expected && actual === expected ? "verified" : "hash_mismatch";
|
||||
}
|
||||
|
||||
/** SHA-256 of the content (LFS files) or the git blob SHA-1 (small files stored in git). */
|
||||
private hash(full: string, f: VerifyFile, onBytes: (n: number) => Promise<void>): Promise<string> {
|
||||
const h = f.lfsSha256 ? createHash("sha256") : createHash("sha1").update(`blob ${f.expectedBytes}\0`);
|
||||
return new Promise((resolve, reject) => {
|
||||
const stream = createReadStream(full, { highWaterMark: 8 * 1024 * 1024 });
|
||||
stream.on("data", (chunk) => {
|
||||
if (this.stopReason) {
|
||||
stream.destroy(new Stopped());
|
||||
return;
|
||||
}
|
||||
h.update(chunk);
|
||||
stream.pause();
|
||||
onBytes(chunk.length).then(
|
||||
() => stream.resume(),
|
||||
(err) => stream.destroy(err),
|
||||
);
|
||||
});
|
||||
stream.on("error", reject);
|
||||
stream.on("end", () => resolve(h.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
private async markFile(f: VerifyFile, state: ModelFileState) {
|
||||
const now = new Date();
|
||||
const ok = state === "present" || state === "verified";
|
||||
await db().batch([
|
||||
db().update(modelFiles).set({ state, checkedAt: now }).where(eq(modelFiles.id, f.modelFileId)),
|
||||
db()
|
||||
.update(jobFiles)
|
||||
.set({ state: ok ? "done" : "failed", doneBytes: ok ? f.expectedBytes : 0 })
|
||||
.where(and(eq(jobFiles.jobId, this.job.id), inArray(jobFiles.modelFileId, [f.modelFileId]))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user