Files
GPU-Node/dashboard/src/app/page.tsx
Z User 38d8d55c21 fix(dashboard): llama.cpp CLI arg changes — flash-attn value, load-mode, no-cont-batching
## Problem

llama.cpp latest (ghcr.io/ggml-org/llama.cpp:server-cuda) changed several CLI
flags, breaking llama launch from the dashboard:

  error while handling argument "--flash-attn": error: unknown value for
  --flash-attn: '--cont-batching'

  usage:
  -fa,   --flash-attn [on|off|auto]  set Flash Attention use ('on', 'off', or
                                       'auto', default: 'auto')

The dashboard was emitting bare flags like `--flash-attn` and the next
token (`--cont-batching`) was being consumed as the value, causing a parse
error.

## Changes in llama.cpp server

After checking the latest llama.cpp/tools/server/README.md and manpage:

- `--flash-attn` → now takes a value: `[on|off|auto]`. Bare flag fails.
- `--mlock` and `--no-mmap` → deprecated, replaced by unified
  `--load-mode {auto|none|mmap|mlock|mmap+mlock|dio}`.
- `--cont-batching` → enabled by default; disable with `--no-cont-batching`.
- `--rope-scaling` → was numeric (factor), now enum {none,linear,yarn}.
  Numeric factor moved to `--rope-scale`.
- `--metrics`, `--embeddings` → still bare flags (unchanged).

## Fix

### buildLlamaExtraArgs() (server-side, in src/lib/docker.ts)

- `--flash-attn` now emits `--flash-attn on` or `--flash-attn off`
  (always, never bare).
- `--mlock` + `--no-mmap` → unified `--load-mode`:
  - both set → `--load-mode mlock`
  - mlock only → `--load-mode mmap+mlock`
  - no-mmap only → `--load-mode none`
  - neither → emit nothing (default auto)
- `--cont-batching` no longer emitted (default-on). Only emit
  `--no-cont-batching` if user explicitly disabled cont-batching.
- `--rope-scaling <N>` → `--rope-scale <N>` (numeric factor uses new flag).

### parseLlamaExtraArgs() (reads .env)

Updated to handle both legacy and modern syntax:

- `--flash-attn on|off|auto` → set cfg.flashAttn accordingly.
- `--flash-attn` (bare, legacy) → treated as 'on'.
- `--load-mode mlock` → set mlock=true, noMmap=true.
- `--load-mode mmap+mlock` → set mlock=true (noMmap stays false).
- `--load-mode none` → set noMmap=true.
- `--mlock` / `--no-mmap` (legacy) → still parsed for backward compat.
- `--no-cont-batching` / `-nocb` → set contBatching=false.
- `--cont-batching` / `-cb` (legacy) → set contBatching=true (default anyway).
- `--rope-scaling <number>` → treated as `--rope-scale <number>`.
- `--rope-scaling {none,linear,yarn}` → ignored (it's the method, not the factor).
- `--rope-scale <number>` → parsed directly.

Helper `isValue(s)` added to detect whether the next token is a value or
another flag (avoids consuming a following flag as a value).

### buildPreviewArgs() (frontend, in src/app/page.tsx)

Same changes as buildLlamaExtraArgs — kept in sync so the .env preview in
the Config tab shows the exact args that will be passed.

## Verification

- `npm run build` — OK, all 26 routes
- `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓
- Manually verified the generated args by calling buildLlamaExtraArgs() with
  default config — produces valid llama.cpp server CLI.

## After deploy

```sh
git pull && sh build.sh
docker compose up -d --force-recreate dashboard
```

Then click 'Start Llama' — should now launch without the flash-attn error.

## Files changed

- dashboard/src/lib/docker.ts — buildLlamaExtraArgs + parseLlamaExtraArgs
- dashboard/src/app/page.tsx — buildPreviewArgs (frontend copy)
2026-10-24 02:00:47 +00:00

3831 lines
127 KiB
TypeScript

"use client";
import * as React from "react";
import {
Activity,
Cpu,
CpuIcon,
Gauge,
HardDrive,
Key as KeyIcon,
Layers,
MessageSquare,
Moon,
Play,
Power,
RefreshCw,
RotateCw,
Save,
Send,
Settings2,
Square,
Sun,
Terminal,
Trash2,
Upload,
Wrench,
X,
Zap,
FileText,
ChevronRight,
Server,
CloudDownload,
Plus,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn, formatBytes, timeAgo } from "@/lib/utils";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface ModelFile {
name: string;
sizeBytes: number;
sizeHuman: string;
modifiedAt: string;
}
interface ContainerInfo {
name: string;
status: string;
state: string;
running: boolean;
ports: string;
image: string;
role: string | null;
createdAt: string;
statusText: string;
}
interface Preset {
id: string;
name: string;
config: Omit<DashboardConfig, "presets">;
createdAt: string;
}
interface DashboardConfig {
model: string;
ctxSize: number;
parallel: number;
nGpuLayers: number;
threads: number;
draftModel: string;
specType: "none" | "draft-mtp" | "draft-llama";
specDraftNMax: number;
batchSize: number;
ubatchSize: number;
contextOverflow: "none" | "shift" | "evict";
cacheTypeK: "f16" | "f32" | "q8_0" | "q4_0";
cacheTypeV: "f16" | "f32" | "q8_0" | "q4_0";
defragThold: number;
flashAttn: boolean;
noMmap: boolean;
mlock: boolean;
contBatching: boolean;
embeddings: boolean;
metrics: boolean;
ropeFreqScale: number;
ropeScale: number;
yarnExtFactor: number;
yarnAttnFactor: number;
yarnBetaFast: number;
yarnBetaSlow: number;
systemPrompt: string;
topK: number;
topP: number;
minP: number;
temperature: number;
repeatPenalty: number;
extraArgs: string;
presets: Preset[];
}
interface ComfyModelEntry {
type: string;
filename: string;
sizeBytes?: number;
sizeHuman?: string;
}
interface ComfyQueueEntry {
id: number;
action: string;
model_type: string;
filename: string;
url?: string;
status: string;
progress?: number;
downloaded_bytes?: number;
total_bytes?: number;
error?: string;
created_at?: string;
}
interface DownloadJob {
id: string;
url: string;
originalUrl?: string;
urlNote?: string;
filename: string;
status: "queued" | "downloading" | "done" | "failed" | "cancelled";
bytesDownloaded: number;
bytesTotal: number | null;
percent: number;
speedBytesPerSec: number | null;
startedAt: number;
finishedAt: number | null;
error: string | null;
}
interface DashboardSettings {
civitaiToken: string;
}
interface UrlPreview {
original: string;
transformed: string;
note: string;
isCivitai: boolean;
}
const DEFAULT_CONFIG: DashboardConfig = {
model: "model.gguf",
ctxSize: 64000,
parallel: 1,
nGpuLayers: -1,
threads: -1,
draftModel: "",
specType: "none",
specDraftNMax: 4,
batchSize: 512,
ubatchSize: 512,
contextOverflow: "none",
cacheTypeK: "f16",
cacheTypeV: "f16",
defragThold: 0.1,
flashAttn: true,
noMmap: false,
mlock: false,
contBatching: true,
embeddings: false,
metrics: false,
ropeFreqScale: 1.0,
ropeScale: 1.0,
yarnExtFactor: 1.0,
yarnAttnFactor: 1.0,
yarnBetaFast: 32.0,
yarnBetaSlow: 1.0,
systemPrompt: "",
topK: 40,
topP: 0.95,
minP: 0.05,
temperature: 0.8,
repeatPenalty: 1.1,
extraArgs: "",
presets: [],
};
const COMFY_MODEL_TYPES = [
"checkpoints",
"loras",
"vae",
"embeddings",
"controlnet",
"clip",
"unet",
"upscale_models",
"custom_nodes",
];
// ---------------------------------------------------------------------------
// Main page
// ---------------------------------------------------------------------------
export default function DashboardPage() {
const [config, setConfig] = React.useState<DashboardConfig>(DEFAULT_CONFIG);
const [models, setModels] = React.useState<ModelFile[]>([]);
const [containers, setContainers] = React.useState<ContainerInfo[]>([]);
const [llamaHealth, setLlamaHealth] = React.useState<{
reachable: boolean;
detail: string;
} | null>(null);
const [gpu, setGpu] = React.useState<string>("");
const [instance, setInstance] = React.useState<string>("gpu-node");
const [lastUpdated, setLastUpdated] = React.useState<string>("");
const [busy, setBusy] = React.useState<string | null>(null);
const [toast, setToast] = React.useState<{
type: "success" | "error" | "info";
message: string;
} | null>(null);
const toastTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const [presetDialogOpen, setPresetDialogOpen] = React.useState(false);
const [presetName, setPresetName] = React.useState("");
// Logs tab
const [liveLogs, setLiveLogs] = React.useState<
{ stream: "stdout" | "stderr"; line: string; ts?: number }[]
>([]);
const [logsAutoScroll, setLogsAutoScroll] = React.useState(true);
const [logsTarget, setLogsTarget] = React.useState<
"llama" | "comfyui" | "dashboard" | "ssh"
>("llama");
const logsEndRef = React.useRef<HTMLDivElement | null>(null);
const logsEventSourceRef = React.useRef<EventSource | null>(null);
const logsActiveRef = React.useRef(false);
// Comfy
const [comfyModels, setComfyModels] = React.useState<ComfyModelEntry[]>([]);
const [comfyQueue, setComfyQueue] = React.useState<ComfyQueueEntry[]>([]);
const [comfyFilter, setComfyFilter] = React.useState<string>("");
const [comfyAddUrl, setComfyAddUrl] = React.useState("");
const [comfyAddType, setComfyAddType] = React.useState(COMFY_MODEL_TYPES[0]);
// Dynamic list of available model types (subdirs of gpu/comfy/models).
// Falls back to COMFY_MODEL_TYPES if the worker is offline / older version.
const [comfyTypes, setComfyTypes] = React.useState<string[]>(COMFY_MODEL_TYPES);
// Upload state
const [uploadProgress, setUploadProgress] = React.useState<{
name: string;
percent: number;
} | null>(null);
// Download state (.gguf from URL)
const [downloadJobs, setDownloadJobs] = React.useState<DownloadJob[]>([]);
const [downloadUrl, setDownloadUrl] = React.useState("");
const downloadsActiveRef = React.useRef(false);
// Settings (civitai token etc)
const [settings, setSettings] = React.useState<DashboardSettings>({
civitaiToken: "",
});
const [urlPreview, setUrlPreview] = React.useState<UrlPreview | null>(null);
const llamaContainer = containers.find((c) => c.role === "llama") || null;
const comfyContainer = containers.find((c) => c.role === "comfyui") || null;
// ---------------------------------------------------------------------------
// Toast helper
// ---------------------------------------------------------------------------
const showToast = React.useCallback(
(type: "success" | "error" | "info", message: string) => {
setToast({ type, message });
if (toastTimer.current) clearTimeout(toastTimer.current);
toastTimer.current = setTimeout(() => setToast(null), 4000);
},
[]
);
// ---------------------------------------------------------------------------
// SSE status stream (replaces fetch polling)
// ---------------------------------------------------------------------------
React.useEffect(() => {
const es = new EventSource("/api/status/stream");
es.addEventListener("hello", (e) => {
try {
const data = JSON.parse((e as MessageEvent).data);
if (data.instance) setInstance(data.instance);
} catch {
/* ignore */
}
});
es.addEventListener("status", (e) => {
try {
const data = JSON.parse((e as MessageEvent).data);
setContainers(data.containers || []);
setLlamaHealth(data.llamaHealth || null);
if (data.instance) setInstance(data.instance);
setLastUpdated(new Date().toLocaleTimeString());
} catch {
/* ignore */
}
});
es.addEventListener("error", () => {
// EventSource auto-reconnects; nothing to do here.
});
return () => {
es.close();
};
}, []);
// ---------------------------------------------------------------------------
// Other data fetching (one-shot / on-demand)
// ---------------------------------------------------------------------------
const refreshModels = React.useCallback(async () => {
try {
const res = await fetch("/api/models", { cache: "no-store" });
if (!res.ok) {
console.error("[refreshModels] HTTP", res.status, await res.text().catch(() => ""));
return;
}
const data = await res.json();
setModels(data.models || []);
} catch (err) {
console.error("[refreshModels] error:", err);
}
}, []);
const refreshConfig = React.useCallback(async () => {
try {
const res = await fetch("/api/config", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
setConfig(data.config || DEFAULT_CONFIG);
} catch (err) {
console.error("[refreshConfig] error:", err);
}
}, []);
const refreshGpu = React.useCallback(async () => {
setBusy("gpu");
try {
const res = await fetch("/api/gpu", { cache: "no-store" });
const data = await res.json();
setGpu(data.output || data.error || "");
} catch (err) {
setGpu(`[error: ${(err as Error).message}]`);
} finally {
setBusy(null);
}
}, []);
const refreshComfyTypes = React.useCallback(async () => {
try {
const res = await fetch("/api/comfy/types", { cache: "no-store" });
const data = await res.json();
const types: string[] = data.types || [];
if (types.length > 0) {
setComfyTypes(types);
// If current selection isn't in the new list, switch to first available
setComfyAddType((cur) => (types.includes(cur) ? cur : types[0]));
}
} catch (err) {
console.error("[refreshComfyTypes] error:", err);
}
}, []);
const refreshComfyModels = React.useCallback(async () => {
try {
const url = comfyFilter
? `/api/comfy/models?type=${encodeURIComponent(comfyFilter)}`
: "/api/comfy/models";
const res = await fetch(url, { cache: "no-store" });
const data = await res.json();
setComfyModels(data.models || []);
} catch (err) {
console.error("[refreshComfyModels] error:", err);
setComfyModels([]);
}
}, [comfyFilter]);
const refreshComfyQueue = React.useCallback(async () => {
try {
const res = await fetch("/api/comfy/queue", { cache: "no-store" });
const data = await res.json();
setComfyQueue(data.queue || []);
} catch (err) {
// Queue refresh runs every 5s — don't spam console on network blips
setComfyQueue([]);
}
}, []);
React.useEffect(() => {
refreshConfig();
refreshModels();
refreshComfyTypes();
refreshComfyModels();
const id = setInterval(refreshComfyQueue, 5000);
return () => clearInterval(id);
}, [
refreshConfig,
refreshModels,
refreshComfyTypes,
refreshComfyModels,
refreshComfyQueue,
]);
// ---------------------------------------------------------------------------
// Live logs streaming via Server-Sent Events (replaces fetch+readablestream)
// ---------------------------------------------------------------------------
const startLogsStream = React.useCallback(() => {
if (logsActiveRef.current) return;
logsActiveRef.current = true;
setLiveLogs([]);
const es = new EventSource(
`/api/services/${logsTarget}/stream?tail=300`
);
logsEventSourceRef.current = es;
es.addEventListener("hello", () => {
// Server confirmed stream is live
});
es.addEventListener("log", (e) => {
try {
const data = JSON.parse((e as MessageEvent).data);
const line: string = data.line ?? "";
const stream: "stdout" | "stderr" = data.stream ?? "stdout";
if (line.length === 0) return;
setLiveLogs((prev) => {
const next = [...prev, { stream, line, ts: data.ts }];
// Cap at 2000 lines
return next.length > 2000 ? next.slice(-2000) : next;
});
} catch {
/* ignore malformed event */
}
});
es.addEventListener("error", (e) => {
// EventSource auto-reconnects unless we close it. We close on
// explicit "end" event, but on network errors we want to keep
// the user's manual "stop" button authoritative.
const ev = e as Event;
// If the connection was successful before, EventSource will retry.
// We leave it alone — don't close here.
void ev;
});
es.addEventListener("end", () => {
// Container exited or stream ended — close & mark inactive.
es.close();
logsEventSourceRef.current = null;
logsActiveRef.current = false;
});
}, [logsTarget]);
const stopLogsStream = React.useCallback(() => {
if (logsEventSourceRef.current) {
logsEventSourceRef.current.close();
logsEventSourceRef.current = null;
}
logsActiveRef.current = false;
}, []);
React.useEffect(() => {
return () => stopLogsStream();
}, [stopLogsStream]);
React.useEffect(() => {
if (logsAutoScroll) {
logsEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}, [liveLogs, logsAutoScroll]);
// Restart logs stream when target changes
React.useEffect(() => {
if (logsActiveRef.current) {
stopLogsStream();
// Small delay so the old EventSource is fully closed before opening a new one
const id = setTimeout(startLogsStream, 100);
return () => clearTimeout(id);
}
}, [logsTarget, startLogsStream, stopLogsStream]);
// ---------------------------------------------------------------------------
// Generic actions
// ---------------------------------------------------------------------------
async function runAction(
name: string,
fn: () => Promise<{ ok: boolean; message: string; logs?: string }>,
refresh = true
) {
setBusy(name);
try {
const result = await fn();
if (result.ok) {
showToast("success", result.message);
} else {
showToast("error", result.message);
}
if (refresh) {
// SSE handles status, but models list / comfy models need explicit refresh
await Promise.all([refreshModels(), refreshComfyModels()]);
}
} catch (err) {
showToast("error", (err as Error).message);
} finally {
setBusy(null);
}
}
async function handleStartLlama() {
await runAction("start-llama", async () => {
// Persist config first so reloads restore it.
const res = await fetch("/api/config", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(config),
});
if (!res.ok) throw new Error("Failed to save config");
const startRes = await fetch("/api/llama", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "start", config }),
});
const result = await startRes.json();
// If start failed, include compose logs in the message so the user can
// see what went wrong (common cause: model-worker still on old image
// without --json flag, or env not set, etc).
if (!result.ok && result.logs) {
return {
ok: false,
message: `${result.message}\n\n${result.logs.slice(-500)}`,
};
}
return result;
});
}
async function handleLlamaAction(action: "stop" | "restart" | "remove") {
await runAction(`llama-${action}`, async () => {
const res = await fetch("/api/llama", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
});
return await res.json();
});
}
async function handleComfyAction(action: "start" | "stop" | "restart") {
await runAction(`comfy-${action}`, async () => {
const res = await fetch("/api/comfy", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
});
return await res.json();
});
}
async function handleServiceAction(
role: string,
action: "start" | "stop" | "restart" | "remove"
) {
await runAction(`${role}-${action}`, async () => {
const res = await fetch(`/api/services/${role}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
});
return await res.json();
});
}
async function handleSystemAction(action: "sleep" | "wake" | "update") {
if (action === "sleep") {
const ok = confirm(
"Sleep mode will stop: llama, comfyui, gpu-test, model-worker, webdav, dashboard.\n\n" +
"Only tailscale + ssh will remain.\n\nContinue?"
);
if (!ok) return;
}
if (action === "update") {
const ok = confirm(
"Update will:\n1. Run build.sh (rebuild all images)\n2. Restart ssh-companion + model-worker + dashboard\n\n" +
"This may take several minutes. Continue?"
);
if (!ok) return;
}
await runAction(`system-${action}`, async () => {
const res = await fetch("/api/system", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
});
return await res.json();
}, false);
}
async function handleUpload(file: File) {
if (!file.name.toLowerCase().endsWith(".gguf")) {
showToast("error", "Only .gguf files are allowed");
return;
}
setUploadProgress({ name: file.name, percent: 0 });
setBusy("upload");
try {
const formData = new FormData();
formData.append("file", file);
// Use XMLHttpRequest for upload progress
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) {
setUploadProgress({
name: file.name,
percent: Math.round((e.loaded / e.total) * 100),
});
}
});
xhr.addEventListener("load", () => {
if (xhr.status >= 200 && xhr.status < 300) resolve();
else reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
});
xhr.addEventListener("error", () =>
reject(new Error("Network error during upload"))
);
xhr.open("POST", "/api/models/upload");
xhr.send(formData);
});
showToast("success", `${file.name} uploaded`);
await refreshModels();
} catch (err) {
showToast("error", (err as Error).message);
} finally {
setUploadProgress(null);
setBusy(null);
}
}
async function handleDeleteModel(name: string) {
if (!confirm(`Delete ${name}? This cannot be undone.`)) return;
await runAction(`del-${name}`, async () => {
const res = await fetch(
`/api/models?name=${encodeURIComponent(name)}`,
{ method: "DELETE" }
);
const data = await res.json();
return {
ok: data.ok,
message: data.ok ? `${name} deleted` : data.error || "Failed",
};
});
}
// ---------------------------------------------------------------------------
// Model download (.gguf from URL) — uses SSE for live progress
// ---------------------------------------------------------------------------
const refreshDownloadJobs = React.useCallback(async () => {
try {
const res = await fetch("/api/models/download/status", {
cache: "no-store",
});
if (!res.ok) return;
const data = await res.json();
const jobs: DownloadJob[] = data.jobs || [];
setDownloadJobs(jobs);
// If any active jobs, ensure SSE subscription is running
const hasActive = jobs.some(
(j) => j.status === "downloading" || j.status === "queued"
);
if (hasActive && !downloadsActiveRef.current) {
startDownloadSSE(jobs);
} else if (!hasActive && downloadsActiveRef.current) {
stopDownloadSSE();
}
} catch (err) {
console.error("[refreshDownloadJobs] error:", err);
}
}, []);
const downloadSSERef = React.useRef<Map<string, EventSource>>(new Map());
const startDownloadSSE = React.useCallback((jobs: DownloadJob[]) => {
const active = jobs.filter(
(j) => j.status === "downloading" || j.status === "queued"
);
for (const job of active) {
if (downloadSSERef.current.has(job.id)) continue;
const es = new EventSource(
`/api/models/download/${job.id}/stream`
);
downloadSSERef.current.set(job.id, es);
es.addEventListener("progress", (e) => {
try {
const data = JSON.parse((e as MessageEvent).data) as DownloadJob;
setDownloadJobs((prev) => {
const next = [...prev];
const idx = next.findIndex((j) => j.id === data.id);
if (idx >= 0) next[idx] = data;
else next.push(data);
return next;
});
} catch {
/* ignore */
}
});
es.addEventListener("end", () => {
es.close();
downloadSSERef.current.delete(job.id);
// Refresh models list — file may have appeared on disk
refreshModels();
});
es.addEventListener("error", () => {
// Will auto-retry; if stream really ended, the end event will fire.
});
}
if (active.length > 0) downloadsActiveRef.current = true;
}, [refreshModels]);
const stopDownloadSSE = React.useCallback(() => {
for (const es of downloadSSERef.current.values()) {
es.close();
}
downloadSSERef.current.clear();
downloadsActiveRef.current = false;
}, []);
React.useEffect(() => {
// On mount, fetch existing download jobs (in case page was refreshed mid-download)
refreshDownloadJobs();
return () => stopDownloadSSE();
}, [refreshDownloadJobs, stopDownloadSSE]);
async function handleDownload() {
if (!downloadUrl.trim()) {
showToast("error", "URL required");
return;
}
let url: string;
try {
url = downloadUrl.trim();
// Validate URL
new URL(url);
} catch {
showToast("error", "Invalid URL");
return;
}
setBusy("download-start");
try {
const res = await fetch("/api/models/download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
});
const data = await res.json();
if (data.ok && data.job) {
const job = data.job as DownloadJob;
setDownloadJobs((prev) => [...prev, job]);
setDownloadUrl("");
showToast("info", `Started: ${job.filename}`);
// Start SSE subscription for this job
startDownloadSSE([job]);
} else {
showToast("error", data.error || "Failed to start download");
}
} catch (err) {
showToast("error", (err as Error).message);
} finally {
setBusy(null);
}
}
async function handleCancelDownload(id: string) {
if (!confirm("Cancel this download? Partial file will be deleted.")) return;
try {
const res = await fetch(`/api/models/download/${id}/cancel`, {
method: "POST",
});
const data = await res.json();
if (data.ok) {
showToast("info", "Download cancelled");
// Stop SSE for this job
const es = downloadSSERef.current.get(id);
if (es) {
es.close();
downloadSSERef.current.delete(id);
}
await refreshDownloadJobs();
} else {
showToast("error", data.error || "Failed to cancel");
}
} catch (err) {
showToast("error", (err as Error).message);
}
}
// ---------------------------------------------------------------------------
// Settings (CivitAI token etc)
// ---------------------------------------------------------------------------
const refreshSettings = React.useCallback(async () => {
try {
const res = await fetch("/api/settings", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
setSettings(data.settings || { civitaiToken: "" });
} catch (err) {
console.error("[refreshSettings] error:", err);
}
}, []);
const previewDebounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const previewUrl = React.useCallback(async (url: string) => {
if (!url.trim()) {
setUrlPreview(null);
return;
}
try {
const res = await fetch("/api/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "preview-url", url }),
});
if (!res.ok) return;
const data = await res.json();
if (data.ok) {
setUrlPreview({
original: data.original,
transformed: data.transformed,
note: data.note,
isCivitai: data.isCivitai,
});
}
} catch {
/* ignore — preview is best-effort */
}
}, []);
// Debounced URL preview — fires 400ms after the user stops typing
React.useEffect(() => {
if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current);
previewDebounceRef.current = setTimeout(() => {
void previewUrl(downloadUrl);
}, 400);
return () => {
if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current);
};
}, [downloadUrl, previewUrl]);
React.useEffect(() => {
refreshSettings();
}, [refreshSettings]);
async function handleSaveCivitaiToken(token: string) {
setBusy("save-settings");
try {
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ civitaiToken: token }),
});
const data = await res.json();
if (data.settings) {
setSettings(data.settings);
showToast("success", "CivitAI token saved");
} else {
showToast("error", data.error || "Failed to save");
}
} finally {
setBusy(null);
}
}
async function handleSavePreset() {
if (!presetName.trim()) {
showToast("error", "Preset name required");
return;
}
setBusy("save-preset");
try {
const res = await fetch("/api/config", {
method: "POST",
headers: { "Content-Type": "application/json" },
// Send current config so the preset snapshots what's actually in
// the form right now — not what was last persisted to config.json.
body: JSON.stringify({
action: "save-preset",
name: presetName.trim(),
config,
}),
});
const data = await res.json();
if (data.config) {
setConfig(data.config);
showToast("success", `Preset "${presetName}" saved`);
setPresetName("");
setPresetDialogOpen(false);
} else {
showToast("error", data.error || "Failed to save preset");
}
} finally {
setBusy(null);
}
}
async function handleLoadPreset(id: string) {
setBusy(`load-${id}`);
try {
const res = await fetch("/api/config", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "load-preset", id }),
});
const data = await res.json();
if (data.config) {
setConfig(data.config);
showToast("success", "Preset loaded");
} else {
showToast("error", data.error || "Failed to load preset");
}
} finally {
setBusy(null);
}
}
async function handleDeletePreset(id: string, name: string) {
setBusy(`del-${id}`);
try {
const res = await fetch("/api/config", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "delete-preset", id }),
});
const data = await res.json();
if (data.config) {
setConfig(data.config);
showToast("info", `Preset "${name}" deleted`);
}
} finally {
setBusy(null);
}
}
async function handleResetConfig() {
setBusy("reset");
try {
const res = await fetch("/api/config", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "reset" }),
});
const data = await res.json();
if (data.config) {
setConfig(data.config);
showToast("info", "Config reset to defaults");
}
} finally {
setBusy(null);
}
}
async function handleComfyAddModel() {
if (!comfyAddUrl.trim()) {
showToast("error", "URL required");
return;
}
await runAction("comfy-add", async () => {
const res = await fetch("/api/comfy/models/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: comfyAddUrl.trim(), type: comfyAddType }),
});
const data = await res.json();
setComfyAddUrl("");
await refreshComfyQueue();
return {
ok: data.ok,
message: data.ok ? `Queued: ${comfyAddType}` : data.error || "Failed",
};
}, false);
}
async function handleComfyRemoveModel(filename: string, type?: string) {
if (!confirm(`Remove ${filename}?`)) return;
await runAction(`comfy-rm-${filename}`, async () => {
const res = await fetch("/api/comfy/models/rm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ filename, type }),
});
const data = await res.json();
await refreshComfyModels();
return {
ok: data.ok,
message: data.ok ? `${filename} removed` : data.error || "Failed",
};
}, false);
}
function update<K extends keyof DashboardConfig>(
key: K,
value: DashboardConfig[K]
) {
setConfig((prev) => ({ ...prev, [key]: value }));
}
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
const llamaStatus: "running" | "stopped" | "absent" = llamaContainer
? llamaContainer.running
? "running"
: "stopped"
: "absent";
return (
<div className="min-h-screen flex flex-col bg-background">
<Header
instance={instance}
lastUpdated={lastUpdated}
llamaStatus={llamaStatus}
onSleep={() => handleSystemAction("sleep")}
onWake={() => handleSystemAction("wake")}
onUpdate={() => handleSystemAction("update")}
busy={busy}
/>
<main className="flex-1 mx-auto max-w-7xl w-full px-4 sm:px-6 py-6 space-y-6">
{/* Quick actions row — llama */}
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<QuickActionCard
icon={<Play className="h-4 w-4" />}
label="Start Llama"
description="Apply config + launch llama.cpp"
color="success"
disabled={busy !== null}
loading={busy === "start-llama"}
onClick={handleStartLlama}
/>
<QuickActionCard
icon={<RotateCw className="h-4 w-4" />}
label="Restart Llama"
description="Restart llama container"
color="default"
disabled={!llamaContainer || busy !== null}
loading={busy === "llama-restart"}
onClick={() => handleLlamaAction("restart")}
/>
<QuickActionCard
icon={<Square className="h-4 w-4" />}
label="Stop Llama"
description="Stop llama (keeps container)"
color="warning"
disabled={!llamaContainer?.running || busy !== null}
loading={busy === "llama-stop"}
onClick={() => handleLlamaAction("stop")}
/>
<QuickActionCard
icon={<Trash2 className="h-4 w-4" />}
label="Remove Llama"
description="Force-remove llama container"
color="destructive"
disabled={!llamaContainer || busy !== null}
loading={busy === "llama-remove"}
onClick={() => handleLlamaAction("remove")}
/>
</div>
{/* Quick actions row — comfy + system */}
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<QuickActionCard
icon={<Play className="h-4 w-4" />}
label="Start Comfy"
description="Launch ComfyUI"
color="success"
disabled={busy !== null}
loading={busy === "comfy-start"}
onClick={() => handleComfyAction("start")}
/>
<QuickActionCard
icon={<RotateCw className="h-4 w-4" />}
label="Restart Comfy"
description="Restart ComfyUI container"
color="default"
disabled={!comfyContainer || busy !== null}
loading={busy === "comfy-restart"}
onClick={() => handleComfyAction("restart")}
/>
<QuickActionCard
icon={<Square className="h-4 w-4" />}
label="Stop Comfy"
description="Stop ComfyUI"
color="warning"
disabled={!comfyContainer?.running || busy !== null}
loading={busy === "comfy-stop"}
onClick={() => handleComfyAction("stop")}
/>
<QuickActionCard
icon={<RefreshCw className="h-4 w-4" />}
label="Refresh GPU"
description="Query nvidia-smi"
color="default"
disabled={busy !== null}
loading={busy === "gpu"}
onClick={refreshGpu}
/>
</div>
{/* Tabs */}
<Tabs defaultValue="config" className="w-full">
<TabsList className="grid w-full grid-cols-2 sm:grid-cols-7 h-auto">
<TabsTrigger value="config" className="gap-1.5">
<Settings2 className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Config</span>
</TabsTrigger>
<TabsTrigger value="chat" className="gap-1.5">
<MessageSquare className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Chat</span>
</TabsTrigger>
<TabsTrigger value="perf" className="gap-1.5">
<Gauge className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Perf</span>
</TabsTrigger>
<TabsTrigger value="models" className="gap-1.5">
<HardDrive className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Models</span>
</TabsTrigger>
<TabsTrigger value="comfy" className="gap-1.5">
<Layers className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Comfy</span>
</TabsTrigger>
<TabsTrigger value="logs" className="gap-1.5">
<Terminal className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Logs</span>
{liveLogs.length > 0 && (
<Badge variant="secondary" className="ml-1 h-4 px-1 text-[10px]">
{liveLogs.length}
</Badge>
)}
</TabsTrigger>
<TabsTrigger value="system" className="gap-1.5">
<Activity className="h-3.5 w-3.5" />
<span className="hidden sm:inline">System</span>
</TabsTrigger>
</TabsList>
{/* Config tab */}
<TabsContent value="config" className="space-y-4">
<ConfigTab
config={config}
models={models}
busy={busy}
presetDialogOpen={presetDialogOpen}
presetName={presetName}
setPresetDialogOpen={setPresetDialogOpen}
setPresetName={setPresetName}
update={update}
onSavePreset={handleSavePreset}
onLoadPreset={handleLoadPreset}
onDeletePreset={handleDeletePreset}
onReset={handleResetConfig}
/>
</TabsContent>
{/* Chat tab */}
<TabsContent value="chat">
<ChatTab
systemPrompt={config.systemPrompt}
temperature={config.temperature}
topP={config.topP}
topK={config.topK}
minP={config.minP}
repeatPenalty={config.repeatPenalty}
llamaRunning={!!llamaContainer?.running}
/>
</TabsContent>
{/* Perf tab */}
<TabsContent value="perf">
<PerfTab llamaRunning={!!llamaContainer?.running} />
</TabsContent>
{/* Models tab */}
<TabsContent value="models">
<ModelsTab
models={models}
config={config}
busy={busy}
uploadProgress={uploadProgress}
onSelectModel={(m) => update("model", m)}
onUpload={handleUpload}
onDelete={handleDeleteModel}
downloadJobs={downloadJobs}
downloadUrl={downloadUrl}
setDownloadUrl={setDownloadUrl}
onDownload={handleDownload}
onCancelDownload={handleCancelDownload}
civitaiToken={settings.civitaiToken}
onSaveCivitaiToken={handleSaveCivitaiToken}
urlPreview={urlPreview}
/>
</TabsContent>
{/* Comfy tab */}
<TabsContent value="comfy">
<ComfyTab
models={comfyModels}
queue={comfyQueue}
types={comfyTypes}
filter={comfyFilter}
setFilter={setComfyFilter}
onRefreshModels={refreshComfyModels}
onRefreshQueue={refreshComfyQueue}
onRefreshTypes={refreshComfyTypes}
onAdd={handleComfyAddModel}
addUrl={comfyAddUrl}
setAddUrl={setComfyAddUrl}
addType={comfyAddType}
setAddType={setComfyAddType}
onRemove={handleComfyRemoveModel}
busy={busy}
/>
</TabsContent>
{/* Logs tab */}
<TabsContent value="logs">
<LogsTab
target={logsTarget}
setTarget={setLogsTarget}
liveLogs={liveLogs}
autoScroll={logsAutoScroll}
setAutoScroll={setLogsAutoScroll}
active={logsActiveRef.current}
onStart={startLogsStream}
onStop={stopLogsStream}
onClear={() => setLiveLogs([])}
logsEndRef={logsEndRef}
/>
</TabsContent>
{/* System tab */}
<TabsContent value="system" className="space-y-4">
<SystemTab
containers={containers}
llamaHealth={llamaHealth}
gpu={gpu}
instance={instance}
busy={busy}
onGpuRefresh={refreshGpu}
onServiceAction={handleServiceAction}
/>
</TabsContent>
</Tabs>
</main>
<footer className="border-t border-border bg-card/30 mt-auto">
<div className="mx-auto max-w-7xl px-4 sm:px-6 py-3 flex items-center justify-between text-xs text-muted-foreground">
<div>
GPU-Node Dashboard ·{" "}
<a
href="https://github.com/ggml-org/llama.cpp"
target="_blank"
rel="noopener noreferrer"
className="underline-offset-2 hover:underline"
>
llama.cpp
</a>
</div>
<div className="flex items-center gap-2">
<span className="h-1.5 w-1.5 rounded-full bg-success animate-pulse" />
Live SSE stream
</div>
</div>
</footer>
{toast && <Toast toast={toast} onClose={() => setToast(null)} />}
</div>
);
}
// ---------------------------------------------------------------------------
// Header
// ---------------------------------------------------------------------------
function Header({
instance,
lastUpdated,
llamaStatus,
onSleep,
onWake,
onUpdate,
busy,
}: {
instance: string;
lastUpdated: string;
llamaStatus: "running" | "stopped" | "absent";
onSleep: () => void;
onWake: () => void;
onUpdate: () => void;
busy: string | null;
}) {
return (
<header className="border-b border-border bg-card/30 backdrop-blur sticky top-0 z-10">
<div className="mx-auto max-w-7xl px-4 sm:px-6 py-3 flex items-center justify-between gap-4">
<div className="flex items-center gap-3 min-w-0">
<div className="h-9 w-9 rounded-md bg-gradient-to-br from-foreground to-muted-foreground flex items-center justify-center text-background">
<Cpu className="h-5 w-5" />
</div>
<div className="min-w-0">
<h1 className="text-base font-semibold tracking-tight truncate">
GPU Node Dashboard
</h1>
<p className="text-xs text-muted-foreground truncate">
Instance: <code className="font-mono">{instance}</code>
{lastUpdated && (
<>
{" · "}
updated <span className="font-mono">{lastUpdated}</span>
</>
)}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="gap-1.5">
<span
className={cn(
"h-1.5 w-1.5 rounded-full",
llamaStatus === "running"
? "bg-success"
: llamaStatus === "stopped"
? "bg-warning"
: "bg-muted-foreground"
)}
/>
{llamaStatus === "running"
? "Running"
: llamaStatus === "stopped"
? "Stopped"
: "Not created"}
</Badge>
<Button
variant="outline"
size="sm"
onClick={onSleep}
disabled={busy !== null}
>
<Moon className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Sleep</span>
</Button>
<Button
variant="outline"
size="sm"
onClick={onWake}
disabled={busy !== null}
>
<Sun className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Wake</span>
</Button>
<Button
variant="outline"
size="sm"
onClick={onUpdate}
disabled={busy !== null}
>
<Wrench className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Update</span>
</Button>
</div>
</div>
</header>
);
}
// ---------------------------------------------------------------------------
// Config Tab
// ---------------------------------------------------------------------------
function ConfigTab({
config,
models,
busy,
presetDialogOpen,
presetName,
setPresetDialogOpen,
setPresetName,
update,
onSavePreset,
onLoadPreset,
onDeletePreset,
onReset,
}: {
config: DashboardConfig;
models: ModelFile[];
busy: string | null;
presetDialogOpen: boolean;
presetName: string;
setPresetDialogOpen: (v: boolean) => void;
setPresetName: (v: string) => void;
update: <K extends keyof DashboardConfig>(key: K, value: DashboardConfig[K]) => void;
onSavePreset: () => void;
onLoadPreset: (id: string) => void;
onDeletePreset: (id: string, name: string) => void;
onReset: () => void;
}) {
return (
<Card>
<CardHeader className="flex flex-row items-start justify-between gap-2">
<div>
<CardTitle className="text-base flex items-center gap-2">
<Settings2 className="h-4 w-4" />
Launch Configuration
</CardTitle>
<CardDescription>
Adjust llama.cpp parameters. Saved automatically on apply.
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={onReset} disabled={busy !== null}>
Reset
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPresetDialogOpen(!presetDialogOpen)}
disabled={busy !== null}
>
<Save className="h-3.5 w-3.5" />
Save preset
</Button>
</div>
</CardHeader>
<CardContent className="space-y-5">
{presetDialogOpen && (
<div className="flex items-end gap-2 p-3 rounded-md border bg-muted/30">
<div className="flex-1 space-y-1.5">
<Label htmlFor="preset-name">Preset name</Label>
<Input
id="preset-name"
value={presetName}
onChange={(e) => setPresetName(e.target.value)}
placeholder="e.g. long-context-spec"
/>
</div>
<Button size="sm" onClick={onSavePreset} disabled={busy === "save-preset"}>
<Save className="h-3.5 w-3.5" />
Save
</Button>
<Button size="sm" variant="ghost" onClick={() => setPresetDialogOpen(false)}>
<X className="h-3.5 w-3.5" />
</Button>
</div>
)}
{config.presets.length > 0 && (
<div className="space-y-2">
<Label>Presets</Label>
<div className="flex flex-wrap gap-2">
{config.presets.map((p) => (
<div
key={p.id}
className="flex items-center gap-1 rounded-md border bg-card pl-3 pr-1 py-1 text-xs"
>
<button
onClick={() => onLoadPreset(p.id)}
disabled={busy !== null}
className="flex items-center gap-1.5 hover:text-primary"
>
<Layers className="h-3 w-3" />
<span className="font-medium">{p.name}</span>
</button>
<button
onClick={() => onDeletePreset(p.id, p.name)}
disabled={busy !== null}
className="ml-1 p-0.5 rounded hover:bg-destructive/10 hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
</div>
)}
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="model">Model <span className="text-destructive">*</span></Label>
<Select value={config.model} onValueChange={(v) => update("model", v)}>
<SelectTrigger id="model">
<SelectValue placeholder="Select a model" />
</SelectTrigger>
<SelectContent>
{models.length === 0 ? (
<SelectItem value={config.model} disabled>
No .gguf files found
</SelectItem>
) : (
models.map((m) => (
<SelectItem key={m.name} value={m.name}>
<span className="font-mono">{m.name}</span>
<span className="ml-2 text-muted-foreground text-xs">{m.sizeHuman}</span>
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="ctx-size">Context size (tokens)</Label>
<Input
id="ctx-size"
type="number"
min={512}
step={512}
value={config.ctxSize}
onChange={(e) => update("ctxSize", Number(e.target.value))}
/>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="space-y-1.5">
<Label htmlFor="parallel">Parallel slots</Label>
<Input
id="parallel"
type="number"
min={1}
max={64}
value={config.parallel}
onChange={(e) => update("parallel", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="batch">Batch size</Label>
<Input
id="batch"
type="number"
min={1}
value={config.batchSize}
onChange={(e) => update("batchSize", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="ngl">GPU layers (-1 = all)</Label>
<Input
id="ngl"
type="number"
min={-1}
value={config.nGpuLayers}
onChange={(e) => update("nGpuLayers", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="threads">Threads (-1 = auto)</Label>
<Input
id="threads"
type="number"
min={-1}
value={config.threads}
onChange={(e) => update("threads", Number(e.target.value))}
/>
</div>
</div>
<div className="rounded-md border p-4 space-y-4 bg-muted/20">
<div className="flex items-center justify-between gap-2">
<div>
<div className="flex items-center gap-2">
<Zap className="h-4 w-4 text-warning" />
<span className="text-sm font-medium">Speculative decoding</span>
</div>
<p className="text-xs text-muted-foreground mt-0.5">
Draft model + spec algorithm. Off by default.
</p>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="spec-type">Spec type</Label>
<Select
value={config.specType}
onValueChange={(v) => update("specType", v as DashboardConfig["specType"])}
>
<SelectTrigger id="spec-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="draft-mtp">draft-mtp</SelectItem>
<SelectItem value="draft-llama">draft-llama</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="draft-model">Draft model</Label>
<Select
value={config.draftModel || "__none__"}
onValueChange={(v) => update("draftModel", v === "__none__" ? "" : v)}
disabled={config.specType === "none"}
>
<SelectTrigger id="draft-model">
<SelectValue placeholder="Optional" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">— None —</SelectItem>
{models.map((m) => (
<SelectItem key={m.name} value={m.name}>
<span className="font-mono">{m.name}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="spec-max">Draft N max</Label>
<Input
id="spec-max"
type="number"
min={1}
max={64}
value={config.specDraftNMax}
onChange={(e) => update("specDraftNMax", Number(e.target.value))}
disabled={config.specType === "none"}
/>
</div>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="overflow">Context overflow</Label>
<Select
value={config.contextOverflow}
onValueChange={(v) => update("contextOverflow", v as DashboardConfig["contextOverflow"])}
>
<SelectTrigger id="overflow">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">none (hard stop)</SelectItem>
<SelectItem value="shift">shift (rolling)</SelectItem>
<SelectItem value="evict">evict (LRU)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="ubatch">Micro-batch size (ubatch)</Label>
<Input
id="ubatch"
type="number"
min={1}
value={config.ubatchSize}
onChange={(e) => update("ubatchSize", Number(e.target.value))}
/>
</div>
</div>
{/* KV cache */}
<div className="rounded-md border p-4 space-y-3 bg-muted/20">
<div>
<span className="text-sm font-medium">KV cache</span>
<p className="text-xs text-muted-foreground mt-0.5">
Quantize KV cache to save VRAM. q8_0 ≈ 50% memory, q4_0 ≈ 25%
(slight quality drop).
</p>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="cache-k">Cache type K</Label>
<Select
value={config.cacheTypeK}
onValueChange={(v) => update("cacheTypeK", v as DashboardConfig["cacheTypeK"])}
>
<SelectTrigger id="cache-k">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="f16">f16 (default)</SelectItem>
<SelectItem value="f32">f32 (full precision)</SelectItem>
<SelectItem value="q8_0">q8_0 (50% mem)</SelectItem>
<SelectItem value="q4_0">q4_0 (25% mem)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="cache-v">Cache type V</Label>
<Select
value={config.cacheTypeV}
onValueChange={(v) => update("cacheTypeV", v as DashboardConfig["cacheTypeV"])}
>
<SelectTrigger id="cache-v">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="f16">f16 (default)</SelectItem>
<SelectItem value="f32">f32 (full precision)</SelectItem>
<SelectItem value="q8_0">q8_0 (50% mem)</SelectItem>
<SelectItem value="q4_0">q4_0 (25% mem)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="defrag">Defrag threshold</Label>
<Input
id="defrag"
type="number"
step={0.05}
min={0}
max={1}
value={config.defragThold}
onChange={(e) => update("defragThold", Number(e.target.value))}
/>
</div>
</div>
</div>
{/* Performance flags */}
<div className="rounded-md border p-4 space-y-3 bg-muted/20">
<div>
<span className="text-sm font-medium">Performance flags</span>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<ToggleRow
label="Flash Attention"
hint="Faster, less memory"
checked={config.flashAttn}
onChange={(v) => update("flashAttn", v)}
/>
<ToggleRow
label="Continuous batching"
hint="Process multiple requests concurrently"
checked={config.contBatching}
onChange={(v) => update("contBatching", v)}
/>
<ToggleRow
label="No mmap"
hint="Load model to RAM (slower startup, no swap)"
checked={config.noMmap}
onChange={(v) => update("noMmap", v)}
/>
<ToggleRow
label="mlock"
hint="Lock model in RAM (prevent swap)"
checked={config.mlock}
onChange={(v) => update("mlock", v)}
/>
<ToggleRow
label="Embeddings"
hint="Expose /embeddings endpoint"
checked={config.embeddings}
onChange={(v) => update("embeddings", v)}
/>
<ToggleRow
label="Metrics"
hint="Expose /metrics (Prometheus)"
checked={config.metrics}
onChange={(v) => update("metrics", v)}
/>
</div>
</div>
{/* RoPE / YaRN */}
<div className="rounded-md border p-4 space-y-3 bg-muted/20">
<div>
<span className="text-sm font-medium">RoPE / YaRN context extension</span>
<p className="text-xs text-muted-foreground mt-0.5">
For extending context beyond the model&apos;s training length.
Leave at defaults unless you know what you&apos;re doing.
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="rope-scale">rope-scaling</Label>
<Input
id="rope-scale"
type="number"
step={0.1}
min={0}
value={config.ropeScale}
onChange={(e) => update("ropeScale", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="rope-freq">rope-freq-scale</Label>
<Input
id="rope-freq"
type="number"
step={0.1}
min={0}
value={config.ropeFreqScale}
onChange={(e) => update("ropeFreqScale", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="yarn-ext">yarn-ext-factor</Label>
<Input
id="yarn-ext"
type="number"
step={0.1}
min={0}
value={config.yarnExtFactor}
onChange={(e) => update("yarnExtFactor", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="yarn-attn">yarn-attn-factor</Label>
<Input
id="yarn-attn"
type="number"
step={0.1}
min={0}
value={config.yarnAttnFactor}
onChange={(e) => update("yarnAttnFactor", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="yarn-bf">yarn-beta-fast</Label>
<Input
id="yarn-bf"
type="number"
step={0.5}
min={0}
value={config.yarnBetaFast}
onChange={(e) => update("yarnBetaFast", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="yarn-bs">yarn-beta-slow</Label>
<Input
id="yarn-bs"
type="number"
step={0.1}
min={0}
value={config.yarnBetaSlow}
onChange={(e) => update("yarnBetaSlow", Number(e.target.value))}
/>
</div>
</div>
</div>
{/* Sampling defaults */}
<div className="rounded-md border p-4 space-y-3 bg-muted/20">
<div>
<span className="text-sm font-medium">Default sampling</span>
<p className="text-xs text-muted-foreground mt-0.5">
Applied as defaults to /completion & /v1/chat/completions requests
(can be overridden per-request).
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="temp">Temperature</Label>
<Input
id="temp"
type="number"
step={0.05}
min={0}
value={config.temperature}
onChange={(e) => update("temperature", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="top-k">top-k</Label>
<Input
id="top-k"
type="number"
min={0}
value={config.topK}
onChange={(e) => update("topK", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="top-p">top-p</Label>
<Input
id="top-p"
type="number"
step={0.05}
min={0}
max={1}
value={config.topP}
onChange={(e) => update("topP", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="min-p">min-p</Label>
<Input
id="min-p"
type="number"
step={0.01}
min={0}
max={1}
value={config.minP}
onChange={(e) => update("minP", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="repeat">Repeat penalty</Label>
<Input
id="repeat"
type="number"
step={0.05}
min={1}
value={config.repeatPenalty}
onChange={(e) => update("repeatPenalty", Number(e.target.value))}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="sys-prompt">System prompt (default)</Label>
<Textarea
id="sys-prompt"
rows={2}
value={config.systemPrompt}
onChange={(e) => update("systemPrompt", e.target.value)}
placeholder="e.g. You are a helpful assistant."
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="extra-args">
Extra args{" "}
<span className="text-muted-foreground normal-case">
(advanced / passthrough)
</span>
</Label>
<Textarea
id="extra-args"
rows={2}
value={config.extraArgs}
onChange={(e) => update("extraArgs", e.target.value)}
placeholder="e.g. --mlock --no-mmap --rope-freq-scale 0.5"
className="font-mono text-xs"
/>
</div>
<div className="rounded-md border bg-card p-3 space-y-1.5">
<Label className="flex items-center gap-1.5">
<FileText className="h-3.5 w-3.5" />
Will be saved to <code className="font-mono text-xs">.env</code> as
</Label>
<pre className="text-xs font-mono whitespace-pre-wrap break-all bg-background p-2 rounded border">
{`LLAMA_MODEL=${config.model}
LLAMA_EXTRA_ARGS=${buildPreviewArgs(config)}`}
</pre>
</div>
</CardContent>
</Card>
);
}
// ---------------------------------------------------------------------------
// Models Tab
// ---------------------------------------------------------------------------
function ModelsTab({
models,
config,
busy,
uploadProgress,
onSelectModel,
onUpload,
onDelete,
downloadJobs,
downloadUrl,
setDownloadUrl,
onDownload,
onCancelDownload,
civitaiToken,
onSaveCivitaiToken,
urlPreview,
}: {
models: ModelFile[];
config: DashboardConfig;
busy: string | null;
uploadProgress: { name: string; percent: number } | null;
onSelectModel: (m: string) => void;
onUpload: (file: File) => void;
onDelete: (name: string) => void;
downloadJobs: DownloadJob[];
downloadUrl: string;
setDownloadUrl: (v: string) => void;
onDownload: () => void;
onCancelDownload: (id: string) => void;
civitaiToken: string;
onSaveCivitaiToken: (token: string) => void;
urlPreview: UrlPreview | null;
}) {
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const [dragOver, setDragOver] = React.useState(false);
const [showCivitaiSettings, setShowCivitaiSettings] = React.useState(false);
const [civitaiTokenDraft, setCivitaiTokenDraft] = React.useState(civitaiToken);
React.useEffect(() => {
setCivitaiTokenDraft(civitaiToken);
}, [civitaiToken]);
function handleFiles(files: FileList | null) {
if (!files || files.length === 0) return;
onUpload(files[0]);
}
const activeDownloads = downloadJobs.filter(
(j) => j.status === "downloading" || j.status === "queued"
);
const finishedDownloads = downloadJobs
.filter(
(j) => j.status !== "downloading" && j.status !== "queued"
)
.sort((a, b) => (b.finishedAt || 0) - (a.finishedAt || 0))
.slice(0, 5);
return (
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<HardDrive className="h-4 w-4" />
Models on Disk
</CardTitle>
<CardDescription>
<code className="font-mono text-xs">/project/gpu/llama_models</code>
{" · "}
{models.length} file(s)
{" · "}
{formatBytes(models.reduce((s, m) => s + m.sizeBytes, 0))} total
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Upload dropzone */}
<div
onDragOver={(e) => {
e.preventDefault();
setDragOver(true);
}}
onDragLeave={() => setDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setDragOver(false);
handleFiles(e.dataTransfer.files);
}}
className={cn(
"rounded-md border-2 border-dashed p-6 text-center cursor-pointer transition-colors",
dragOver
? "border-primary bg-primary/5"
: "border-border hover:border-foreground/20 hover:bg-muted/30"
)}
onClick={() => fileInputRef.current?.click()}
>
<input
ref={fileInputRef}
type="file"
accept=".gguf"
className="hidden"
onChange={(e) => handleFiles(e.target.files)}
/>
<Upload className="h-6 w-6 mx-auto mb-2 text-muted-foreground" />
{uploadProgress ? (
<div className="space-y-1">
<p className="text-sm font-medium">{uploadProgress.name}</p>
<div className="h-2 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-primary transition-all"
style={{ width: `${uploadProgress.percent}%` }}
/>
</div>
<p className="text-xs text-muted-foreground">
{uploadProgress.percent}%
</p>
</div>
) : (
<>
<p className="text-sm font-medium">Drop .gguf here or click to upload</p>
<p className="text-xs text-muted-foreground mt-1">
Files are saved to <code className="font-mono">gpu/llama_models/</code>
</p>
</>
)}
</div>
{/* Download from URL */}
<div className="rounded-md border bg-muted/20 p-4 space-y-3">
<div className="flex items-start justify-between gap-2">
<div>
<span className="text-sm font-medium flex items-center gap-2">
<CloudDownload className="h-4 w-4" />
Download from URL
</span>
<p className="text-xs text-muted-foreground mt-0.5">
Fetch a .gguf file from HuggingFace, GitHub releases, or any
direct URL. CivitAI URLs are auto-converted (model page →
API download) and the saved token is appended.
</p>
</div>
<Button
size="sm"
variant="outline"
onClick={() => setShowCivitaiSettings((v) => !v)}
>
<KeyIcon className="h-3.5 w-3.5" />
CivitAI token
{civitaiToken ? (
<Badge variant="success" className="ml-1 text-[10px]">
set
</Badge>
) : (
<Badge variant="secondary" className="ml-1 text-[10px]">
empty
</Badge>
)}
</Button>
</div>
{showCivitaiSettings && (
<div className="rounded-md border bg-card p-3 space-y-2">
<Label htmlFor="civitai-token">CivitAI API token</Label>
<Input
id="civitai-token"
type="password"
value={civitaiTokenDraft}
onChange={(e) => setCivitaiTokenDraft(e.target.value)}
placeholder="Get it from https://civitai.com/user/account → API Keys"
className="font-mono text-xs"
/>
<div className="flex items-center gap-2">
<Button
size="sm"
onClick={() => onSaveCivitaiToken(civitaiTokenDraft)}
disabled={busy === "save-settings"}
>
Save
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => {
setCivitaiTokenDraft("");
onSaveCivitaiToken("");
}}
>
Clear
</Button>
<a
href="https://civitai.com/user/account"
target="_blank"
rel="noopener noreferrer"
className="ml-auto text-xs text-muted-foreground hover:underline"
>
Get token ↗
</a>
</div>
<p className="text-[10px] text-muted-foreground">
Stored locally in <code className="font-mono">gpu/dashboard/settings.json</code>.
Used to authenticate CivitAI downloads. Without it, NSFW /
gated models will fail with 401.
</p>
</div>
)}
<div className="flex items-end gap-2">
<div className="flex-1 space-y-1.5">
<Label htmlFor="download-url">URL</Label>
<Input
id="download-url"
value={downloadUrl}
onChange={(e) => setDownloadUrl(e.target.value)}
placeholder="https://huggingface.co/.../model.gguf or https://civitai.com/models/12345"
className="font-mono text-xs"
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
onDownload();
}
}}
/>
</div>
<Button
onClick={onDownload}
disabled={busy !== null || !downloadUrl.trim()}
>
<CloudDownload className="h-3.5 w-3.5" />
Download
</Button>
</div>
{/* URL preview — shows what we'll actually curl */}
{urlPreview && urlPreview.original !== urlPreview.transformed && (
<div className="rounded-md border bg-card p-2.5 text-xs space-y-1">
<div className="flex items-center gap-1.5">
<Badge variant={urlPreview.isCivitai ? "default" : "secondary"} className="text-[10px]">
{urlPreview.isCivitai ? "CivitAI" : "transformed"}
</Badge>
<span className="text-muted-foreground">{urlPreview.note}</span>
</div>
<pre className="font-mono text-[10px] text-foreground whitespace-pre-wrap break-all">
{urlPreview.transformed}
</pre>
</div>
)}
{/* Active downloads */}
{activeDownloads.length > 0 && (
<div className="space-y-2">
{activeDownloads.map((job) => (
<DownloadJobRow
key={job.id}
job={job}
onCancel={() => onCancelDownload(job.id)}
/>
))}
</div>
)}
{/* Recently finished downloads */}
{finishedDownloads.length > 0 && (
<div className="space-y-1.5 pt-2 border-t">
<Label>Recent</Label>
<div className="space-y-1">
{finishedDownloads.map((job) => (
<DownloadJobRow key={job.id} job={job} compact />
))}
</div>
</div>
)}
</div>
{/* Models table */}
{models.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<HardDrive className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No .gguf files found</p>
<p className="text-xs mt-1">
Drop them into <code className="font-mono">gpu/llama_models/</code>
{" "}or upload above
</p>
</div>
) : (
<div className="max-h-96 overflow-y-auto scrollbar-thin -mx-2">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-card">
<tr className="text-left text-xs text-muted-foreground border-b">
<th className="py-2 px-2 font-medium">Name</th>
<th className="py-2 px-2 font-medium w-32 text-right">Size</th>
<th className="py-2 px-2 font-medium w-32 text-right">Modified</th>
<th className="py-2 px-2 font-medium w-32 text-right">Actions</th>
</tr>
</thead>
<tbody>
{models.map((m) => (
<tr
key={m.name}
className="border-b border-border/40 hover:bg-muted/30"
>
<td className="py-2 px-2">
<div className="flex items-center gap-2">
<FileText className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
<span className="font-mono text-xs truncate">{m.name}</span>
{config.model === m.name && (
<Badge variant="success" className="text-[10px]">
active
</Badge>
)}
</div>
</td>
<td className="py-2 px-2 text-right font-mono text-xs">
{m.sizeHuman}
</td>
<td className="py-2 px-2 text-right text-xs text-muted-foreground">
{timeAgo(m.modifiedAt)}
</td>
<td className="py-2 px-2 text-right">
<div className="flex items-center justify-end gap-1">
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={config.model === m.name || busy !== null}
onClick={() => onSelectModel(m.name)}
>
Use
<ChevronRight className="h-3 w-3" />
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 hover:text-destructive"
disabled={busy !== null}
onClick={() => onDelete(m.name)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
);
}
function DownloadJobRow({
job,
onCancel,
compact = false,
}: {
job: DownloadJob;
onCancel?: () => void;
compact?: boolean;
}) {
const isActive = job.status === "downloading" || job.status === "queued";
const isDone = job.status === "done";
const isFailed = job.status === "failed";
const isCancelled = job.status === "cancelled";
const durationSec =
job.finishedAt != null
? (job.finishedAt - job.startedAt) / 1000
: (Date.now() - job.startedAt) / 1000;
const speedText =
job.speedBytesPerSec != null
? `${formatBytes(job.speedBytesPerSec)}/s`
: null;
const progressText =
job.bytesTotal != null && job.bytesTotal > 0
? `${formatBytes(job.bytesDownloaded)} / ${formatBytes(job.bytesTotal)}`
: job.bytesDownloaded > 0
? formatBytes(job.bytesDownloaded)
: "starting...";
return (
<div
className={cn(
"rounded-md border p-2.5 space-y-1.5 bg-card",
isFailed && "border-destructive/30",
isCancelled && "opacity-60",
isDone && "border-success/30"
)}
>
<div className="flex items-center gap-2">
<Badge
variant={
isActive
? "default"
: isDone
? "success"
: isFailed
? "destructive"
: "secondary"
}
className="text-[10px] shrink-0"
>
{job.status}
</Badge>
<span className="font-mono text-xs truncate flex-1">{job.filename}</span>
{isActive && onCancel && (
<Button
size="sm"
variant="ghost"
className="h-6 text-xs hover:text-destructive"
onClick={onCancel}
>
<X className="h-3 w-3" />
Cancel
</Button>
)}
</div>
{!compact && isActive && (
<>
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-primary transition-all"
style={{ width: `${job.percent}%` }}
/>
</div>
<div className="flex justify-between text-[10px] text-muted-foreground font-mono">
<span>{progressText}</span>
<span>
{job.percent > 0 ? `${job.percent.toFixed(1)}%` : ""}
{speedText ? ` · ${speedText}` : ""}
{` · ${durationSec.toFixed(0)}s elapsed`}
</span>
</div>
</>
)}
{!compact && (isFailed || isCancelled) && job.error && (
<p className="text-[10px] text-destructive font-mono">{job.error}</p>
)}
{compact && (
<div className="text-[10px] text-muted-foreground font-mono">
{isDone && formatBytes(job.bytesDownloaded)}
{isFailed && job.error && ` · ${job.error.slice(0, 80)}`}
{isCancelled && " · cancelled"}
{` · ${durationSec.toFixed(0)}s`}
</div>
)}
{/* URL transformation note (e.g. "added CivitAI token") */}
{!compact && job.urlNote && (
<div className="text-[10px] text-muted-foreground italic">
{job.urlNote}
</div>
)}
{/* Show source URL for reference (compact mode hides it) */}
{!compact && (
<div className="text-[10px] text-muted-foreground font-mono truncate">
{job.originalUrl && (
<span className="line-through opacity-60">
{job.originalUrl}
</span>
)}
{job.originalUrl && <span className="mx-1">→</span>}
<a
href={job.url}
target="_blank"
rel="noopener noreferrer"
className="hover:underline"
>
{job.url}
</a>
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Comfy Tab
// ---------------------------------------------------------------------------
function ComfyTab({
models,
queue,
types,
filter,
setFilter,
onRefreshModels,
onRefreshQueue,
onRefreshTypes,
onAdd,
addUrl,
setAddUrl,
addType,
setAddType,
onRemove,
busy,
}: {
models: ComfyModelEntry[];
queue: ComfyQueueEntry[];
types: string[];
filter: string;
setFilter: (v: string) => void;
onRefreshModels: () => void;
onRefreshQueue: () => void;
onRefreshTypes: () => void;
onAdd: () => void;
addUrl: string;
setAddUrl: (v: string) => void;
addType: string;
setAddType: (v: string) => void;
onRemove: (filename: string, type?: string) => void;
busy: string | null;
}) {
return (
<div className="space-y-4">
{/* Download queue */}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<div>
<CardTitle className="text-base flex items-center gap-2">
<CloudDownload className="h-4 w-4" />
Download Queue
</CardTitle>
<CardDescription>
Active downloads via model-worker
</CardDescription>
</div>
<Button size="sm" variant="outline" onClick={onRefreshQueue} disabled={busy !== null}>
<RefreshCw className="h-3.5 w-3.5" />
Refresh
</Button>
</CardHeader>
<CardContent>
{queue.length === 0 ? (
<p className="text-sm text-muted-foreground py-4 text-center">
Queue is empty
</p>
) : (
<div className="space-y-2 max-h-64 overflow-y-auto scrollbar-thin">
{queue.map((q) => (
<div
key={q.id}
className="rounded-md border p-3 space-y-2 bg-card"
>
<div className="flex items-center justify-between gap-2">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<Badge
variant={
q.status === "done"
? "success"
: q.status === "failed"
? "destructive"
: q.status === "downloading"
? "default"
: "secondary"
}
className="text-[10px]"
>
{q.status}
</Badge>
<span className="font-mono text-xs truncate">
{q.filename}
</span>
</div>
<div className="text-xs text-muted-foreground mt-0.5">
type: <code className="font-mono">{q.model_type}</code>
{q.total_bytes && (
<>
{" · "}
{formatBytes(q.downloaded_bytes)} /{" "}
{formatBytes(q.total_bytes)}
</>
)}
</div>
</div>
</div>
{q.status === "downloading" && q.progress != null && (
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-primary transition-all"
style={{ width: `${q.progress}%` }}
/>
</div>
)}
{q.error && (
<p className="text-xs text-destructive font-mono">{q.error}</p>
)}
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Add model */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Plus className="h-4 w-4" />
Queue Download
</CardTitle>
<CardDescription>
Mirrors <code className="font-mono text-xs">gpuctl comfy models add &lt;URL&gt; &lt;type&gt;</code>
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-2 sm:grid-cols-[1fr_180px_auto]">
<Input
placeholder="https://huggingface.co/.../model.safetensors"
value={addUrl}
onChange={(e) => setAddUrl(e.target.value)}
className="font-mono text-xs"
/>
<Select value={addType} onValueChange={setAddType}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{types.length === 0 ? (
<SelectItem value={addType} disabled>
No types available (worker offline?)
</SelectItem>
) : (
types.map((t) => (
<SelectItem key={t} value={t}>
{t}
</SelectItem>
))
)}
</SelectContent>
</Select>
<Button onClick={onAdd} disabled={busy !== null}>
<Plus className="h-3.5 w-3.5" />
Queue
</Button>
</div>
</CardContent>
</Card>
{/* Models list */}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<div>
<CardTitle className="text-base flex items-center gap-2">
<Layers className="h-4 w-4" />
Comfy Models
</CardTitle>
<CardDescription>
<code className="font-mono text-xs">/project/gpu/comfy/models</code>
{" · "}
{models.length} file(s)
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Select value={filter || "__all__"} onValueChange={(v) => setFilter(v === "__all__" ? "" : v)}>
<SelectTrigger className="w-40">
<SelectValue placeholder="All types" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__all__">All types</SelectItem>
{types.map((t) => (
<SelectItem key={t} value={t}>
{t}
</SelectItem>
))}
</SelectContent>
</Select>
<Button size="sm" variant="outline" onClick={onRefreshModels} disabled={busy !== null}>
<RefreshCw className="h-3.5 w-3.5" />
Refresh
</Button>
</div>
</CardHeader>
<CardContent>
{models.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<Layers className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No models found</p>
<p className="text-xs mt-1">
Queue a download above, or check that model-worker is running.
</p>
</div>
) : (
<div className="max-h-96 overflow-y-auto scrollbar-thin -mx-2">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-card">
<tr className="text-left text-xs text-muted-foreground border-b">
<th className="py-2 px-2 font-medium">Name</th>
<th className="py-2 px-2 font-medium w-32">Type</th>
<th className="py-2 px-2 font-medium w-28 text-right">Size</th>
<th className="py-2 px-2 font-medium w-16 text-right">Action</th>
</tr>
</thead>
<tbody>
{models.map((m, i) => (
<tr key={`${m.filename}-${i}`} className="border-b border-border/40 hover:bg-muted/30">
<td className="py-2 px-2">
<span className="font-mono text-xs truncate">{m.filename}</span>
</td>
<td className="py-2 px-2">
<Badge variant="outline" className="text-[10px]">
{m.type}
</Badge>
</td>
<td className="py-2 px-2 text-right text-xs font-mono">
{m.sizeHuman || "—"}
</td>
<td className="py-2 px-2 text-right">
<Button
size="sm"
variant="ghost"
className="h-7 hover:text-destructive"
disabled={busy !== null}
onClick={() => onRemove(m.filename, m.type)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
);
}
// ---------------------------------------------------------------------------
// Logs Tab
// ---------------------------------------------------------------------------
function LogsTab({
target,
setTarget,
liveLogs,
autoScroll,
setAutoScroll,
active,
onStart,
onStop,
onClear,
logsEndRef,
}: {
target: "llama" | "comfyui" | "dashboard" | "ssh";
setTarget: (t: "llama" | "comfyui" | "dashboard" | "ssh") => void;
liveLogs: { stream: "stdout" | "stderr"; line: string; ts?: number }[];
autoScroll: boolean;
setAutoScroll: (v: boolean) => void;
active: boolean;
onStart: () => void;
onStop: () => void;
onClear: () => void;
logsEndRef: React.RefObject<HTMLDivElement | null>;
}) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2 flex-wrap">
<div>
<CardTitle className="text-base flex items-center gap-2">
<Terminal className="h-4 w-4" />
Live Logs
</CardTitle>
<CardDescription>
Streaming <code className="font-mono text-xs">docker logs -f</code>
</CardDescription>
</div>
<div className="flex items-center gap-2 flex-wrap">
<Select value={target} onValueChange={(v) => setTarget(v as typeof target)}>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="llama">llama</SelectItem>
<SelectItem value="comfyui">comfyui</SelectItem>
<SelectItem value="dashboard">dashboard</SelectItem>
<SelectItem value="ssh">ssh-main</SelectItem>
</SelectContent>
</Select>
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<input
type="checkbox"
checked={autoScroll}
onChange={(e) => setAutoScroll(e.target.checked)}
/>
Auto-scroll
</label>
{active ? (
<Button size="sm" variant="outline" onClick={onStop}>
<Power className="h-3.5 w-3.5" />
Stop
</Button>
) : (
<Button size="sm" onClick={onStart}>
<Play className="h-3.5 w-3.5" />
Start
</Button>
)}
<Button size="sm" variant="ghost" onClick={onClear}>
<Trash2 className="h-3.5 w-3.5" />
Clear
</Button>
</div>
</CardHeader>
<CardContent>
<div className="h-[28rem] overflow-y-auto scrollbar-thin bg-zinc-950 dark:bg-black rounded-md border p-3 logs-terminal text-zinc-300">
{liveLogs.length === 0 ? (
<div className="text-muted-foreground italic">
Click "Start" to follow logs from {target}.
</div>
) : (
liveLogs.map((entry, i) => (
<div
key={i}
className={cn(
"whitespace-pre-wrap break-all",
entry.stream === "stderr" && "text-red-300",
entry.stream === "stdout" && /error|fail|exception/i.test(entry.line) && "text-red-400",
entry.stream === "stdout" && /warn/i.test(entry.line) && "text-yellow-400",
entry.stream === "stdout" && /^#|\binfo\b/i.test(entry.line) && "text-zinc-500"
)}
>
{entry.line}
</div>
))
)}
<div ref={logsEndRef} />
</div>
</CardContent>
</Card>
);
}
// ---------------------------------------------------------------------------
// System Tab
// ---------------------------------------------------------------------------
function SystemTab({
containers,
llamaHealth,
gpu,
instance,
busy,
onGpuRefresh,
onServiceAction,
}: {
containers: ContainerInfo[];
llamaHealth: { reachable: boolean; detail: string } | null;
gpu: string;
instance: string;
busy: string | null;
onGpuRefresh: () => void;
onServiceAction: (role: string, action: "start" | "stop" | "restart" | "remove") => void;
}) {
return (
<div className="space-y-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<div>
<CardTitle className="text-base flex items-center gap-2">
<CpuIcon className="h-4 w-4" />
GPU Status
</CardTitle>
<CardDescription>nvidia-smi output</CardDescription>
</div>
<Button size="sm" variant="outline" onClick={onGpuRefresh} disabled={busy === "gpu"}>
<RefreshCw className="h-3.5 w-3.5" />
Refresh
</Button>
</CardHeader>
<CardContent>
{gpu ? (
<pre className="text-xs font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-3 max-h-96 overflow-y-auto scrollbar-thin">
{gpu}
</pre>
) : (
<p className="text-sm text-muted-foreground">
Click "Refresh" to query nvidia-smi.
</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Server className="h-4 w-4" />
Containers
</CardTitle>
<CardDescription>
All services for instance <code className="font-mono text-xs">{instance}</code>
{" · "}click action buttons to manage
</CardDescription>
</CardHeader>
<CardContent>
{containers.length === 0 ? (
<p className="text-sm text-muted-foreground">
No containers found. Docker socket not reachable?
</p>
) : (
<div className="max-h-[28rem] overflow-y-auto scrollbar-thin -mx-2">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-card">
<tr className="text-left text-xs text-muted-foreground border-b">
<th className="py-2 px-2 font-medium">Name</th>
<th className="py-2 px-2 font-medium w-24">Role</th>
<th className="py-2 px-2 font-medium w-32">Status</th>
<th className="py-2 px-2 font-medium w-44 text-right">Actions</th>
</tr>
</thead>
<tbody>
{containers.map((c) => (
<tr key={c.name} className="border-b border-border/40 hover:bg-muted/30">
<td className="py-2 px-2">
<span className="font-mono text-xs">{c.name}</span>
<div className="text-[10px] text-muted-foreground font-mono truncate max-w-[20rem]">
{c.image}
</div>
</td>
<td className="py-2 px-2">
{c.role && (
<Badge
variant={c.role === "llama" ? "default" : "outline"}
className="text-[10px]"
>
{c.role}
</Badge>
)}
</td>
<td className="py-2 px-2">
<Badge
variant={
c.running
? "success"
: c.state === "exited"
? "secondary"
: "outline"
}
className="text-[10px]"
>
{c.statusText}
</Badge>
</td>
<td className="py-2 px-2 text-right">
<div className="flex items-center justify-end gap-1">
<button
title="Start"
disabled={busy !== null || c.running || c.role === "tailscale"}
onClick={() => onServiceAction(c.role || "", "start")}
className="p-1 rounded hover:bg-success/10 hover:text-success disabled:opacity-30"
>
<Play className="h-3.5 w-3.5" />
</button>
<button
title="Restart"
disabled={busy !== null || !c.running || c.role === "tailscale"}
onClick={() => onServiceAction(c.role || "", "restart")}
className="p-1 rounded hover:bg-muted hover:text-foreground disabled:opacity-30"
>
<RotateCw className="h-3.5 w-3.5" />
</button>
<button
title="Stop"
disabled={busy !== null || !c.running || c.role === "tailscale"}
onClick={() => onServiceAction(c.role || "", "stop")}
className="p-1 rounded hover:bg-warning/10 hover:text-warning disabled:opacity-30"
>
<Square className="h-3.5 w-3.5" />
</button>
<button
title="Remove"
disabled={busy !== null || c.role === "tailscale" || c.role === "ssh-main"}
onClick={() => onServiceAction(c.role || "", "remove")}
className="p-1 rounded hover:bg-destructive/10 hover:text-destructive disabled:opacity-30"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
{llamaHealth && (
<Card>
<CardHeader>
<CardTitle className="text-base">Llama /health</CardTitle>
<CardDescription>
Query <code className="font-mono text-xs">http://llama:8080/health</code>
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-3">
<Badge variant={llamaHealth.reachable ? "success" : "destructive"}>
{llamaHealth.reachable ? "OK" : "Unreachable"}
</Badge>
<pre className="text-xs font-mono flex-1 whitespace-pre-wrap">
{llamaHealth.detail}
</pre>
</div>
</CardContent>
</Card>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Chat Tab — talk to the running llama model directly
// ---------------------------------------------------------------------------
interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
// For assistant only — timings from llama.cpp response
timings?: {
predicted_n?: number;
predicted_ms?: number;
predicted_per_second?: number;
prompt_n?: number;
prompt_ms?: number;
prompt_per_second?: number;
cache_hit_rate?: number;
};
// For assistant only — speculative decoding stats
specAccepted?: number;
specDrafted?: number;
}
function ChatTab({
systemPrompt,
temperature,
topP,
topK,
minP,
repeatPenalty,
llamaRunning,
}: {
systemPrompt: string;
temperature: number;
topP: number;
topK: number;
minP: number;
repeatPenalty: number;
llamaRunning: boolean;
}) {
const [messages, setMessages] = React.useState<ChatMessage[]>([]);
const [input, setInput] = React.useState("");
const [streaming, setStreaming] = React.useState(false);
const [autoScroll, setAutoScroll] = React.useState(true);
const abortRef = React.useRef<AbortController | null>(null);
const messagesEndRef = React.useRef<HTMLDivElement | null>(null);
// Reset chat on mount if systemPrompt changes
React.useEffect(() => {
if (messages.length === 0 && systemPrompt) {
setMessages([{ role: "system", content: systemPrompt }]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [systemPrompt]);
React.useEffect(() => {
if (autoScroll) {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}, [messages, autoScroll]);
async function handleSend() {
if (!input.trim() || streaming || !llamaRunning) return;
const userMsg: ChatMessage = { role: "user", content: input.trim() };
setInput("");
const allMsgs = [...messages, userMsg];
setMessages(allMsgs);
setStreaming(true);
const controller = new AbortController();
abortRef.current = controller;
// Add an empty assistant message we'll stream into
const assistantIdx = allMsgs.length;
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: allMsgs,
temperature,
top_p: topP,
top_k: topK,
min_p: minP,
repeat_penalty: repeatPenalty,
stream: true,
}),
signal: controller.signal,
});
if (!res.ok || !res.body) {
const errText = await res.text().catch(() => "");
setMessages((prev) => {
const next = [...prev];
next[assistantIdx] = {
role: "assistant",
content: `[error: ${res.status} ${errText.slice(0, 200)}]`,
};
return next;
});
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
let finalTimings: ChatMessage["timings"] | undefined;
let specAccepted: number | undefined;
let specDrafted: number | undefined;
const pump = (): Promise<void> =>
reader.read().then(({ done, value }) => {
if (done) return;
buf += decoder.decode(value, { stream: true });
// Parse SSE chunks: lines starting with "data: "
const lines = buf.split("\n");
buf = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice("data: ".length).trim();
if (payload === "[DONE]") continue;
try {
const chunk = JSON.parse(payload);
// OpenAI-compatible chunk has choices[0].delta.content
const delta = chunk.choices?.[0]?.delta?.content;
if (typeof delta === "string" && delta.length > 0) {
setMessages((prev) => {
const next = [...prev];
const cur = next[assistantIdx];
next[assistantIdx] = {
...cur,
content: (cur?.content || "") + delta,
};
return next;
});
}
// Capture timings if present (llama.cpp includes them in the
// final chunk under choices[0].timings or under .timings)
const t = chunk.choices?.[0]?.timings || chunk.timings;
if (t) {
finalTimings = {
predicted_n: t.predicted_n,
predicted_ms: t.predicted_ms,
predicted_per_second: t.predicted_per_second,
prompt_n: t.prompt_n,
prompt_ms: t.prompt_ms,
prompt_per_second: t.prompt_per_second,
cache_hit_rate: t.cache_hit_rate,
};
if (t.spec_accepted != null)
specAccepted = t.spec_accepted;
if (t.spec_drafted != null)
specDrafted = t.spec_drafted;
}
} catch {
/* ignore malformed chunk */
}
}
return pump();
});
await pump();
// Attach timings to the final assistant message
if (finalTimings) {
setMessages((prev) => {
const next = [...prev];
const cur = next[assistantIdx];
next[assistantIdx] = {
...cur,
timings: finalTimings,
specAccepted,
specDrafted,
};
return next;
});
}
} catch (err) {
if ((err as Error).name !== "AbortError") {
setMessages((prev) => {
const next = [...prev];
next[assistantIdx] = {
role: "assistant",
content: `[error: ${(err as Error).message}]`,
};
return next;
});
}
} finally {
setStreaming(false);
abortRef.current = null;
}
}
function handleStop() {
if (abortRef.current) {
abortRef.current.abort();
abortRef.current = null;
}
setStreaming(false);
}
function handleClear() {
setMessages(systemPrompt ? [{ role: "system", content: systemPrompt }] : []);
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2 flex-wrap">
<div>
<CardTitle className="text-base flex items-center gap-2">
<MessageSquare className="h-4 w-4" />
Chat
</CardTitle>
<CardDescription>
Streaming chat with the running llama model · OpenAI-compatible
</CardDescription>
</div>
<div className="flex items-center gap-2">
<label className="flex items-center gap-1.5 text-xs text-muted-foreground">
<input
type="checkbox"
checked={autoScroll}
onChange={(e) => setAutoScroll(e.target.checked)}
/>
Auto-scroll
</label>
<Button size="sm" variant="ghost" onClick={handleClear}>
<Trash2 className="h-3.5 w-3.5" />
Clear
</Button>
</div>
</CardHeader>
<CardContent className="space-y-3">
{!llamaRunning && (
<div className="rounded-md border border-warning/30 bg-warning/5 p-3 text-sm">
<span className="text-warning font-medium">Llama is not running.</span>{" "}
<span className="text-muted-foreground">
Start it from the System tab or use the &quot;Start Llama&quot;
quick action above.
</span>
</div>
)}
{/* Messages */}
<div className="h-[28rem] overflow-y-auto scrollbar-thin space-y-3 rounded-md border bg-zinc-950 dark:bg-black p-3">
{messages.length === 0 && (
<div className="text-muted-foreground italic text-center py-12">
Send a message to start chatting.
</div>
)}
{messages.map((m, i) => (
<MessageBubble key={i} message={m} />
))}
<div ref={messagesEndRef} />
</div>
{/* Input */}
<div className="flex items-end gap-2">
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message... (Ctrl+Enter to send)"
rows={2}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
handleSend();
}
}}
className="flex-1 resize-none"
disabled={!llamaRunning || streaming}
/>
{streaming ? (
<Button onClick={handleStop} variant="destructive">
<Square className="h-3.5 w-3.5" />
Stop
</Button>
) : (
<Button
onClick={handleSend}
disabled={!llamaRunning || !input.trim()}
>
<Send className="h-3.5 w-3.5" />
Send
</Button>
)}
</div>
</CardContent>
</Card>
);
}
function MessageBubble({ message }: { message: ChatMessage }) {
const isUser = message.role === "user";
const isAssistant = message.role === "assistant";
const isSystem = message.role === "system";
if (isSystem) {
return (
<div className="text-xs text-muted-foreground italic border-l-2 border-muted pl-2">
<span className="font-medium">system:</span> {message.content}
</div>
);
}
return (
<div className={cn("flex gap-2", isUser ? "justify-end" : "justify-start")}>
<div
className={cn(
"max-w-[85%] rounded-md px-3 py-2 text-sm",
isUser
? "bg-primary text-primary-foreground"
: "bg-muted text-foreground"
)}
>
<div className="whitespace-pre-wrap break-words">{message.content}</div>
{isAssistant && message.timings && (
<MessageStats message={message} />
)}
</div>
</div>
);
}
function MessageStats({ message }: { message: ChatMessage }) {
const t = message.timings;
if (!t) return null;
return (
<div className="mt-2 pt-2 border-t border-border/30 text-[10px] font-mono text-muted-foreground space-y-0.5">
{t.predicted_per_second != null && (
<div>
<span className="text-foreground">TPS:</span>{" "}
{t.predicted_per_second.toFixed(1)} tok/s
{t.predicted_n != null && t.predicted_ms != null && (
<span className="ml-2">
({t.predicted_n} tok in {(t.predicted_ms / 1000).toFixed(2)}s)
</span>
)}
</div>
)}
{t.prompt_n != null && (
<div>
<span className="text-foreground">Prompt:</span> {t.prompt_n} tok
{t.prompt_ms != null && (
<span className="ml-2">
({(t.prompt_ms / 1000).toFixed(2)}s
{t.prompt_per_second != null &&
`, ${t.prompt_per_second.toFixed(1)} tok/s`}
)
</span>
)}
</div>
)}
{t.cache_hit_rate != null && (
<div>
<span className="text-foreground">Cache hit:</span>{" "}
{(t.cache_hit_rate * 100).toFixed(1)}%
</div>
)}
{message.specDrafted != null && message.specAccepted != null && (
<div>
<span className="text-foreground">Spec decoding:</span>{" "}
{message.specAccepted}/{message.specDrafted} accepted
{message.specDrafted > 0 && (
<span className="ml-1">
({((message.specAccepted / message.specDrafted) * 100).toFixed(0)}%)
</span>
)}
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Perf Tab — live TPS / TTFT / cache-hit / spec-decoding metrics
// ---------------------------------------------------------------------------
interface SlotInfo {
id: number;
is_processing: boolean;
n_ctx: number;
n_past: number;
n_eval: number;
prompt: number[];
timings?: {
prompt_n: number;
prompt_ms: number;
prompt_per_token: number;
prompt_per_second: number;
predicted_n: number;
predicted_ms: number;
predicted_per_token: number;
predicted_per_second: number;
cache_hit_rate?: number;
};
// Speculative decoding stats (if --spec-* was passed at startup)
spec?: {
accepted: number;
drafted: number;
rate: number;
};
}
function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
const [slots, setSlots] = React.useState<SlotInfo[]>([]);
const [metricsRaw, setMetricsRaw] = React.useState<string>("");
const [active, setActive] = React.useState(false);
const [view, setView] = React.useState<"slots" | "metrics">("slots");
React.useEffect(() => {
if (!active || !llamaRunning) return;
let cancelled = false;
async function poll() {
if (cancelled) return;
try {
if (view === "slots") {
const res = await fetch("/api/slots", { cache: "no-store" });
if (res.ok) {
const data = await res.json();
if (!cancelled) setSlots(data.slots || []);
}
} else {
const res = await fetch("/api/metrics", { cache: "no-store" });
if (res.ok) {
const text = await res.text();
if (!cancelled) setMetricsRaw(text);
}
}
} catch {
/* ignore — will retry */
}
}
poll();
const id = setInterval(poll, 1500);
return () => {
cancelled = true;
clearInterval(id);
};
}, [active, llamaRunning, view]);
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2 flex-wrap">
<div>
<CardTitle className="text-base flex items-center gap-2">
<Gauge className="h-4 w-4" />
Performance
</CardTitle>
<CardDescription>
TPS · TTFT · cache-hit · speculative decoding
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Select value={view} onValueChange={(v) => setView(v as "slots" | "metrics")}>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="slots">Slots</SelectItem>
<SelectItem value="metrics">Prometheus</SelectItem>
</SelectContent>
</Select>
<Button
size="sm"
variant={active ? "outline" : "default"}
onClick={() => setActive(!active)}
disabled={!llamaRunning}
>
{active ? (
<>
<Power className="h-3.5 w-3.5" />
Pause
</>
) : (
<>
<Play className="h-3.5 w-3.5" />
Live
</>
)}
</Button>
</div>
</CardHeader>
<CardContent>
{!llamaRunning ? (
<div className="text-center py-12 text-muted-foreground">
<Gauge className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Llama is not running</p>
<p className="text-xs mt-1">
Start it to see live performance metrics.
</p>
</div>
) : view === "slots" ? (
<SlotsView slots={slots} />
) : (
<pre className="text-xs font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-3 max-h-[32rem] overflow-y-auto scrollbar-thin">
{metricsRaw || "[no metrics — was llama started with --metrics?]"}
</pre>
)}
</CardContent>
</Card>
);
}
function SlotsView({ slots }: { slots: SlotInfo[] }) {
if (slots.length === 0) {
return (
<p className="text-sm text-muted-foreground text-center py-8">
No active slots. Start a chat to see metrics.
</p>
);
}
return (
<div className="space-y-3">
{slots.map((s) => (
<div key={s.id} className="rounded-md border p-3 bg-card space-y-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Badge variant={s.is_processing ? "default" : "secondary"}>
{s.is_processing ? "processing" : "idle"}
</Badge>
<span className="text-xs text-muted-foreground font-mono">
slot #{s.id}
</span>
</div>
<div className="text-xs text-muted-foreground font-mono">
ctx: {s.n_past}/{s.n_ctx}
</div>
</div>
{s.timings ? (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
<MetricCell
label="TPS"
value={
s.timings.predicted_per_second != null
? `${s.timings.predicted_per_second.toFixed(1)} tok/s`
: "—"
}
hint={
s.timings.predicted_n != null
? `${s.timings.predicted_n} tok / ${(s.timings.predicted_ms / 1000).toFixed(2)}s`
: undefined
}
/>
<MetricCell
label="TTFT"
value={
s.timings.prompt_ms != null
? `${(s.timings.prompt_ms / 1000).toFixed(2)}s`
: "—"
}
hint={
s.timings.prompt_n != null
? `${s.timings.prompt_n} prompt tok`
: undefined
}
/>
<MetricCell
label="Prompt TPS"
value={
s.timings.prompt_per_second != null
? `${s.timings.prompt_per_second.toFixed(1)} tok/s`
: "—"
}
/>
<MetricCell
label="Cache hit"
value={
s.timings.cache_hit_rate != null
? `${(s.timings.cache_hit_rate * 100).toFixed(1)}%`
: "—"
}
/>
</div>
) : (
<p className="text-xs text-muted-foreground italic">
No timings yet — slot hasn&apos;t processed any tokens.
</p>
)}
{s.spec && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs pt-2 border-t">
<MetricCell
label="Spec drafted"
value={`${s.spec.drafted}`}
/>
<MetricCell
label="Spec accepted"
value={`${s.spec.accepted}`}
/>
<MetricCell
label="Accept rate"
value={
s.spec.drafted > 0
? `${((s.spec.accepted / s.spec.drafted) * 100).toFixed(0)}%`
: "—"
}
/>
</div>
)}
</div>
))}
</div>
);
}
function MetricCell({
label,
value,
hint,
}: {
label: string;
value: string;
hint?: string;
}) {
return (
<div>
<div className="text-[10px] uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div className="text-sm font-mono text-foreground">{value}</div>
{hint && (
<div className="text-[10px] text-muted-foreground font-mono">{hint}</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Helper components
// ---------------------------------------------------------------------------
function ToggleRow({
label,
hint,
checked,
onChange,
}: {
label: string;
hint?: string;
checked: boolean;
onChange: (v: boolean) => void;
}) {
return (
<label className="flex items-start gap-2 cursor-pointer rounded-md border bg-card p-2 hover:bg-muted/30">
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
className="mt-0.5"
/>
<div className="flex-1 min-w-0">
<div className="text-xs font-medium">{label}</div>
{hint && (
<div className="text-[10px] text-muted-foreground">{hint}</div>
)}
</div>
</label>
);
}
function QuickActionCard({
icon,
label,
description,
color,
disabled,
loading,
onClick,
}: {
icon: React.ReactNode;
label: string;
description: string;
color: "success" | "warning" | "destructive" | "default";
disabled?: boolean;
loading?: boolean;
onClick: () => void;
}) {
return (
<button
onClick={onClick}
disabled={disabled}
className={cn(
"group relative flex flex-col items-start gap-1 rounded-lg border bg-card p-4 text-left transition-all hover:shadow-md hover:border-foreground/20 disabled:opacity-50 disabled:pointer-events-none",
color === "success" && "hover:border-success/40",
color === "warning" && "hover:border-warning/40",
color === "destructive" && "hover:border-destructive/40"
)}
>
<div className="flex items-center gap-2">
<div
className={cn(
"flex h-8 w-8 items-center justify-center rounded-md",
color === "success" && "bg-success/10 text-success",
color === "warning" && "bg-warning/10 text-warning",
color === "destructive" && "bg-destructive/10 text-destructive",
color === "default" && "bg-muted text-foreground"
)}
>
{loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : icon}
</div>
<span className="font-medium">{label}</span>
</div>
<p className="text-xs text-muted-foreground">{description}</p>
</button>
);
}
function Toast({
toast,
onClose,
}: {
toast: { type: "success" | "error" | "info"; message: string };
onClose: () => void;
}) {
// If message has multiple lines, render as pre-formatted text (so logs are
// readable); otherwise normal flow.
const isMultiLine = toast.message.includes("\n");
return (
<div
className={cn(
"fixed bottom-4 right-4 z-50 max-w-md rounded-md border bg-card shadow-lg p-3 pr-9 text-sm",
toast.type === "success" && "border-success/30",
toast.type === "error" && "border-destructive/30",
toast.type === "info" && "border-border"
)}
>
<div className="flex items-start gap-2">
<div
className={cn(
"mt-0.5 h-2 w-2 rounded-full shrink-0",
toast.type === "success" && "bg-success",
toast.type === "error" && "bg-destructive",
toast.type === "info" && "bg-muted-foreground"
)}
/>
{isMultiLine ? (
<pre className="text-foreground whitespace-pre-wrap break-all font-mono text-[11px] leading-tight max-h-60 overflow-y-auto scrollbar-thin">
{toast.message}
</pre>
) : (
<span className="text-foreground">{toast.message}</span>
)}
</div>
<button
onClick={onClose}
className="absolute right-2 top-2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
);
}
// -----------------------------------------------------------------------------
// Preview builder (must match server-side buildLlamaExtraArgs)
// -----------------------------------------------------------------------------
function buildPreviewArgs(cfg: DashboardConfig): string {
const parts: string[] = [];
parts.push(`--ctx-size ${cfg.ctxSize}`);
parts.push(`--parallel ${cfg.parallel}`);
if (cfg.nGpuLayers >= 0) parts.push(`--n-gpu-layers ${cfg.nGpuLayers}`);
if (cfg.threads > 0) parts.push(`--threads ${cfg.threads}`);
parts.push(`--batch-size ${cfg.batchSize}`);
parts.push(`--ubatch-size ${cfg.ubatchSize}`);
if (cfg.contextOverflow !== "none")
parts.push(`--context-overflow ${cfg.contextOverflow}`);
parts.push(`--cache-type-k ${cfg.cacheTypeK}`);
parts.push(`--cache-type-v ${cfg.cacheTypeV}`);
if (cfg.defragThold >= 0 && cfg.defragThold !== 0.1)
parts.push(`--defrag-thold ${cfg.defragThold}`);
// --flash-attn takes on/off/auto in modern llama.cpp (bare flag fails)
parts.push(`--flash-attn ${cfg.flashAttn ? "on" : "off"}`);
// --mlock / --no-mmap → unified --load-mode in modern llama.cpp
if (cfg.mlock && cfg.noMmap) {
parts.push("--load-mode mlock");
} else if (cfg.mlock) {
parts.push("--load-mode mmap+mlock");
} else if (cfg.noMmap) {
parts.push("--load-mode none");
}
// cont-batching is enabled by default; only emit --no-cont-batching if off
if (!cfg.contBatching) parts.push("--no-cont-batching");
if (cfg.embeddings) parts.push("--embeddings");
if (cfg.metrics) parts.push("--metrics");
if (cfg.ropeFreqScale !== 1.0)
parts.push(`--rope-freq-scale ${cfg.ropeFreqScale}`);
if (cfg.ropeScale !== 1.0)
parts.push(`--rope-scale ${cfg.ropeScale}`);
if (cfg.yarnExtFactor !== 1.0)
parts.push(`--yarn-ext-factor ${cfg.yarnExtFactor}`);
if (cfg.yarnAttnFactor !== 1.0)
parts.push(`--yarn-attn-factor ${cfg.yarnAttnFactor}`);
if (cfg.yarnBetaFast !== 32.0)
parts.push(`--yarn-beta-fast ${cfg.yarnBetaFast}`);
if (cfg.yarnBetaSlow !== 1.0)
parts.push(`--yarn-beta-slow ${cfg.yarnBetaSlow}`);
if (cfg.specType !== "none") {
parts.push(`--spec-type ${cfg.specType}`);
if (cfg.draftModel) {
parts.push(`--model-draft /models/${cfg.draftModel}`);
parts.push(`--spec-draft-n-max ${cfg.specDraftNMax}`);
}
}
if (cfg.topK > 0) parts.push(`--top-k ${cfg.topK}`);
if (cfg.topP < 1.0) parts.push(`--top-p ${cfg.topP}`);
if (cfg.minP > 0) parts.push(`--min-p ${cfg.minP}`);
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
if (cfg.repeatPenalty > 1.0)
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}