"use client"; import { BoxesIcon, CheckIcon, SearchIcon, TerminalIcon } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useState } from "react"; import { toast } from "sonner"; import { ArgsEditor } from "@/components/args-editor"; import { CopyButton } from "@/components/copy-button"; import { FileRoleBadge } from "@/components/labels"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { NativeSelect } from "@/components/ui/native-select"; import type { DeploymentOptions, HardwareGpu, HostGpu, RuntimeAccelerator, RuntimeEngine, } from "@/lib/db/schema"; import type { ModelCandidates } from "@/lib/deploy-candidates"; import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, estimateVramMb, renderCommand, } from "@/lib/deploy-command"; import { argsToRows, rowsToArgs } from "@/lib/extra-args"; import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared"; 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; extraArgs: string[]; accelerator: RuntimeAccelerator; }; export type FormModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates; }; export type FormHost = { cpus: number | null; memoryBytes: number | null; cpuFeatures: string[]; nvidia: boolean; gpus: HostGpu[]; /** All GPUs on the host with Settings → Hardware applied (Intel/AMD VRAM for the estimate). */ hardwareGpus: HardwareGpu[]; } | null; export type FormInitial = { id?: string; name: string; runtimeId: string; modelId: string; options: DeploymentOptions; cpus: number | null; memoryMb: number | null; hostPort: number | null; }; const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768]; const KV_TYPES = ["f16", "q8_0", "q4_0"]; const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null; /** Like intOrNull, but 0 and -1 are meaningful (e.g. --cache-ram 0 = off). */ const intOrNullSigned = (s: string) => s.trim() === "" || !Number.isFinite(Number(s)) ? null : Math.round(Number(s)); /** Default prompt cache for new llama.cpp deployments (llama-server's own default is 8 GiB). */ const DEFAULT_CACHE_RAM_MB = 1024; 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 ( {step} {title} {description && {description}} {children} ); } /** A titled block of related options inside the launch options card. */ function Group({ title, description, children, }: { title: string; description?: string; children: React.ReactNode; }) { return (

{title}

{description && (

{description}

)}
{children}
); } /** `flag`: the command-line flag the field sets, shown next to the label. */ function Field({ label, flag, hint, children, htmlFor, wide, }: { label: string; flag?: string; hint?: React.ReactNode; children: React.ReactNode; htmlFor?: string; wide?: boolean; }) { return (
{flag && ( {flag} )}
{children} {hint &&

{hint}

}
); } /** Pick runtime → model and files → launch options. Used for "New deployment" and "Edit". */ export function DeploymentForm({ runtimes, models, host, apiKeyCount, initial, }: { runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number; initial?: FormInitial; }) { const router = useRouter(); const editing = !!initial?.id; const [runtimeId, setRuntimeId] = useState( initial?.runtimeId ?? runtimes.find((r) => r.imageState === "present")?.id ?? "", ); const runtime = runtimes.find((r) => r.id === runtimeId) ?? null; const engine = runtime?.engine ?? "llama.cpp"; const accelerator: RuntimeAccelerator = runtime?.accelerator ?? "cpu"; const gpu = accelerator !== "cpu"; const [query, setQuery] = useState(""); const [modelId, setModelId] = useState(initial?.modelId ?? ""); const servable = models.filter((m) => engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm, ); const shown = servable.filter((m) => m.repoId.toLowerCase().includes(query.trim().toLowerCase()), ); const model = servable.find((m) => m.id === modelId) ?? null; const o = initial?.options; const [modelFile, setModelFile] = useState(o?.modelFile ?? ""); const [mmproj, setMmproj] = useState(o?.mmproj ?? ""); const [draftFile, setDraftFile] = useState(o?.draftFile ?? ""); const [name, setName] = useState(initial?.name ?? ""); const [contextSize, setContextSize] = useState( String(o?.contextSize ?? 4096), ); const [threads, setThreads] = useState( o?.threads != null ? String(o.threads) : "", ); const [parallel, setParallel] = useState( o?.parallel != null ? String(o.parallel) : "1", ); const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? ""); const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? ""); const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? ""); const [webui, setWebui] = useState(o?.webui !== false); const [requireApiKey, setRequireApiKey] = useState(!!o?.requireApiKey); const [batchSize, setBatchSize] = useState( o?.batchSize != null ? String(o.batchSize) : "", ); const [ubatchSize, setUbatchSize] = useState( o?.ubatchSize != null ? String(o.ubatchSize) : "", ); const [dtype, setDtype] = useState(o?.dtype ?? ""); const [maxNumSeqs, setMaxNumSeqs] = useState( o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "", ); const [kvCacheGb, setKvCacheGb] = useState( o?.kvCacheGb != null ? String(o.kvCacheGb) : "", ); const [cacheRam, setCacheRam] = useState( o ? o.cacheRamMb != null ? String(o.cacheRamMb) : "" : String(DEFAULT_CACHE_RAM_MB), ); const [gpuIds, setGpuIds] = useState(o?.gpus ?? []); const [gpuLayers, setGpuLayers] = useState(o?.gpuLayers ?? "auto"); const [splitMode, setSplitMode] = useState(o?.splitMode ?? ""); const [tensorSplit, setTensorSplit] = useState(o?.tensorSplit ?? ""); const [cpuMoe, setCpuMoe] = useState(!!o?.cpuMoe); const [nCpuMoe, setNCpuMoe] = useState( o?.nCpuMoe != null ? String(o.nCpuMoe) : "", ); const [tensorParallel, setTensorParallel] = useState( o?.tensorParallel != null ? String(o.tensorParallel) : "", ); const [gpuMemUtil, setGpuMemUtil] = useState( o?.gpuMemoryUtilization != null ? String(o.gpuMemoryUtilization) : "", ); const [argRows, setArgRows] = useState(() => argsToRows(o?.extraArgs ?? [])); const [cpus, setCpus] = useState( initial?.cpus != null ? String(initial.cpus) : "", ); const [memoryMb, setMemoryMb] = useState( initial?.memoryMb != null ? String(initial.memoryMb) : "", ); const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb); const [hostPort, setHostPort] = useState( initial?.hostPort != null ? String(initial.hostPort) : "", ); const [saving, setSaving] = useState(false); function pickModel(m: FormModel) { setModelId(m.id); const first = m.candidates.gguf[0]; setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : ""); setMmproj(m.candidates.mmproj[0]?.path ?? ""); setDraftFile(""); if (!editing) setName( `${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim(), ); } const options: DeploymentOptions = { modelFile: engine === "llama.cpp" ? modelFile : "", mmproj: engine === "llama.cpp" && mmproj ? mmproj : null, draftFile: engine === "llama.cpp" && draftFile ? draftFile : null, draftType: model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null, contextSize: intOrNull(contextSize) ?? 4096, threads: intOrNull(threads), parallel: intOrNull(parallel), batchSize: engine === "llama.cpp" ? intOrNull(batchSize) : null, ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null, cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null, cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null, flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null, webui: engine === "llama.cpp" ? webui : null, requireApiKey, dtype: engine === "vllm" && dtype ? dtype : null, maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null, kvCacheGb: engine === "vllm" && !gpu ? numOrNull(kvCacheGb) : null, cacheRamMb: engine === "llama.cpp" ? intOrNullSigned(cacheRam) : null, gpus: accelerator === "nvidia" && gpuIds.length ? gpuIds : null, gpuLayers: gpu && engine === "llama.cpp" && gpuLayers !== "auto" ? gpuLayers : null, splitMode: gpu && engine === "llama.cpp" && splitMode ? (splitMode as "none" | "layer" | "row" | "tensor") : null, tensorSplit: gpu && engine === "llama.cpp" && tensorSplit.trim() ? tensorSplit.trim() : null, cpuMoe: gpu && engine === "llama.cpp" ? cpuMoe : null, nCpuMoe: gpu && engine === "llama.cpp" && !cpuMoe ? intOrNull(nCpuMoe) : null, tensorParallel: gpu && engine === "vllm" ? intOrNull(tensorParallel) : null, gpuMemoryUtilization: gpu && engine === "vllm" ? numOrNull(gpuMemUtil) : null, extraArgs: rowsToArgs(argRows), }; const fileBytes = model ? engine === "llama.cpp" ? (model.candidates.gguf.find((g) => g.path === modelFile)?.size ?? 0) + (model.candidates.mmproj.find((g) => g.path === mmproj)?.size ?? 0) + (model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0) : (model.candidates.vllm?.size ?? 0) : 0; const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, { ...options, accelerator, }) : null; const hostGpus = host?.gpus ?? []; const chosenGpus = gpuIds.length ? hostGpus.filter((g) => gpuIds.includes(g.uuid)) : hostGpus; const vramMb = chosenGpus.reduce((s, g) => s + g.memoryMb, 0); // Intel/AMD GPUs come in as /dev/dri: all of them, VRAM as detected (or set in Settings → Hardware). const driGpus = (host?.hardwareGpus ?? []).filter((g) => (accelerator === "rocm" ? g.vendor === "amd" : g.vendor === "intel" || g.vendor === "amd")); const gpuVramMb = accelerator === "nvidia" ? vramMb || null : driGpus.some((g) => g.vramMb) ? driGpus.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null; const vramEstimate = model && gpu ? estimateVramMb(fileBytes, options.contextSize, engine, options, gpuVramMb) : 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, accelerator, }, apiKeys: Array.from( { length: apiKeyCount }, () => API_KEY_PLACEHOLDER, ), }), ) : null; const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16"); async function submit(start: boolean) { if (!runtime || !model) return; setSaving(true); try { const body = { name: name.trim() || model.repoId, runtimeId: runtime.id, modelId: model.id, options, cpus: numOrNull(cpus), memoryMb: memory, hostPort: intOrNull(hostPort), start, }; const res = await fetch( editing ? `/api/deployments/${initial!.id}` : "/api/deployments", { method: editing ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }, ); const json = await res.json().catch(() => ({})); if (!res.ok) { toast.error(json.error?.message ?? `Could not save (${res.status})`); return; } const id = editing ? initial!.id : json.id; if (editing && start) await fetch(`/api/deployments/${id}/start`, { method: "POST" }); toast.success(start ? "Deployment starting" : "Deployment saved"); router.push(`/deployments/${id}`); router.refresh(); } finally { setSaving(false); } } return (
{runtimes.length === 0 ? (

No runtimes yet.{" "} Add one in Settings .

) : (
{runtimes.map((r) => { const ready = r.imageState === "present"; return ( ); })}
)} {runtimes.some((r) => r.imageState !== "present") && (

Runtimes whose image isn't pulled yet can't be picked.{" "} Pull them in Settings .

)}
{runtime && (
{servable.length === 0 ? (

No downloaded model fits this runtime.{" "} Add one in the library {engine === "vllm" ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)." : "."}

) : ( <> {servable.length > 6 && (
setQuery(e.target.value)} placeholder="Search models…" className="pl-8" />
)}
{shown.map((m) => ( ))}
{model && engine === "llama.cpp" && (
{model.candidates.gguf.map((g) => ( ))}
setMmproj(e.target.value)} disabled={model.candidates.mmproj.length === 0} > {model.candidates.mmproj.map((m) => ( ))} setDraftFile(e.target.value)} disabled={model.candidates.drafts.length === 0} > {model.candidates.drafts.map((d) => ( ))}
)} {model && (
{[modelFile, mmproj, draftFile].filter(Boolean).map((p) => ( ))} {formatBytes(fileBytes)} of model files
)} )}
)} {runtime && model && (
setName(e.target.value)} maxLength={80} /> setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" /> {engine === "llama.cpp" && ( )}
setContextSize(e.target.value.replace(/\D/g, "")) } inputMode="numeric" className="w-28" /> {CONTEXT_PRESETS.map((c) => ( ))}
{engine === "vllm" ? ( setMaxNumSeqs(e.target.value.replace(/\D/g, "")) } inputMode="numeric" placeholder="default" /> ) : ( setParallel(e.target.value.replace(/\D/g, "")) } inputMode="numeric" placeholder="auto" /> )}
{gpu && ( {accelerator === "nvidia" && (
{!host?.nvidia ? (

Docker on this host has no NVIDIA runtime. Install the NVIDIA Container Toolkit, then restart the worker.

) : hostGpus.length === 0 ? (

No GPUs detected yet; the deployment gets all of them.

) : (
{hostGpus.map((g) => ( ))}

{gpuIds.length === 0 ? "All GPUs" : `${gpuIds.length} of ${hostGpus.length}`}{" "} · {formatBytes(vramMb * 2 ** 20)} VRAM {fileBytes > 0 && ` · model files ${formatBytes(fileBytes)}`}

)}
)} {accelerator !== "nvidia" && driGpus.length > 0 && (

{driGpus.map((g) => `${g.name ?? "GPU"}${g.vramMb ? ` (${formatBytes(g.vramMb * 2 ** 20)})` : ""}`).join(", ")} via /dev/dri

)} {model && (

gpuVramMb ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground"}`}> {vramEstimate == null ? "VRAM need: depends on how many layers/experts go to the GPU." : `VRAM need, roughly: ${formatBytes(vramEstimate * 2 ** 20)}${gpuVramMb ? ` of ${formatBytes(gpuVramMb * 2 ** 20)}` : ""}${ engine === "vllm" ? " (vLLM reserves its GPU memory share up front)" : " (weights, KV cache, compute buffers)" }${gpuVramMb != null && vramEstimate > gpuVramMb ? ". Doesn't fit: lower the context, quantize the KV cache or offload fewer layers." : ""}`}

)} {engine === "llama.cpp" ? ( <>
setGpuLayers( e.target.value === "n" ? "20" : e.target.value, ) } > {gpuLayers !== "auto" && gpuLayers !== "all" && ( setGpuLayers( e.target.value.replace(/\D/g, "") || "0", ) } inputMode="numeric" className="w-20" aria-label="Number of GPU layers" /> )}
setSplitMode(e.target.value)} > setTensorSplit(e.target.value.replace(/[^\d.,]/g, "")) } placeholder="even" />
{ setCpuMoe(e.target.value === "all"); if (e.target.value === "") setNCpuMoe(""); if (e.target.value === "n" && !nCpuMoe) setNCpuMoe("10"); }} > {!cpuMoe && nCpuMoe !== "" && ( setNCpuMoe(e.target.value.replace(/\D/g, "")) } inputMode="numeric" className="w-20" aria-label="Layers with MoE experts in RAM" /> )}
) : ( <> setTensorParallel(e.target.value.replace(/\D/g, "")) } inputMode="numeric" placeholder={String(Math.max(1, chosenGpus.length))} /> setGpuMemUtil(e.target.value.replace(/[^\d.]/g, "")) } inputMode="decimal" placeholder="0.9" /> )}
)} {engine === "llama.cpp" ? ( setThreads(e.target.value.replace(/\D/g, "")) } inputMode="numeric" placeholder="auto" /> setFlashAttn(e.target.value)} > setBatchSize(e.target.value.replace(/\D/g, "")) } inputMode="numeric" placeholder="2048" /> setUbatchSize(e.target.value.replace(/\D/g, "")) } inputMode="numeric" placeholder="512" /> ) : ( setDtype(e.target.value)} > )} {engine === "llama.cpp" ? ( <> setCacheTypeK(e.target.value)} > {KV_TYPES.filter((t) => t !== "f16").map((t) => ( ))} setCacheTypeV(e.target.value)} > {KV_TYPES.filter((t) => t !== "f16").map((t) => ( ))} setCacheRam(e.target.value.replace(/[^\d-]/g, "")) } inputMode="numeric" placeholder="8192" /> ) : gpu ? (

On a GPU, vLLM sizes the KV cache from the GPU memory share above.

) : ( setKvCacheGb(e.target.value.replace(/[^\d.]/g, "")) } inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} /> )}
setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" /> Estimate:{" "} {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"} {host?.memoryBytes ? ` · host: ${formatBytes(host.memoryBytes)}` : ""} {memoryTouched && ( )} } > { setMemoryTouched(true); setMemoryMb(e.target.value.replace(/\D/g, "")); }} inputMode="numeric" />
)} {runtime && model && (
{preview && (
                
                {preview}
              
)}
)}
); }