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,402 @@
"use client";
import { PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { ENGINE_PORT } from "@/lib/deploy-command";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
type LogLine = { id: number; ts: number; stream: string; line: string };
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold tabular-nums">{value}</span>
{children}
</div>
);
}
export function DeploymentDetail({ initial }: { initial: Deployment }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
useEffect(() => {
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
if (res?.status === 404) router.push("/deployments");
else if (res?.ok) setD(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [d.id, router]);
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
// The browser's host name (null while rendering on the server, so hydration matches).
const hostname = useSyncExternalStore(
() => () => {},
() => window.location.hostname,
() => null,
);
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{d.name}</h1>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
{d.repoId}
</Link>
{file && ` · ${file}`}
{d.options.mmproj && " · vision"}
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
</p>
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
</div>
<div className="flex flex-wrap items-center gap-2">
{active ? (
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
<SquareIcon />
Stop
</Button>
) : (
<Button onClick={() => startDeployment(d.id)}>
<PlayIcon />
Start
</Button>
)}
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
aria-disabled={active}
title={active ? "Stop it first" : undefined}
>
<PencilIcon />
Edit
</Link>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteDeployment(d.id)) router.push("/deployments");
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{d.state === "failed" && d.error && (
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
<div className="flex min-w-0 flex-col gap-4">
<Card>
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat
label="CPU"
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
>
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
</Stat>
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
{d.stats && d.state === "running" && d.memoryMb ? (
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
) : (
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
)}
</Stat>
<Stat
label={d.state === "starting" ? "Loading" : "Load time"}
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
>
<span className="text-xs text-muted-foreground">until /health answered</span>
</Stat>
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
<span className="text-xs text-muted-foreground">
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
</span>
</Stat>
</CardContent>
</Card>
<Logs id={d.id} />
</div>
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-xs">
{internal ? (
<div className="flex items-center justify-between gap-2">
<code className="font-mono break-all">{internal}</code>
<CopyButton value={internal} label="Copy URL" />
</div>
) : (
<span className="text-muted-foreground">Not started yet.</span>
)}
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
{published && (
<div className="flex items-center justify-between gap-2 border-t pt-2">
<code className="font-mono break-all">{published}</code>
<CopyButton value={published} label="Copy URL" />
</div>
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
</span>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Container</dt>
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={d.startedAt} />
</dd>
<dt className="text-muted-foreground">Stopped</dt>
<dd>
<LocalTime value={d.stoppedAt} />
</dd>
{d.command && (
<>
<dt className="text-muted-foreground">Arguments</dt>
<dd className="flex items-start gap-1">
<code className="font-mono break-all">{d.command.join(" ")}</code>
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
</dd>
</>
)}
</dl>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
/** Live container log (polls new lines every 1.5 s). */
function Logs({ id }: { id: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`/api/deployments/${id}/logs?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [id]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className="min-w-0">
<CardHeader>
<CardTitle>Log</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
const [answer, setAnswer] = useState("");
const [busy, setBusy] = useState(false);
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
const [error, setError] = useState<string | null>(null);
async function send() {
setBusy(true);
setAnswer("");
setError(null);
setStats(null);
const t0 = performance.now();
let first: number | null = null;
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
let chunks = 0;
try {
const res = await fetch(`/api/deployments/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
});
if (!res.ok || !res.body) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const j = JSON.parse(data);
if (j.usage) usage = j.usage;
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
if (delta) {
first ??= performance.now();
chunks++;
setAnswer((a) => a + delta);
}
}
}
const total = (performance.now() - t0) / 1000;
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle>Try it</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
disabled={!running}
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
/>
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
<SendIcon />
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
</Button>
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
{stats && (
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div>
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
<div className="text-muted-foreground">first token</div>
</div>
<div>
<div className="font-semibold tabular-nums">
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
</div>
<div className="text-muted-foreground">generation</div>
</div>
<div>
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,26 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentForm } from "../../deployment-form";
import { formData } from "../../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Edit deployment" };
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
const { id } = await params;
const [d, data] = await Promise.all([getDeployment(id), formData()]);
if (!d) notFound();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
{d.state !== "stopped" && d.state !== "failed" && (
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
)}
<DeploymentForm
{...data}
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
/>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
const d = await getDeployment((await params).id);
return { title: d ? d.name : "Deployment" };
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const d = await getDeployment((await params).id);
if (!d) notFound();
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} />;
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string): Promise<boolean> {
const res = await fetch(url, { method });
if (res.ok) return true;
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
@@ -0,0 +1,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>
);
}
@@ -0,0 +1,97 @@
"use client";
import { PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { startDeployment, stopDeployment } from "./actions";
type Row = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
const isActive = (r: Row) => r.desiredState === "running" || r.state === "starting" || r.state === "running" || r.state === "stopping";
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
async function reload() {
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(() => null);
if (res?.ok) setRows(await res.json());
}
useEffect(() => {
const t = setInterval(reload, busy ? 2_000 : 5_000);
return () => clearInterval(t);
}, [busy]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<RocketIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">No deployments yet. Pick a runtime and a downloaded model to start one.</p>
<Link href="/deployments/new" className="text-sm underline">
New deployment
</Link>
</Card>
);
}
return (
<div className="grid gap-3 md:grid-cols-2">
{rows.map((r) => {
const file = r.options.modelFile ? (quantGroup(r.options.modelFile) ?? r.options.modelFile) : null;
const loadSecs = r.readyAt && r.startedAt ? (new Date(r.readyAt).getTime() - new Date(r.startedAt).getTime()) / 1000 : null;
return (
<Card key={r.id} className="gap-3 px-4 py-3">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-0.5">
<Link href={`/deployments/${r.id}`} className="truncate font-medium hover:underline">
{r.name}
</Link>
<span className="truncate text-xs text-muted-foreground">
{r.repoId}
{file && ` · ${file}`}
{r.options.mmproj && " · vision"}
{r.options.draftFile && " · MTP/draft"}
</span>
<span className="text-xs text-muted-foreground">{r.runtimeName}</span>
</div>
<DeploymentStateBadge state={r.state} desiredState={r.desiredState} />
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="tabular-nums">
{r.state === "running" && r.stats
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
: r.state === "failed"
? (r.error?.split("\n")[0] ?? "failed")
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
{r.state === "running" && loadSecs != null && ` · loaded in ${loadSecs.toFixed(1)} s`}
</span>
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
</div>
</Card>
);
})}
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import "server-only";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost }> {
const [runtimes, models, docker] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
};
}
+16
View File
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
export default async function NewDeploymentPage() {
const data = await formData();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { listDeployments } from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { DeploymentList } from "./deployment-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Deployments" };
export default async function DeploymentsPage() {
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Deployments</h1>
<Link href="/deployments/new" className={buttonVariants()}>
New deployment
</Link>
</div>
{!docker?.connected && (
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
<Link href="/settings/runtimes" className="underline">
Settings → Runtimes
</Link>
.
</p>
)}
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
@@ -0,0 +1,41 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
const Body = z.object({
messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100),
maxTokens: z.number().int().min(1).max(8192).default(256),
});
/**
* Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and
* streams the server-sent events back unchanged.
*/
export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (req, { params }) => {
try {
const d = await getDeployment((await params).id);
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`);
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listDeploymentLogs } from "@/lib/deployments";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/deployments/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listDeploymentLogs((await params).id, after));
});
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentBody, DeploymentError, getDeployment, requestDelete, updateDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
const d = await getDeployment((await params).id);
return d ? NextResponse.json(d) : apiError(404, "not_found", "Deployment not found.");
});
export const PUT = withAuth<RouteContext<"/api/deployments/[id]">>(async (req, { params }) => {
try {
await updateDeployment((await params).id, DeploymentBody.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Stop the container (if running) and delete the deployment. */
export const DELETE = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
try {
await requestDelete((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/start">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "running");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/stop">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "stopped");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createDeployment, DeploymentBody, DeploymentError, listDeployments } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listDeployments()));
/** Create a deployment; `start: true` starts it right away. */
export const POST = withAuth(async (req) => {
try {
const body = DeploymentBody.extend({ start: z.boolean().default(true) }).parse(await req.json());
return NextResponse.json(await createDeployment(body, body.start), { status: 201 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});