Files
Kaname/src/app/(app)/endpoints/endpoint-form.tsx
T
Claude d10a491042 Client bundles: no drizzle in the browser, lazy palette, one copy of the painting
- The enum arrays move from schema.ts to src/lib/db/enums.ts (no imports),
  which schema.ts re-exports. The endpoint form and benchmark start imported
  ENDPOINT_ENGINES/QUALITY_SECTIONS from the schema, which put drizzle-orm,
  every table definition and ulid (18 KB gzipped) on the endpoint pages. An
  ESLint rule now refuses value imports from the schema in client code.
- The ⌘K palette dialog is its own chunk, loaded on first open and preloaded
  when you hover or focus Search or press ⌘/Ctrl.
- The dot painting's brightness grid was copied into 10 page chunks (~10 KB
  gzipped each); it is now one async chunk, parsed once per tab. The canvas
  skips redraws when size, pixel ratio and theme are unchanged (the
  ResizeObserver's first callback drew everything a second time) and draws at
  most once per frame while resizing.

First-load JS per route drops by 10-29 KB gzipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 20:57:53 +00:00

299 lines
14 KiB
TypeScript

"use client";
import { CheckCircle2Icon, Loader2Icon, PlugZapIcon, SaveIcon, XCircleIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
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 { NativeSelect } from "@/components/ui/native-select";
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
import { ENDPOINT_ENGINES } from "@/lib/db/enums";
import type { EndpointHardware, EndpointProbe } from "@/lib/db/schema";
import type { EndpointView } from "@/lib/endpoints";
type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string };
const GROUPS: { title: string; hint: string; fields: Field[] }[] = [
{
title: "GPU",
hint: "Leave empty for a CPU-only server.",
fields: [
{ key: "gpuName", label: "GPU", placeholder: "NVIDIA GeForce RTX 4090" },
{ key: "gpuCount", label: "Count", placeholder: "1", kind: "int" },
{ key: "vramGb", label: "VRAM per GPU (GB)", placeholder: "24", kind: "number" },
{ key: "pcie", label: "PCIe link", placeholder: "Gen4 x16" },
{ key: "gpuDriver", label: "Driver", placeholder: "nvidia 580.82" },
],
},
{
title: "Machine",
hint: "Only facts like these are published, never host names or addresses.",
fields: [
{ key: "cpu", label: "CPU", placeholder: "AMD EPYC 7282" },
{ key: "memoryGb", label: "RAM (GB)", placeholder: "128", kind: "number" },
{ key: "os", label: "OS", placeholder: "Debian 13" },
{ key: "virtualization", label: "Virtualization", placeholder: "Proxmox VM with GPU passthrough, or bare metal" },
],
},
{
title: "Server",
hint: "What the server runs. Empty fields are taken from what it reports where it can.",
fields: [
{ key: "engineName", label: "Engine name", placeholder: "ik_llama.cpp (default: detected)" },
{ key: "engineVersion", label: "Engine version", placeholder: "default: detected" },
{ key: "image", label: "Container image", placeholder: "ghcr.io/ggml-org/llama.cpp:server-cuda" },
{ key: "quant", label: "Quant", placeholder: "Q4_K_M (default: from the model name)" },
{ key: "kvCache", label: "KV cache type", placeholder: "q8_0" },
{ key: "contextSize", label: "Context (tokens)", placeholder: "default: reported", kind: "int" },
{ key: "concurrency", label: "Parallel slots", placeholder: "4", kind: "int" },
],
},
];
const toText = (v: unknown) => (v == null ? "" : String(v));
/** Create or edit an endpoint. The API key is never sent to the browser: on edit it can be kept, replaced or removed. */
export function EndpointForm({ initial }: { initial?: EndpointView }) {
const router = useRouter();
const [name, setName] = useState(initial?.name ?? "");
const [baseUrl, setBaseUrl] = useState(initial?.baseUrl ?? "");
const [apiKey, setApiKey] = useState("");
const [removeKey, setRemoveKey] = useState(false);
const [model, setModel] = useState(initial?.model ?? "");
const [engine, setEngine] = useState<string>(initial?.engine ?? "");
const [hw, setHw] = useState<Record<string, string>>(() =>
Object.fromEntries(Object.entries(initial?.hardware ?? {}).map(([k, v]) => [k, typeof v === "boolean" ? (v ? "on" : "off") : toText(v)])),
);
const [probe, setProbe] = useState<EndpointProbe | null>(initial?.probe ?? null);
const [testing, setTesting] = useState(false);
const [saving, setSaving] = useState(false);
const fields = GROUPS.flatMap((g) => g.fields);
function body() {
const hardware: Record<string, unknown> = {};
for (const f of fields) {
const v = (hw[f.key] ?? "").trim();
if (!v) continue;
hardware[f.key] = f.kind ? Number(v.replace(",", ".")) : v;
}
if (hw.p2p) hardware.p2p = hw.p2p;
if (hw.rebar) hardware.rebar = hw.rebar === "on";
if (hw.description?.trim()) hardware.description = hw.description.trim();
return {
name,
baseUrl,
// Left out: keep the stored key. "": remove it.
...(apiKey.trim() ? { apiKey: apiKey.trim() } : removeKey || !initial ? { apiKey: "" } : {}),
model: model.trim() || null,
engine: engine || null,
hardware,
};
}
async function test() {
setTesting(true);
try {
const res = await fetch(initial ? `/api/endpoints/${initial.id}/test` : "/api/endpoints/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body()),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
setProbe(json);
if (json.ok && !model && json.models.length === 1) setModel(json.models[0]);
} finally {
setTesting(false);
}
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
const res = await fetch(initial ? `/api/endpoints/${initial.id}` : "/api/endpoints", {
method: initial ? "PATCH" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body()),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
router.push(`/endpoints/${json.id}`);
router.refresh();
} finally {
setSaving(false);
}
}
const set = (key: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setHw((cur) => ({ ...cur, [key]: e.target.value }));
const models = probe?.ok ? probe.models : [];
return (
<form onSubmit={save} className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<Card>
<CardHeader>
<CardTitle>Connection</CardTitle>
<CardDescription>Any OpenAI-compatible server: llama.cpp, vLLM, SGLang, Ollama, … Kaname talks to it from its own server.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
<label className="flex flex-col gap-1">
<span className="text-muted-foreground">Name</span>
<Input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="4090 llama.cpp" required />
</label>
<label className="flex flex-col gap-1">
<span className="text-muted-foreground">URL</span>
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="http://192.168.1.20:8080" required />
<span className="text-xs text-muted-foreground">The server&apos;s root; /v1 is added by Kaname.</span>
</label>
<label className="flex flex-col gap-1">
<span className="text-muted-foreground">API key</span>
<Input
type="password"
autoComplete="off"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder={initial?.hasApiKey ? "stored; type to replace" : "optional"}
disabled={removeKey}
/>
{initial?.hasApiKey && (
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<Checkbox checked={removeKey} onCheckedChange={(v) => setRemoveKey(!!v)} />
Remove the stored key
</label>
)}
<span className="text-xs text-muted-foreground">Stays on the server: never shown again, logged or put into a run.</span>
</label>
<div className="grid grid-cols-2 gap-2">
<label className="flex flex-col gap-1">
<span className="text-muted-foreground">Engine</span>
<NativeSelect value={engine} onChange={(e) => setEngine(e.target.value)}>
<option value="">Detect</option>
{ENDPOINT_ENGINES.map((e) => (
<option key={e} value={e}>
{ENGINE_LABEL[e]}
</option>
))}
</NativeSelect>
</label>
<label className="flex flex-col gap-1">
<span className="text-muted-foreground">Model</span>
{models.length > 1 ? (
<NativeSelect value={model} onChange={(e) => setModel(e.target.value)}>
<option value="">Choose…</option>
{models.map((m) => (
<option key={m} value={m}>
{m}
</option>
))}
</NativeSelect>
) : (
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={models[0] ?? "the only one it serves"} />
)}
</label>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button type="button" variant="outline" onClick={test} disabled={testing || !baseUrl.trim()}>
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
Test connection
</Button>
<Button type="submit" disabled={saving}>
<SaveIcon />
{initial ? "Save" : "Add endpoint"}
</Button>
</div>
{probe && <ProbeResult probe={probe} />}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Hardware notes</CardTitle>
<CardDescription>
Kaname can&apos;t see the machine behind an endpoint. What you enter here goes into every run, its BetterBench notes and launch80 reports, so results stay
comparable.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4 text-sm">
{GROUPS.map((g) => (
<fieldset key={g.title} className="flex flex-col gap-2">
<legend className="mb-1 font-medium">{g.title}</legend>
<p className="-mt-1 text-xs text-muted-foreground">{g.hint}</p>
<div className="grid gap-2 sm:grid-cols-2">
{g.fields.map((f) => (
<label key={f.key} className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{f.label}</span>
<Input value={hw[f.key] ?? ""} onChange={set(f.key)} placeholder={f.placeholder} inputMode={f.kind ? "decimal" : undefined} />
</label>
))}
{g.title === "GPU" && (
<>
<label className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">P2P between GPUs</span>
<NativeSelect value={hw.p2p ?? ""} onChange={set("p2p")}>
<option value="">unknown</option>
<option value="on">on</option>
<option value="off">off</option>
<option value="partial">partial</option>
</NativeSelect>
</label>
<label className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">Resizable BAR</span>
<NativeSelect value={hw.rebar ?? ""} onChange={set("rebar")}>
<option value="">unknown</option>
<option value="on">on</option>
<option value="off">off</option>
</NativeSelect>
</label>
</>
)}
</div>
</fieldset>
))}
<label className="flex flex-col gap-1">
<span className="font-medium">Notes</span>
<textarea
value={hw.description ?? ""}
onChange={set("description")}
maxLength={2000}
rows={3}
placeholder="Launch flags, power limit, anything worth knowing. Published with the runs."
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
/>
</label>
</CardContent>
</Card>
</form>
);
}
/** What "Test connection" found. */
export function ProbeResult({ probe }: { probe: EndpointProbe }) {
if (!probe.ok) {
return (
<div className="flex gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs">
<XCircleIcon className="size-4 shrink-0 text-destructive" />
<span>{probe.error}</span>
</div>
);
}
return (
<div className="flex gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs">
<CheckCircle2Icon className="size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
<div className="flex min-w-0 flex-col gap-0.5">
<span>
Reachable{probe.latencyMs != null ? ` (${probe.latencyMs} ms)` : ""}
{probe.engine ? ` · ${ENGINE_LABEL[probe.engine]}${probe.engineVersion ? ` ${probe.engineVersion}` : ""}` : " · engine not detected"}
{probe.contextSize ? ` · ${probe.contextSize.toLocaleString("en-US")} tokens context` : ""}
{probe.slots ? ` · ${probe.slots} slots` : ""}
</span>
<span className="break-all text-muted-foreground">
{probe.models.length ? `Serves: ${probe.models.slice(0, 6).join(", ")}${probe.models.length > 6 ? ", …" : ""}` : "Lists no models."}
</span>
</div>
</div>
);
}