Deployments: serve a model with a runtime container

- deployments + deployment_logs tables; desired/actual state reconciled by
  the worker (create/start/stop/remove via the socket proxy, /health wait,
  log follower, stats, memory guard, adopt/remove containers on restart).
- Pure command builder for llama-server and vllm serve (mmproj, MTP draft,
  KV cache types, dtype, KV cache size) with tests; file candidates per
  engine with tests.
- New main menu entry Deployments: list, new/edit form (runtime -> model
  and files -> launch options, live command preview), detail page with
  stats, log, endpoint and a streaming chat smoke test.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 11:31:04 +02:00
1 parent 4f7ae1fc8c
commit 8b74fa69db
32 files changed
+3824 -3

No files matched your search

@@ -0,0 +1,520 @@
"use client";
import { BoxesIcon, CheckIcon, CpuIcon, SearchIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
import { buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
export type FormRuntime = {
id: string;
name: string;
engine: RuntimeEngine;
image: string;
imageState: string;
env: Record<string, string>;
extraArgs: string[];
};
export type FormModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
export type FormHost = { cpus: number | null; memoryBytes: number | null; cpuFeatures: string[] } | null;
export type FormInitial = {
id?: string;
name: string;
runtimeId: string;
modelId: string;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
hostPort: number | null;
};
const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
const KV_TYPES = ["f16", "q8_0", "q4_0"];
const selectClass =
"h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
function Section({ step, title, description, children }: { step: number; title: string; description?: string; children: React.ReactNode }) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-primary text-xs text-primary-foreground">{step}</span>
{title}
</CardTitle>
{description && <CardDescription>{description}</CardDescription>}
</CardHeader>
<CardContent className="flex flex-col gap-4">{children}</CardContent>
</Card>
);
}
function Field({ label, hint, children, htmlFor }: { label: string; hint?: React.ReactNode; children: React.ReactNode; htmlFor?: string }) {
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={htmlFor}>{label}</Label>
{children}
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
);
}
/** Pick runtime → model and files → launch options. Used for "New deployment" and "Edit". */
export function DeploymentForm({
runtimes,
models,
host,
initial,
}: {
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
initial?: FormInitial;
}) {
const router = useRouter();
const editing = !!initial?.id;
const [runtimeId, setRuntimeId] = useState(initial?.runtimeId ?? runtimes.find((r) => r.imageState === "present")?.id ?? "");
const runtime = runtimes.find((r) => r.id === runtimeId) ?? null;
const engine = runtime?.engine ?? "llama.cpp";
const [query, setQuery] = useState("");
const [modelId, setModelId] = useState(initial?.modelId ?? "");
const servable = models.filter((m) => (engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm));
const shown = servable.filter((m) => m.repoId.toLowerCase().includes(query.trim().toLowerCase()));
const model = servable.find((m) => m.id === modelId) ?? null;
const o = initial?.options;
const [modelFile, setModelFile] = useState(o?.modelFile ?? "");
const [mmproj, setMmproj] = useState(o?.mmproj ?? "");
const [draftFile, setDraftFile] = useState(o?.draftFile ?? "");
const [name, setName] = useState(initial?.name ?? "");
const [contextSize, setContextSize] = useState(String(o?.contextSize ?? 4096));
const [threads, setThreads] = useState(o?.threads != null ? String(o.threads) : "");
const [parallel, setParallel] = useState(o?.parallel != null ? String(o.parallel) : "1");
const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? "");
const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
const [batchSize, setBatchSize] = useState(o?.batchSize != null ? String(o.batchSize) : "");
const [ubatchSize, setUbatchSize] = useState(o?.ubatchSize != null ? String(o.ubatchSize) : "");
const [dtype, setDtype] = useState(o?.dtype ?? "");
const [maxNumSeqs, setMaxNumSeqs] = useState(o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "");
const [kvCacheGb, setKvCacheGb] = useState(o?.kvCacheGb != null ? String(o.kvCacheGb) : "");
const [extraArgs, setExtraArgs] = useState((o?.extraArgs ?? []).join("\n"));
const [cpus, setCpus] = useState(initial?.cpus != null ? String(initial.cpus) : "");
const [memoryMb, setMemoryMb] = useState(initial?.memoryMb != null ? String(initial.memoryMb) : "");
const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
const [hostPort, setHostPort] = useState(initial?.hostPort != null ? String(initial.hostPort) : "");
const [saving, setSaving] = useState(false);
function pickModel(m: FormModel) {
setModelId(m.id);
const first = m.candidates.gguf[0];
setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : "");
setMmproj(m.candidates.mmproj[0]?.path ?? "");
setDraftFile("");
if (!editing) setName(`${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim());
}
const options: DeploymentOptions = {
modelFile: engine === "llama.cpp" ? modelFile : "",
mmproj: engine === "llama.cpp" && mmproj ? mmproj : null,
draftFile: engine === "llama.cpp" && draftFile ? draftFile : null,
draftType: model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
contextSize: intOrNull(contextSize) ?? 4096,
threads: intOrNull(threads),
parallel: intOrNull(parallel),
batchSize: engine === "llama.cpp" ? intOrNull(batchSize) : null,
ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null,
cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null,
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
extraArgs: extraArgs
.split("\n")
.map((a) => a.trim())
.filter(Boolean),
};
const fileBytes = model
? engine === "llama.cpp"
? (model.candidates.gguf.find((g) => g.path === modelFile)?.size ?? 0) +
(model.candidates.mmproj.find((g) => g.path === mmproj)?.size ?? 0) +
(model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0)
: (model.candidates.vllm?.size ?? 0)
: 0;
const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, options.kvCacheGb) : null;
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
runtime && model ? renderCommand(runtime.image, buildCommand({ engine, options, model, runtime: { env: runtime.env, extraArgs: runtime.extraArgs } })) : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
if (!runtime || !model) return;
setSaving(true);
try {
const body = {
name: name.trim() || model.repoId,
runtimeId: runtime.id,
modelId: model.id,
options,
cpus: numOrNull(cpus),
memoryMb: memory,
hostPort: intOrNull(hostPort),
start,
};
const res = await fetch(editing ? `/api/deployments/${initial!.id}` : "/api/deployments", {
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
return;
}
const id = editing ? initial!.id : json.id;
if (editing && start) await fetch(`/api/deployments/${id}/start`, { method: "POST" });
toast.success(start ? "Deployment starting" : "Deployment saved");
router.push(`/deployments/${id}`);
router.refresh();
} finally {
setSaving(false);
}
}
return (
<div className="flex flex-col gap-4">
<Section step={1} title="Runtime" description="The container image that serves the model.">
{runtimes.length === 0 ? (
<p className="text-sm text-muted-foreground">
No runtimes yet.{" "}
<Link href="/settings/runtimes" className="underline">
Add one in Settings
</Link>
.
</p>
) : (
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{runtimes.map((r) => {
const ready = r.imageState === "present";
return (
<button
key={r.id}
type="button"
disabled={!ready}
onClick={() => {
setRuntimeId(r.id);
if (r.engine !== engine) setModelId("");
}}
className={cn(
"flex flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50",
runtimeId === r.id ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/50",
)}
>
<span className="flex w-full items-center justify-between gap-2 text-sm font-medium">
<span className="flex items-center gap-1.5">
<BoxesIcon className="size-4 text-muted-foreground" />
{r.name}
</span>
{runtimeId === r.id && <CheckIcon className="size-4 text-primary" />}
</span>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
<span className="text-xs text-muted-foreground">
{r.engine === "vllm" ? "vLLM · safetensors" : "llama.cpp · GGUF"}
{!ready && " · image not pulled"}
</span>
</button>
);
})}
</div>
)}
{runtimes.some((r) => r.imageState !== "present") && (
<p className="text-xs text-muted-foreground">
Runtimes whose image isn&apos;t pulled yet can&apos;t be picked.{" "}
<Link href="/settings/runtimes" className="underline">
Pull them in Settings
</Link>
.
</p>
)}
</Section>
{runtime && (
<Section
step={2}
title="Model"
description={engine === "llama.cpp" ? "Downloaded GGUF models. Pick the quant and optional extras." : "Downloaded safetensors repos (with config.json)."}
>
{servable.length === 0 ? (
<p className="text-sm text-muted-foreground">
No downloaded model fits this runtime.{" "}
<Link href="/" className="underline">
Add one in the library
</Link>
{engine === "vllm" ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)." : "."}
</p>
) : (
<>
{servable.length > 6 && (
<div className="relative">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search models…" className="pl-8" />
</div>
)}
<div className="flex max-h-72 flex-col divide-y overflow-y-auto rounded-lg ring-1 ring-foreground/10">
{shown.map((m) => (
<button
key={m.id}
type="button"
onClick={() => pickModel(m)}
className={cn("flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50", modelId === m.id && "bg-primary/5")}
>
<span className="flex min-w-0 items-center gap-2">
{modelId === m.id ? <CheckIcon className="size-4 shrink-0 text-primary" /> : <span className="size-4 shrink-0" />}
<span className="truncate">{m.repoId}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{engine === "llama.cpp"
? `${m.candidates.gguf.length} GGUF${m.candidates.mmproj.length ? " · vision" : ""}${m.candidates.drafts.length ? " · MTP/draft" : ""}`
: formatBytes(m.candidates.vllm?.size ?? 0)}
</span>
</button>
))}
</div>
{model && engine === "llama.cpp" && (
<div className="grid gap-4 md:grid-cols-3">
<Field label="Model file">
<div className="flex flex-col gap-1">
{model.candidates.gguf.map((g) => (
<label key={g.path} className={cn("flex cursor-pointer items-center gap-2 rounded-md border px-2 py-1.5 text-xs", modelFile === g.path && "border-primary bg-primary/5")}>
<input type="radio" name="modelFile" checked={modelFile === g.path} onChange={() => setModelFile(g.path)} className="accent-primary" />
<span className="min-w-0 flex-1 truncate font-mono" title={g.path}>
{quantGroup(g.path) ?? g.path}
</span>
<span className="text-muted-foreground tabular-nums">{formatBytes(g.size)}</span>
</label>
))}
</div>
</Field>
<Field label="Vision (mmproj)" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<select value={mmproj} onChange={(e) => setMmproj(e.target.value)} className={selectClass} disabled={model.candidates.mmproj.length === 0}>
<option value="">None</option>
{model.candidates.mmproj.map((m) => (
<option key={m.path} value={m.path}>
{m.path} ({formatBytes(m.size)})
</option>
))}
</select>
</Field>
<Field
label="Speculative decoding"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "MTP heads use --spec-type draft-mtp."}
>
<select value={draftFile} onChange={(e) => setDraftFile(e.target.value)} className={selectClass} disabled={model.candidates.drafts.length === 0}>
<option value="">Off</option>
{model.candidates.drafts.map((d) => (
<option key={d.path} value={d.path}>
{d.type === "draft-mtp" ? "MTP: " : "Draft: "}
{d.path} ({formatBytes(d.size)})
</option>
))}
</select>
</Field>
</div>
)}
{model && (
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{[modelFile, mmproj, draftFile].filter(Boolean).map((p) => (
<span key={p} className="flex items-center gap-1">
<FileRoleBadge path={p} />
</span>
))}
<span>{formatBytes(fileBytes)} of model files</span>
</div>
)}
</>
)}
</Section>
)}
{runtime && model && (
<Section step={3} title="Launch options" description="Empty fields use the engine's defaults.">
<div className="grid gap-4 md:grid-cols-3">
<Field label="Name" htmlFor="d-name">
<Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} />
</Field>
<Field label="Context size (tokens)" htmlFor="d-ctx" hint={engine === "vllm" ? "--max-model-len" : "-c"}>
<div className="flex gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-24" />
<div className="flex flex-wrap gap-1">
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c >= 1024 ? `${c / 1024}k` : c}
</Button>
))}
</div>
</div>
</Field>
<Field
label={engine === "vllm" ? "Max concurrent sequences" : "Parallel slots"}
htmlFor="d-par"
hint={engine === "vllm" ? "--max-num-seqs" : "-np; the context is shared between slots"}
>
{engine === "vllm" ? (
<Input id="d-par" value={maxNumSeqs} onChange={(e) => setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
) : (
<Input id="d-par" value={parallel} onChange={(e) => setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
)}
</Field>
</div>
{engine === "llama.cpp" ? (
<div className="grid gap-4 md:grid-cols-4">
<Field label="Threads" htmlFor="d-thr" hint={host?.cpus ? `-t / -tb; host has ${host.cpus}` : "-t / -tb"}>
<Input id="d-thr" value={threads} onChange={(e) => setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
<Field label="KV cache K / V" hint="-ctk / -ctv; q8_0 halves the KV memory">
<div className="flex gap-1.5">
{[
[cacheTypeK, setCacheTypeK],
[cacheTypeV, setCacheTypeV],
].map(([value, set], i) => (
<select key={i} value={value as string} onChange={(e) => (set as (v: string) => void)(e.target.value)} className={selectClass}>
<option value="">default</option>
{KV_TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
))}
</div>
</Field>
<Field label="Flash attention" hint="-fa">
<select value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)} className={selectClass}>
<option value="">default (auto)</option>
<option value="on">on</option>
<option value="off">off</option>
</select>
</Field>
<Field label="Batch / micro-batch" hint="-b / -ub">
<div className="flex gap-1.5">
<Input value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" aria-label="Batch size" />
<Input value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" aria-label="Micro-batch size" />
</div>
</Field>
</div>
) : (
<div className="grid gap-4 md:grid-cols-3">
<Field
label="Data type"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster than bfloat16." : "--dtype; overrides the runtime's default"}
>
<select value={dtype} onChange={(e) => setDtype(e.target.value)} className={selectClass}>
<option value="">runtime default</option>
<option value="bfloat16">bfloat16</option>
<option value="float32">float32</option>
<option value="float16">float16</option>
<option value="auto">auto</option>
</select>
</Field>
<Field label="KV cache (GiB)" htmlFor="d-kv" hint="VLLM_CPU_KVCACHE_SPACE">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
<Field label="Threads" hint="vLLM binds OpenMP threads itself (VLLM_CPU_OMP_THREADS_BIND); limit CPUs below instead.">
<Input value="auto" disabled />
</Field>
</div>
)}
<div className="grid gap-4 md:grid-cols-3">
<Field label="CPU limit (cores)" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus})` : "Empty: no limit"}>
<Input id="d-cpus" value={cpus} onChange={(e) => setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
</Field>
<Field
label="Memory limit (MiB)"
htmlFor="d-mem"
hint={
<>
Estimate: {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
{host?.memoryBytes ? ` · host: ${formatBytes(host.memoryBytes)}` : ""}
{memoryTouched && (
<button type="button" className="ml-1 underline" onClick={() => setMemoryTouched(false)}>
use estimate
</button>
)}
</>
}
>
<Input
id="d-mem"
value={memoryTouched ? memoryMb : String(estimate ?? "")}
onChange={(e) => {
setMemoryTouched(true);
setMemoryMb(e.target.value.replace(/\D/g, ""));
}}
inputMode="numeric"
/>
</Field>
<Field label="Publish on host port" htmlFor="d-port" hint={`Optional: reach the API at http://<server>:<port>/v1 (container port ${ENGINE_PORT[engine]}).`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
</div>
<Field label="Extra arguments" htmlFor="d-args" hint="One per line, appended after the runtime's own extra arguments.">
<textarea
id="d-args"
value={extraArgs}
onChange={(e) => setExtraArgs(e.target.value)}
spellCheck={false}
className="min-h-16 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"
placeholder={engine === "vllm" ? "--enforce-eager" : "--temp\n0.7"}
/>
</Field>
{preview && (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<Label className="flex items-center gap-1.5">
<CpuIcon className="size-4 text-muted-foreground" />
Command
</Label>
<CopyButton value={preview} label="Copy command" />
</div>
<pre className="overflow-x-auto rounded-lg bg-muted/60 px-3 py-2 font-mono text-xs whitespace-pre-wrap break-all">{preview}</pre>
</div>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => router.back()}>
Cancel
</Button>
<Button type="button" variant="outline" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(false)}>
{editing ? "Save" : "Create"}
</Button>
<Button type="button" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(true)}>
{editing ? "Save & start" : "Create & start"}
</Button>
</div>
</Section>
)}
</div>
);
}