Deployments: API keys, deploy from the library, reorganized form

- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 12:28:25 +02:00
1 parent 66e6a8c4f7
commit ea1f18cc74
32 files changed
+2478 -183

No files matched your search

+12
View File
@@ -28,9 +28,21 @@ step 1 (Hugging Face downloader) is released as a minor version.
traceback), followed by the last lines of output.
- A deployment's vLLM data type replaces the runtime's `--dtype` instead of repeating the flag.
- Models and runtimes used by a deployment can't be deleted until the deployment is.
- **API keys** (Settings → API keys): add generated or own keys, show and copy them again later.
A deployment with "Require an API key" accepts any of them (`LLAMA_API_KEY`, `VLLM_API_KEY` or
`--api-key` for several vLLM keys); the values are masked in the shown command and in the log, and
Kaname's own "Try it" chat sends one. Key changes apply when a deployment restarts.
- **Deploy from the library:** a "Deploy" button in the library and on the model page opens a new
deployment with the model and a fitting runtime preselected. The library and the model page link
to the deployments that use a model.
- Deployment form reorganized: launch options in groups (General, Context, Performance, KV cache,
Resources, Extra arguments) with each field's flag next to its label, the command in its own step,
and extra arguments as flag/value rows with "+ Add argument" (also in the runtime form).
### Fixed
- Dropdowns were unreadable in dark mode (white option list with light text): native controls now
follow the theme.
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
written (Drizzle queries only run when awaited).
+8
View File
@@ -0,0 +1,8 @@
CREATE TABLE `api_keys` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`key` text NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_keys_key_unique` ON `api_keys` (`key`);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -85,6 +85,13 @@
"when": 1791278463453,
"tag": "0011_deployments",
"breakpoints": true
},
{
"idx": 12,
"version": "6",
"when": 1791281615301,
"tag": "0012_api_keys",
"breakpoints": true
}
]
}
+44 -1
View File
@@ -9,6 +9,8 @@ import {
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
PlusIcon,
RocketIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
@@ -17,12 +19,14 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
@@ -97,13 +101,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, recentJobs] = await Promise.all([
const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
deploymentsByModel(),
listDeployableModels(),
]);
const modelDeployments = byModel.get(model.id) ?? [];
const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
@@ -143,6 +151,15 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</span>
)}
<div className="ml-auto flex items-center gap-2">
{canDeploy && (
<Link
href={`/deployments/new?model=${model.id}`}
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
>
<RocketIcon />
Deploy
</Link>
)}
<DeleteModelButton
id={model.id}
repoId={model.repoId}
@@ -287,6 +304,32 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
</SideCard>
{(modelDeployments.length > 0 || canDeploy) && (
<SideCard title="Deployments" icon={RocketIcon}>
<div className="flex flex-col gap-2">
{modelDeployments.length === 0 ? (
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
) : (
modelDeployments.map((d) => (
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{d.name}</span>
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
</span>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</Link>
))
)}
{canDeploy && (
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
<PlusIcon className="size-3.5" />
New deployment
</Link>
)}
</div>
</SideCard>
)}
<SideCard title="Local copy" icon={ListChecksIcon}>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Selection</dt>
@@ -3,7 +3,7 @@
import { ExternalLinkIcon, 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 { useEffect, useRef, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LocalTime } from "@/components/local-time";
@@ -21,6 +21,7 @@ import {
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
@@ -67,15 +68,9 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
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 hostname = useHostname();
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
// llama-server's built-in chat UI, served at / on the same port.
const webUi = d.engine === "llama.cpp" && d.options.webui !== false && d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/` : null;
const webUi = webUiUrl(d, hostname);
return (
<div className="flex flex-col gap-4">
@@ -218,6 +213,16 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
{d.options.requireApiKey && (
<>
{" "}
Requires one of the{" "}
<Link href="/settings/api-keys" className="underline">
API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.
</>
)}
</span>
</CardContent>
</Card>
+195 -111
View File
@@ -1,19 +1,23 @@
"use client";
import { BoxesIcon, CheckIcon, CpuIcon, SearchIcon } from "lucide-react";
import { BoxesIcon, CheckIcon, SearchIcon, TerminalIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { ArgsEditor } from "@/components/args-editor";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
import { buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
@@ -42,8 +46,6 @@ export type FormInitial = {
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;
@@ -63,10 +65,41 @@ function Section({ step, title, description, children }: { step: number; title:
);
}
function Field({ label, hint, children, htmlFor }: { label: string; hint?: React.ReactNode; children: React.ReactNode; htmlFor?: string }) {
/** A titled block of related options inside the launch options card. */
function Group({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={htmlFor}>{label}</Label>
<div className="grid gap-3 border-t pt-5 first:border-t-0 first:pt-0 md:grid-cols-[11rem_1fr] md:gap-6">
<div className="flex flex-col gap-0.5">
<h3 className="text-sm font-medium">{title}</h3>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
</div>
<div className="grid content-start gap-4 sm:grid-cols-2">{children}</div>
</div>
);
}
/** `flag`: the command-line flag the field sets, shown next to the label. */
function Field({
label,
flag,
hint,
children,
htmlFor,
wide,
}: {
label: string;
flag?: string;
hint?: React.ReactNode;
children: React.ReactNode;
htmlFor?: string;
wide?: boolean;
}) {
return (
<div className={cn("flex flex-col gap-1.5", wide && "sm:col-span-2")}>
<div className="flex items-baseline justify-between gap-2">
<Label htmlFor={htmlFor}>{label}</Label>
{flag && <code className="font-mono text-[11px] text-muted-foreground">{flag}</code>}
</div>
{children}
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
@@ -78,11 +111,13 @@ export function DeploymentForm({
runtimes,
models,
host,
apiKeyCount,
initial,
}: {
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
apiKeyCount: number;
initial?: FormInitial;
}) {
const router = useRouter();
@@ -109,12 +144,13 @@ export function DeploymentForm({
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 [extraArgs, setExtraArgs] = useState((o?.extraArgs ?? []).join("\n"));
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);
@@ -144,13 +180,11 @@ export function DeploymentForm({
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
webui: engine === "llama.cpp" ? webui : null,
requireApiKey,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
extraArgs: extraArgs
.split("\n")
.map((a) => a.trim())
.filter(Boolean),
extraArgs: rowsToArgs(argRows),
};
const fileBytes = model
@@ -163,7 +197,13 @@ export function DeploymentForm({
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;
runtime && model ? renderCommand(runtime.image, buildCommand({
engine,
options,
model,
runtime: { env: runtime.env, extraArgs: runtime.extraArgs },
apiKeys: Array.from({ length: apiKeyCount }, () => API_KEY_PLACEHOLDER),
})) : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
@@ -302,7 +342,7 @@ export function DeploymentForm({
{model && engine === "llama.cpp" && (
<div className="grid gap-4 md:grid-cols-3">
<Field label="Model file">
<Field label="Model file" flag="-m">
<div className="flex flex-col gap-1">
{model.candidates.gguf.map((g) => (
<label key={g.path} className={cn("flex cursor-pointer items-center gap-2 rounded-md border px-2 py-1.5 text-xs", modelFile === g.path && "border-primary bg-primary/5")}>
@@ -315,21 +355,22 @@ export function DeploymentForm({
))}
</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}>
<Field label="Vision (mmproj)" flag="--mmproj" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<NativeSelect value={mmproj} onChange={(e) => setMmproj(e.target.value)} disabled={model.candidates.mmproj.length === 0}>
<option value="">None</option>
{model.candidates.mmproj.map((m) => (
<option key={m.path} value={m.path}>
{m.path} ({formatBytes(m.size)})
</option>
))}
</select>
</NativeSelect>
</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."}
flag="-md"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "Faster generation with an MTP head or draft model."}
>
<select value={draftFile} onChange={(e) => setDraftFile(e.target.value)} className={selectClass} disabled={model.candidates.drafts.length === 0}>
<NativeSelect value={draftFile} onChange={(e) => setDraftFile(e.target.value)} disabled={model.candidates.drafts.length === 0}>
<option value="">Off</option>
{model.candidates.drafts.map((d) => (
<option key={d.path} value={d.path}>
@@ -337,7 +378,7 @@ export function DeploymentForm({
{d.path} ({formatBytes(d.size)})
</option>
))}
</select>
</NativeSelect>
</Field>
</div>
)}
@@ -358,106 +399,152 @@ export function DeploymentForm({
{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">
<Group title="General" description="Name and how to reach the server.">
<Field label="Name" htmlFor="d-name">
<Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} />
</Field>
<Field label="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>
<Field label="Host port" htmlFor="d-port" hint={`Publishes container port ${ENGINE_PORT[engine]}; empty: only reachable inside Docker.`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={requireApiKey} onCheckedChange={(v) => setRequireApiKey(v === true)} className="mt-0.5" disabled={apiKeyCount === 0 && !requireApiKey} />
<span className="flex flex-col gap-0.5">
<span>Require an API key</span>
<span className="text-xs text-muted-foreground">
{apiKeyCount === 0 ? (
<>
No keys yet.{" "}
<Link href="/settings/api-keys" className="underline">
Add one in Settings
</Link>
.
</>
) : (
<>
Accepts any of the {apiKeyCount} key{apiKeyCount === 1 ? "" : "s"} from{" "}
<Link href="/settings/api-keys" className="underline">
Settings → API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.{engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
</>
)}
</span>
</span>
</label>
{engine === "llama.cpp" && (
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={webui} onCheckedChange={(v) => setWebui(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>Serve the llama.cpp web UI</span>
<span className="text-xs text-muted-foreground">
{webui
? hostPort
? `Opens at http://<server>:${hostPort}/ (no login on that port).`
: "Set a host port to open it."
: "Off: passes --no-webui; the API keeps working."}
</span>
</span>
</label>
)}
</Group>
<Group title="Context" description="How much text the model sees and how many requests run at once.">
<Field label="Context size (tokens)" flag={engine === "vllm" ? "--max-model-len" : "-c"} htmlFor="d-ctx" wide>
<div className="flex flex-wrap items-center gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-28" />
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c / 1024}k
</Button>
))}
</div>
</Field>
<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" ? (
{engine === "vllm" ? (
<Field label="Max concurrent sequences" flag="--max-num-seqs" htmlFor="d-par">
<Input id="d-par" value={maxNumSeqs} onChange={(e) => setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
) : (
</Field>
) : (
<Field label="Parallel slots" flag="-np" htmlFor="d-par" hint="The context is split between slots.">
<Input id="d-par" value={parallel} onChange={(e) => setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
)}
</Field>
</div>
</Field>
)}
</Group>
{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"}>
<Group title="Performance" description="CPU threads and prompt processing.">
<Field label="Threads" flag="-t / -tb" htmlFor="d-thr" hint={host?.cpus ? `Host has ${host.cpus} threads.` : undefined}>
<Input id="d-thr" value={threads} onChange={(e) => setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
<Field label="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>
<Field label="Flash attention" flag="-fa" htmlFor="d-fa">
<NativeSelect id="d-fa" value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)}>
<option value="">auto</option>
<option value="on">on</option>
<option value="off">off</option>
</select>
</NativeSelect>
</Field>
<Field label="Web UI" hint={webui ? (hostPort ? `Opens at http://<server>:${hostPort}/` : "Needs a host port to open it (below).") : "--no-webui"}>
<select value={webui ? "on" : "off"} onChange={(e) => setWebui(e.target.value === "on")} className={selectClass}>
<option value="on">on</option>
<option value="off">off</option>
</select>
<Field label="Batch size" flag="-b" htmlFor="d-b">
<Input id="d-b" value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" />
</Field>
<Field label="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 label="Micro-batch size" flag="-ub" htmlFor="d-ub">
<Input id="d-ub" value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" />
</Field>
</div>
</Group>
) : (
<div className="grid gap-4 md:grid-cols-3">
<Group title="Performance" description="vLLM binds its CPU threads itself; limit cores under Resources.">
<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"}
flag="--dtype"
htmlFor="d-dtype"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster." : "Overrides the runtime's default."}
>
<select value={dtype} onChange={(e) => setDtype(e.target.value)} className={selectClass}>
<NativeSelect id="d-dtype" value={dtype} onChange={(e) => setDtype(e.target.value)}>
<option value="">runtime default</option>
<option value="bfloat16">bfloat16</option>
<option value="float32">float32</option>
<option value="float16">float16</option>
<option value="auto">auto</option>
</select>
</NativeSelect>
</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>
</Group>
)}
<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"}>
<Group title="KV cache" description="Memory for the context of running requests.">
{engine === "llama.cpp" ? (
<>
<Field label="K type" flag="-ctk" htmlFor="d-ctk" hint="q8_0 halves the memory.">
<NativeSelect id="d-ctk" value={cacheTypeK} onChange={(e) => setCacheTypeK(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
<Field label="V type" flag="-ctv" htmlFor="d-ctv">
<NativeSelect id="d-ctv" value={cacheTypeV} onChange={(e) => setCacheTypeV(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
</>
) : (
<Field label="KV cache size (GiB)" flag="VLLM_CPU_KVCACHE_SPACE" htmlFor="d-kv" hint="Reserved up front; must fit in the memory limit.">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
)}
</Group>
<Group title="Resources" description="Container limits.">
<Field label="CPU cores" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus}).` : "Empty: no limit."}>
<Input id="d-cpus" value={cpus} onChange={(e) => setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
</Field>
<Field
label="Memory limit (MiB)"
label="Memory (MiB)"
htmlFor="d-mem"
hint={
<>
@@ -481,35 +568,32 @@ export function DeploymentForm({
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>
</Group>
<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>
<Group
title="Extra arguments"
description={`Any other ${engine === "vllm" ? "vllm serve" : "llama-server"} flag. Added after the runtime's own arguments.`}
>
<div className="sm:col-span-2">
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--enforce-eager", value: "value (optional)" } : { flag: "--temp", value: "0.7" }} />
</div>
</Group>
</Section>
)}
{runtime && model && (
<Section step={4} title="Command" description="What Kaname runs, including the runtime's environment and arguments.">
{preview && (
<div className="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>
<div className="relative">
<pre className="overflow-x-auto rounded-lg bg-muted/60 py-2.5 pr-12 pl-3 font-mono text-xs break-all whitespace-pre-wrap">
<TerminalIcon className="mr-1.5 inline size-3.5 align-[-2px] text-muted-foreground" />
{preview}
</pre>
<div className="absolute top-1.5 right-1.5">
<CopyButton value={preview} label="Copy command" />
</div>
<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
+23 -13
View File
@@ -1,11 +1,12 @@
"use client";
import { PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import { ExternalLinkIcon, PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
@@ -23,6 +24,7 @@ const isActive = (r: Row) => r.desiredState === "running" || r.state === "starti
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
const hostname = useHostname();
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
async function reload() {
@@ -77,17 +79,25 @@ export function DeploymentList({ rows: initial }: { rows: Row[] }) {
: `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>
)}
<span className="flex items-center gap-1.5">
{r.state === "running" && webUiUrl(r, hostname) && (
<a href={webUiUrl(r, hostname)!} target="_blank" rel="noreferrer" className={buttonVariants({ size: "xs", variant: "outline" })}>
<ExternalLinkIcon />
Web UI
</a>
)}
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
</span>
</div>
</Card>
);
+5 -3
View File
@@ -1,14 +1,16 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost }> {
const [runtimes, models, docker] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo()]);
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
apiKeyCount: keys.length,
};
}
+6 -3
View File
@@ -1,16 +1,19 @@
import type { Metadata } from "next";
import { deployPreset } from "@/lib/deployments";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
export default async function NewDeploymentPage() {
const data = await formData();
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
const { model } = await searchParams;
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} />
<DeploymentForm {...data} initial={preset ?? undefined} />
</div>
);
}
+36 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
@@ -10,7 +10,7 @@ import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -19,6 +19,7 @@ import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
@@ -180,6 +181,9 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
<TableHead className="w-24">
<span className="sr-only">Deploy</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -195,6 +199,23 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
<Link
key={d.id}
href={`/deployments/${d.id}`}
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
>
<RocketIcon className="size-3" />
<span className="max-w-40 truncate">{d.name}</span>
<span
className={cn(
"size-1.5 rounded-full",
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
)}
/>
</Link>
))}
{r.tags.map((t) => (
<button
key={t.id}
@@ -236,6 +257,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
</span>
)}
</TableCell>
<TableCell>
{r.deployable && (
<Link
href={`/deployments/new?model=${r.id}`}
className={buttonVariants({ variant: "outline", size: "xs" })}
title="Serve this model with a runtime"
aria-label={`Deploy ${r.repoId}`}
>
<RocketIcon />
Deploy
</Link>
)}
</TableCell>
</TableRow>
);
})}
@@ -0,0 +1,172 @@
"use client";
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { ApiKeyRow } from "@/lib/api-keys";
/** Keys that deployments with "Require an API key" accept. */
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewKeyRow onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">API key &ldquo;{created.name}&rdquo; added. You can show it again from the list.</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.key}</code>
<CopyButton value={created.key} label="Copy API key" />
</div>
</div>
)}
{keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{keys.map((k) => (
<KeyRow key={k.id} apiKey={k} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, key: key.trim() || undefined }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
return;
}
onCreated({ name: json.name, key: json.key });
setName("");
setKey("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
<Input
value={key}
maxLength={256}
disabled={busy}
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
placeholder="Key (empty: generate one)"
aria-label="Key value"
spellCheck={false}
autoComplete="off"
className="font-mono text-xs md:text-xs"
/>
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
<PlusIcon />
Add
</Button>
</form>
);
}
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
const router = useRouter();
const [shown, setShown] = useState<string | null>(null);
async function toggle() {
if (shown) return setShown(null);
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
else setShown(json.key);
}
async function remove() {
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`API key "${apiKey.name}" deleted`);
router.refresh();
}
return (
<div className="flex items-center gap-3 px-4 py-2.5">
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
{shown ? (
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
{shown}
</code>
<CopyButton value={shown} label="Copy API key" />
</span>
) : (
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
)}
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
{shown ? <EyeOffIcon /> : <EyeIcon />}
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
<LocalTime value={apiKey.createdAt} />
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API key &ldquo;{apiKey.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { BoxesIcon, DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
@@ -6,6 +6,7 @@ const SECTIONS = [
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
@@ -1,11 +1,13 @@
"use client";
import { useState } from "react";
import { ArgsEditor } from "@/components/args-editor";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
@@ -34,7 +36,7 @@ export function RuntimeForm({
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 [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
const [numa, setNuma] = useState(!!initial.numaTuning);
@@ -51,7 +53,7 @@ export function RuntimeForm({
image,
description,
env: parseEnvLines(envText),
extraArgs: argsText.split("\n"),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
shmSizeMb: shm.trim() ? Number(shm) : null,
numaTuning: numa,
@@ -117,31 +119,22 @@ export function RuntimeForm({
<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 className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label>Extra arguments</Label>
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--dtype", value: "bfloat16" } : { flag: "--temp", value: "0.7" }} />
<p className="text-xs text-muted-foreground">Added to every deployment&apos;s command; a deployment can override them.</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
+29
View File
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** The key's value ("show key" in Settings). */
export const GET = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Remove a key; running deployments keep accepting it until they restart. */
export const DELETE = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteApiKey(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** Keys without their values (only the last characters). */
export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
/** Add a key (generated when `key` is missing); the response carries the full key once. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+5 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { apiKeyValues } from "@/lib/api-keys";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
@@ -21,9 +22,11 @@ export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
// Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest.
const [key] = d.options.requireApiKey ? await apiKeyValues() : [];
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
@@ -31,6 +34,7 @@ export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys.");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
+7
View File
@@ -127,4 +127,11 @@
html {
@apply font-sans;
}
/* Native controls (select popups, scrollbars, date pickers) follow the theme. */
.dark {
color-scheme: dark;
}
option {
@apply bg-popover text-popover-foreground;
}
}
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ArgRow } from "@/lib/extra-args";
const GENERIC = { flag: "--flag", value: "value (optional)" };
/** Extra command-line arguments as flag/value rows (controlled). `placeholder` is the first row's example. */
export function ArgsEditor({
rows,
onChange,
placeholder = GENERIC,
addLabel = "Add argument",
}: {
rows: ArgRow[];
onChange: (rows: ArgRow[]) => void;
placeholder?: { flag: string; value: string };
addLabel?: string;
}) {
const set = (i: number, patch: Partial<ArgRow>) => onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const single = (s: string) => s.replace(/[\r\n]/g, "");
return (
<div className="flex flex-col gap-1.5">
{rows.map((r, i) => (
<div key={i} className="flex items-center gap-1.5">
<Input
value={r.flag}
onChange={(e) => set(i, { flag: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).flag}
spellCheck={false}
aria-label={`Argument ${i + 1} flag`}
className="font-mono text-xs md:text-xs"
/>
<Input
value={r.value}
onChange={(e) => set(i, { value: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).value}
spellCheck={false}
aria-label={`Argument ${i + 1} value`}
className="font-mono text-xs md:text-xs"
/>
<Button type="button" variant="ghost" size="icon-sm" aria-label={`Remove argument ${i + 1}`} onClick={() => onChange(rows.filter((_, j) => j !== i))}>
<XIcon />
</Button>
</div>
))}
<Button type="button" variant="outline" size="sm" className="self-start" onClick={() => onChange([...rows, { flag: "", value: "" }])}>
<PlusIcon />
{addLabel}
</Button>
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { ChevronDownIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
/** A native <select> styled like Input; the option list follows the theme via `color-scheme`. */
function NativeSelect({ className, children, ...props }: React.ComponentProps<"select">) {
return (
<div className={cn("relative w-full", className)}>
<select
data-slot="native-select"
className="h-8 w-full min-w-0 appearance-none rounded-lg border border-input bg-transparent py-1 pr-8 pl-2.5 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"
{...props}
>
{children}
</select>
<ChevronDownIcon className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
</div>
);
}
export { NativeSelect };
+5 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { BoxesIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -71,6 +71,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<BoxesIcon />
Runtimes
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
<KeyRoundIcon />
API keys
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
+20
View File
@@ -0,0 +1,20 @@
"use client";
import { useSyncExternalStore } from "react";
/** The browser's host name; null while rendering on the server, so hydration matches. */
export function useHostname(): string | null {
return useSyncExternalStore(
() => () => {},
() => window.location.hostname,
() => null,
);
}
/** llama-server's built-in chat UI, served at / on the published host port. */
export function webUiUrl(
d: { engine: string; hostPort: number | null; options: { webui?: boolean | null } },
hostname: string | null,
): string | null {
return d.engine === "llama.cpp" && d.options.webui !== false && d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/` : null;
}
+67
View File
@@ -0,0 +1,67 @@
import "server-only";
import { randomBytes } from "node:crypto";
import { asc, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { apiKeys } from "@/lib/db/schema";
export class ApiKeyError extends Error {
constructor(
public code: "invalid" | "not_found" | "conflict",
message: string,
public status: number,
) {
super(message);
}
}
// No whitespace or commas: llama.cpp takes several keys as one comma-separated list.
export const ApiKeyBody = z.object({
name: z.string().trim().min(1).max(80),
key: z
.string()
.trim()
.min(16, "at least 16 characters")
.max(256)
.regex(/^[\x21-\x7e]+$/, "printable characters without spaces")
.refine((k) => !k.includes(","), "no commas")
.optional(),
});
export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`;
/** "…" plus the last 4 characters: enough to tell keys apart without showing them. */
const mask = (key: string) => `…${key.slice(-4)}`;
export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number };
export async function listApiKeys(): Promise<ApiKeyRow[]> {
const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt));
return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() }));
}
/** Returns the full key once, so the user can copy it. */
export async function createApiKey(input: z.infer<typeof ApiKeyBody>) {
const key = input.key ?? generateApiKey();
const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) });
if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409);
const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning();
return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() };
}
export async function deleteApiKey(id: string) {
const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id });
if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404);
}
/** All key values (for runtime containers and Kaname's own requests to them). */
export async function apiKeyValues(): Promise<string[]> {
return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
}
/** One key's value, for "show key" in Settings. */
export async function revealApiKey(id: string): Promise<string> {
const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) });
if (!row) throw new ApiKeyError("not_found", "API key not found.", 404);
return row.key;
}
+13
View File
@@ -451,6 +451,8 @@ export type DeploymentOptions = {
flashAttn?: "auto" | "on" | "off" | null;
/** llama.cpp: serve the built-in web UI at / (llama-server's default; false passes --no-webui). */
webui?: boolean | null;
/** Only accept requests with one of the API keys from Settings → API keys. */
requireApiKey?: boolean | null;
/** vLLM */
dtype?: string | null;
maxNumSeqs?: number | null;
@@ -510,3 +512,14 @@ export const deploymentLogs = sqliteTable(
},
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
);
/**
* API keys that deployments with `requireApiKey` accept. Stored in plain text because the worker
* hands them to the runtime container; never logged or written into a stored command line.
*/
export const apiKeys = sqliteTable("api_keys", {
id: id(),
name: text("name").notNull(),
key: text("key").notNull().unique(),
createdAt: createdAt(),
});
+19 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { buildCommand, renderCommand } from "./deploy-command";
import { buildCommand, redactCommand, renderCommand } from "./deploy-command";
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
@@ -65,4 +65,22 @@ describe("buildCommand", () => {
assert.ok(!args().includes("--no-webui") && !args(true).includes("--no-webui"));
assert.ok(args(false).includes("--no-webui"));
});
it("passes API keys via the environment and redacts them", () => {
const base = { model: { repoId: "a/b", localPath: "a/b" }, runtime: { env: {}, extraArgs: [] } };
const opts = { modelFile: "m.gguf", contextSize: 2048, requireApiKey: true, extraArgs: [] };
const llama = buildCommand({ ...base, engine: "llama.cpp", options: opts, apiKeys: ["sk-one-1234567890", "sk-two-1234567890"] });
assert.equal(llama.env.LLAMA_API_KEY, "sk-one-1234567890,sk-two-1234567890");
assert.ok(!llama.args.join(" ").includes("sk-"));
const shown = renderCommand("img", redactCommand(llama, ["sk-one-1234567890", "sk-two-1234567890"]));
assert.ok(!shown.includes("sk-") && shown.includes("<api-key>,<api-key>"));
const one = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["sk-one-1234567890"] });
assert.equal(one.env.VLLM_API_KEY, "sk-one-1234567890");
const two = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["k1-1234567890123456", "k2-1234567890123456"] });
assert.deepEqual(two.args.slice(two.args.indexOf("--api-key"), two.args.indexOf("--api-key") + 3), ["--api-key", "k1-1234567890123456", "k2-1234567890123456"]);
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
assert.equal(off.env.LLAMA_API_KEY, undefined);
});
});
+19 -2
View File
@@ -14,8 +14,13 @@ export type CommandInput = {
options: DeploymentOptions;
model: { repoId: string; localPath: string };
runtime: { env: Record<string, string>; extraArgs: string[] };
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
apiKeys?: string[];
};
/** Stands in for key values in everything Kaname shows or stores. */
export const API_KEY_PLACEHOLDER = "<api-key>";
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
const inModels = (localPath: string, file?: string | null) =>
@@ -34,8 +39,9 @@ function withoutFlag(args: string[], flag: string): string[] {
return out;
}
export function buildCommand({ engine, options: o, model, runtime }: CommandInput): ContainerCommand {
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
const port = ENGINE_PORT[engine];
const keys = o.requireApiKey ? apiKeys : [];
if (engine === "llama.cpp") {
// The image's entrypoint is llama-server, so these are its arguments.
const args = [
@@ -63,12 +69,16 @@ export function buildCommand({ engine, options: o, model, runtime }: CommandInpu
...runtime.extraArgs,
...o.extraArgs,
];
return { args, env: { ...runtime.env }, port };
// Via the environment, not the command line; several keys as one comma-separated list.
const env = { ...runtime.env, ...(keys.length ? { LLAMA_API_KEY: keys.join(",") } : {}) };
return { args, env, port };
}
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
const env = { ...runtime.env };
if (o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
// VLLM_API_KEY holds a single key; more than one needs --api-key.
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
const args = [
inModels(model.localPath, o.modelFile || null),
"--host",
@@ -79,6 +89,7 @@ export function buildCommand({ engine, options: o, model, runtime }: CommandInpu
model.repoId,
...num("--max-model-len", o.contextSize),
...num("--max-num-seqs", o.maxNumSeqs),
...(keys.length > 1 ? ["--api-key", ...keys] : []),
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
...str("--dtype", o.dtype),
@@ -87,6 +98,12 @@ export function buildCommand({ engine, options: o, model, runtime }: CommandInpu
return { args, env, port };
}
/** The command with every key replaced by {@link API_KEY_PLACEHOLDER}. */
export function redactCommand(cmd: ContainerCommand, keys: string[]): ContainerCommand {
const hide = (v: string) => keys.filter(Boolean).reduce((acc, k) => acc.split(k).join(API_KEY_PLACEHOLDER), v);
return { ...cmd, args: cmd.args.map(hide), env: Object.fromEntries(Object.entries(cmd.env).map(([k, v]) => [k, hide(v)])) };
}
/** Shell-style rendering for display ("docker run … image args"). */
export function renderCommand(image: string, cmd: ContainerCommand): string {
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
+48 -1
View File
@@ -2,8 +2,9 @@ import "server-only";
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
import { apiKeys, deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
import { quantGroup } from "@/lib/selection";
export class DeploymentError extends Error {
constructor(
@@ -35,6 +36,7 @@ export const DeploymentBody = z.object({
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
webui: z.boolean().nullable().optional(),
requireApiKey: z.boolean().nullable().optional(),
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
maxNumSeqs: int(1, 1024).nullable().optional(),
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
@@ -92,6 +94,9 @@ async function validate(input: DeploymentInput, selfId?: string): Promise<Deploy
} else {
Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null, webui: null });
}
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
}
if (input.hostPort) {
const clash = await db().query.deployments.findFirst({
columns: { name: true },
@@ -236,3 +241,45 @@ export async function deploymentsUsing(by: { modelId?: string; runtimeId?: strin
),
);
}
export type ModelDeployment = { id: string; name: string; state: DeploymentRow["state"]; desiredState: DeploymentRow["desiredState"]; runtimeName: string };
/** Deployments per model id (for links from the library and model pages). */
export async function deploymentsByModel(): Promise<Map<string, ModelDeployment[]>> {
const rows = await db()
.select({
modelId: deployments.modelId,
id: deployments.id,
name: deployments.name,
state: deployments.state,
desiredState: deployments.desiredState,
runtimeName: runtimes.name,
})
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(isNull(deployments.deleteRequestedAt))
.orderBy(asc(deployments.name));
const out = new Map<string, ModelDeployment[]>();
for (const { modelId, ...d } of rows) out.set(modelId, [...(out.get(modelId) ?? []), d]);
return out;
}
/** Form defaults for "Deploy" from the library: the first runtime with a pulled image that can serve the model. */
export async function deployPreset(modelId: string) {
const model = (await listDeployableModels()).find((m) => m.id === modelId);
if (!model) return null;
const rts = await db().select({ id: runtimes.id, engine: runtimes.engine }).from(runtimes).where(eq(runtimes.imageState, "present")).orderBy(asc(runtimes.createdAt));
const runtime = rts.find((r) => servableBy(model.candidates, r.engine));
if (!runtime) return null;
const gguf = runtime.engine === "llama.cpp" ? model.candidates.gguf[0] : undefined;
const quant = gguf ? quantGroup(gguf.path) : null;
return {
name: `${model.repoId.split("/")[1]}${quant ? ` ${quant}` : ""}`,
runtimeId: runtime.id,
modelId: model.id,
options: { modelFile: gguf?.path ?? "", mmproj: gguf ? (model.candidates.mmproj[0]?.path ?? null) : null, contextSize: 4096, extraArgs: [] },
cpus: null,
memoryMb: null,
hostPort: null,
};
}
+22
View File
@@ -0,0 +1,22 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { argsToRows, rowsToArgs } from "./extra-args";
describe("extra args rows", () => {
it("pairs flags with their values", () => {
const tokens = ["--temp", "0.7", "--no-mmap", "--dtype=bfloat16", "--seed", "-1", "positional"];
const rows = argsToRows(tokens);
assert.deepEqual(rows, [
{ flag: "--temp", value: "0.7" },
{ flag: "--no-mmap", value: "" },
{ flag: "--dtype=bfloat16", value: "" },
{ flag: "--seed", value: "-1" },
{ flag: "", value: "positional" },
]);
assert.deepEqual(rowsToArgs(rows), tokens);
});
it("drops empty rows and trims", () => {
assert.deepEqual(rowsToArgs([{ flag: " --top-k ", value: " 40 " }, { flag: "", value: "" }]), ["--top-k", "40"]);
});
});
+24
View File
@@ -0,0 +1,24 @@
// Extra command-line arguments as editable flag/value rows. Pure; shared by the runtime and
// deployment forms. The stored form stays a token list (one argv entry per item).
export type ArgRow = { flag: string; value: string };
const isFlag = (t: string) => t.startsWith("-") && !/^-\d/.test(t);
/** Tokens → rows: a flag takes the following non-flag token as its value. */
export function argsToRows(tokens: string[]): ArgRow[] {
const rows: ArgRow[] = [];
for (const t of tokens) {
const last = rows.at(-1);
// "--flag=value" stays one token, so it is shown (and passed) exactly as written.
if (!isFlag(t) && last && last.flag && !last.value && !last.flag.includes("=")) last.value = t;
else if (isFlag(t)) rows.push({ flag: t, value: "" });
else rows.push({ flag: "", value: t });
}
return rows;
}
/** Rows → tokens, skipping empty rows. */
export function rowsToArgs(rows: ArgRow[]): string[] {
return rows.flatMap((r) => [r.flag.trim(), r.value.trim()].filter(Boolean));
}
+6
View File
@@ -1,6 +1,7 @@
import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { modelFamilies } from "@/lib/hub/metadata";
import { fileRole } from "@/lib/file-roles";
@@ -52,6 +53,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 }]);
const [byModel, deployable] = await Promise.all([deploymentsByModel(), listDeployableModels()]);
const deployableIds = new Set(deployable.map((m) => m.id));
return rows.map(({ updateDiff, ...r }) => ({
...r,
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
@@ -61,6 +65,8 @@ export async function listLibrary() {
hubTags: r.hubTags ?? [],
quants: [...(quants.get(r.id) ?? [])].sort(),
tags: tagsByModel.get(r.id) ?? [],
deployable: deployableIds.has(r.id),
deployments: byModel.get(r.id) ?? [],
}));
}
+21 -7
View File
@@ -4,10 +4,10 @@
import { stat } from "node:fs/promises";
import { join } from "node:path";
import { and, desc, eq, inArray, lt } from "drizzle-orm";
import { and, asc, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, renderCommand } from "@/lib/deploy-command";
import { apiKeys, deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, redactCommand, renderCommand } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
@@ -40,8 +40,17 @@ const slug = (s: string) =>
const followers = new Map<string, AbortController>();
const pending: { deploymentId: string; stream: LogStream; line: string; ts: Date }[] = [];
// API key values, refreshed every reconcile pass: hidden in every log line (vLLM prints its
// arguments, including --api-key, at startup).
let apiKeySecrets: string[] = [];
async function loadApiKeys(): Promise<string[]> {
apiKeySecrets = (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
return apiKeySecrets;
}
function addLog(deploymentId: string, stream: LogStream, line: string) {
pending.push({ deploymentId, stream, line: sanitizeLine(line, [coreEnv().HF_TOKEN ?? ""]).slice(0, 4000), ts: new Date() });
pending.push({ deploymentId, stream, line: sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...apiKeySecrets]).slice(0, 4000), ts: new Date() });
}
export async function flushDeploymentLogs(): Promise<void> {
@@ -127,7 +136,11 @@ async function start(c: DockerClient, d: Deployment) {
}
}
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime });
const keys = d.options.requireApiKey ? await loadApiKeys() : [];
if (d.options.requireApiKey && keys.length === 0) return fail(d, "This deployment requires an API key, but there are none. Add one under Settings → API keys.");
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime, apiKeys: keys });
// What Kaname shows and stores: never the key values.
const shown = redactCommand(cmd, keys);
const name = `kaname-${slug(d.name)}-${d.id.slice(-6).toLowerCase()}`;
const portKey = `${cmd.port}/tcp`;
const spec = {
@@ -153,7 +166,7 @@ async function start(c: DockerClient, d: Deployment) {
};
addLog(d.id, "system", `Starting ${runtime.name} (${runtime.image})`);
addLog(d.id, "system", `$ ${renderCommand(runtime.image, cmd)}`);
addLog(d.id, "system", `$ ${renderCommand(runtime.image, shown)}`);
try {
await c.removeContainer(name); // leftover from a crash
const created = await c.createContainer(name, spec);
@@ -162,7 +175,7 @@ async function start(c: DockerClient, d: Deployment) {
state: "starting",
containerId: created.Id,
containerName: name,
command: cmd.args,
command: shown.args,
imageId: image.Id,
startedAt: new Date(),
readyAt: null,
@@ -278,6 +291,7 @@ export async function reconcileDeployments(): Promise<void> {
if (!c || reconciling) return;
reconciling = true;
try {
await loadApiKeys();
for (const d of await db().select().from(deployments)) {
await reconcileOne(c, d).catch((err) => log.error(`deployment ${d.name}`, err));
}