"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, Volume2, } 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"; import { DASHBOARD_VERSION } from "@/lib/version"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- type ModelKind = "base" | "mmproj" | "mtp" | "draft"; interface ModelFile { name: string; relativePath: string; subdir: string; kind: ModelKind; 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; createdAt: string; } interface DashboardConfig { model: string; ctxSize: number; parallel: number; nGpuLayers: number; threads: number; draftModel: string; /** Optional mmproj file (multimodal vision projector) */ mmprojPath: 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; perf: 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; nPredict: number; reasoningFormat: "none" | "deepthink" | "auto"; jinja: boolean; 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: "", mmprojPath: "", 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, perf: true, 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, nPredict: -1, reasoningFormat: "auto", jinja: true, 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(DEFAULT_CONFIG); const [models, setModels] = React.useState([]); const [containers, setContainers] = React.useState([]); const [llamaHealth, setLlamaHealth] = React.useState<{ reachable: boolean; detail: string; } | null>(null); const [gpu, setGpu] = React.useState(""); const [instance, setInstance] = React.useState("gpu-node"); const [lastUpdated, setLastUpdated] = React.useState(""); const [busy, setBusy] = React.useState(null); const [toast, setToast] = React.useState<{ type: "success" | "error" | "info"; message: string; } | null>(null); const toastTimer = React.useRef | 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" | "tts" >("llama"); const logsEndRef = React.useRef(null); const logsEventSourceRef = React.useRef(null); const logsActiveRef = React.useRef(false); // Comfy const [comfyModels, setComfyModels] = React.useState([]); const [comfyQueue, setComfyQueue] = React.useState([]); const [comfyFilter, setComfyFilter] = React.useState(""); 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(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([]); const [downloadUrl, setDownloadUrl] = React.useState(""); const downloadsActiveRef = React.useRef(false); // Settings (civitai token etc) const [settings, setSettings] = React.useState({ civitaiToken: "", }); const [urlPreview, setUrlPreview] = React.useState(null); // Separate preview state for the Comfy tab's URL field (same logic as urlPreview, // just tracks a different input) const [comfyUrlPreview, setComfyUrlPreview] = React.useState(null); // Chat state — kept at top level so switching tabs doesn't reset the // conversation. ChatTab is mounted/unmounted when the user clicks the tab. const [chatMessages, setChatMessages] = React.useState([]); const [chatInput, setChatInput] = React.useState(""); const [chatStreaming, setChatStreaming] = React.useState(false); const [chatAutoScroll, setChatAutoScroll] = React.useState(true); const chatAbortRef = React.useRef(null); const chatMessagesEndRef = React.useRef(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, 2000); 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((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>(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 | 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]); // Same debounced preview, but for the Comfy tab's URL field const comfyPreviewDebounceRef = React.useRef | null>(null); React.useEffect(() => { if (comfyPreviewDebounceRef.current) clearTimeout(comfyPreviewDebounceRef.current); comfyPreviewDebounceRef.current = setTimeout(() => { void (async () => { if (!comfyAddUrl.trim()) { setComfyUrlPreview(null); return; } try { const res = await fetch("/api/settings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "preview-url", url: comfyAddUrl }), }); if (!res.ok) return; const data = await res.json(); if (data.ok) { setComfyUrlPreview({ original: data.original, transformed: data.transformed, note: data.note, isCivitai: data.isCivitai, }); } } catch { /* ignore */ } })(); }, 400); return () => { if (comfyPreviewDebounceRef.current) clearTimeout(comfyPreviewDebounceRef.current); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [comfyAddUrl]); 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); } } // --------------------------------------------------------------------------- // Chat handlers (state lives at top level to survive tab switches) // --------------------------------------------------------------------------- React.useEffect(() => { if (chatAutoScroll) { chatMessagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); } }, [chatMessages, chatAutoScroll]); // Cleanup any in-flight chat request on unmount React.useEffect(() => { return () => { if (chatAbortRef.current) { chatAbortRef.current.abort(); chatAbortRef.current = null; } }; }, []); async function handleChatSend() { if (!chatInput.trim() || chatStreaming || !llamaContainer?.running) return; const userMsg: ChatMessage = { role: "user", content: chatInput.trim() }; const systemMsg: ChatMessage | null = config.systemPrompt.trim() ? { role: "system", content: config.systemPrompt.trim() } : null; const inputText = chatInput; setChatInput(""); // Build the messages we send to the server: system + history + new user msg const historyForServer: ChatMessage[] = systemMsg ? [systemMsg, ...chatMessages.filter((m) => m.role !== "system"), userMsg] : [...chatMessages.filter((m) => m.role !== "system"), userMsg]; // For display: history + new user msg + empty assistant placeholder const allMsgs = [...chatMessages, userMsg]; setChatMessages([...allMsgs, { role: "assistant", content: "" }]); setChatStreaming(true); const controller = new AbortController(); chatAbortRef.current = controller; const assistantIdx = allMsgs.length; try { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: historyForServer, temperature: config.temperature, top_p: config.topP, top_k: config.topK, min_p: config.minP, repeat_penalty: config.repeatPenalty, // Pass nPredict as max_tokens (-1 = infinity, model decides) max_tokens: config.nPredict, reasoning_format: config.reasoningFormat, stream: true, }), signal: controller.signal, }); if (!res.ok || !res.body) { const errText = await res.text().catch(() => ""); setChatMessages((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 => reader.read().then(({ done, value }) => { if (done) return; buf += decoder.decode(value, { stream: true }); 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); const choice = chunk.choices?.[0]; const delta = choice?.delta; // Regular content const contentDelta = delta?.content; // Reasoning content (thinking blocks) — separate stream const reasoningDelta = delta?.reasoning_content; setChatMessages((prev) => { const next = [...prev]; const cur = next[assistantIdx]; if (cur) { if (typeof contentDelta === "string" && contentDelta.length > 0) { cur.content = (cur.content || "") + contentDelta; } if (typeof reasoningDelta === "string" && reasoningDelta.length > 0) { cur.reasoning = (cur.reasoning || "") + reasoningDelta; } } return next; }); // Capture timings (llama.cpp puts them in choice.timings or chunk.timings) const t = choice?.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 ?? t.cache_hit, }; 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 || specAccepted != null || specDrafted != null) { setChatMessages((prev) => { const next = [...prev]; const cur = next[assistantIdx]; if (cur) { if (finalTimings) cur.timings = finalTimings; if (specAccepted != null) cur.specAccepted = specAccepted; if (specDrafted != null) cur.specDrafted = specDrafted; } return next; }); } } catch (err) { if ((err as Error).name !== "AbortError") { setChatMessages((prev) => { const next = [...prev]; next[assistantIdx] = { role: "assistant", content: `[error: ${(err as Error).message}]`, }; return next; }); } else { // Aborted — leave whatever was streamed so far } } finally { setChatStreaming(false); chatAbortRef.current = null; } void inputText; // suppress unused } function handleChatStop() { if (chatAbortRef.current) { chatAbortRef.current.abort(); chatAbortRef.current = null; } setChatStreaming(false); } function handleChatClear() { setChatMessages([]); } 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(); // Build a helpful message — if the URL was transformed (CivitAI // model page → API download URL with token), include the note so the // user can see what happened. let message: string; if (data.ok) { message = `Queued: ${comfyAddType}`; if (data.urlNote) { message += `\n${data.urlNote}`; } if (data.transformedUrl) { message += `\n→ ${data.transformedUrl}`; } } else { message = data.error || "Failed"; } return { ok: data.ok, message }; }, 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( key: K, value: DashboardConfig[K] ) { setConfig((prev) => ({ ...prev, [key]: value })); } // --------------------------------------------------------------------------- // Render // --------------------------------------------------------------------------- const llamaStatus: "running" | "stopped" | "absent" = llamaContainer ? llamaContainer.running ? "running" : "stopped" : "absent"; return (
handleSystemAction("sleep")} onWake={() => handleSystemAction("wake")} onUpdate={() => handleSystemAction("update")} busy={busy} />
{/* Quick actions row — llama */}
} label="Start Llama" description="Apply config + launch llama.cpp" color="success" disabled={busy !== null} loading={busy === "start-llama"} onClick={handleStartLlama} /> } label="Restart Llama" description="Restart llama container" color="default" disabled={!llamaContainer || busy !== null} loading={busy === "llama-restart"} onClick={() => handleLlamaAction("restart")} /> } label="Stop Llama" description="Stop llama (keeps container)" color="warning" disabled={!llamaContainer?.running || busy !== null} loading={busy === "llama-stop"} onClick={() => handleLlamaAction("stop")} /> } label="Remove Llama" description="Force-remove llama container" color="destructive" disabled={!llamaContainer || busy !== null} loading={busy === "llama-remove"} onClick={() => handleLlamaAction("remove")} />
{/* Quick actions row — comfy + system */}
} label="Start Comfy" description="Launch ComfyUI" color="success" disabled={busy !== null} loading={busy === "comfy-start"} onClick={() => handleComfyAction("start")} /> } label="Restart Comfy" description="Restart ComfyUI container" color="default" disabled={!comfyContainer || busy !== null} loading={busy === "comfy-restart"} onClick={() => handleComfyAction("restart")} /> } label="Stop Comfy" description="Stop ComfyUI" color="warning" disabled={!comfyContainer?.running || busy !== null} loading={busy === "comfy-stop"} onClick={() => handleComfyAction("stop")} /> } label="Refresh GPU" description="Query nvidia-smi" color="default" disabled={busy !== null} loading={busy === "gpu"} onClick={refreshGpu} />
{/* Tabs */} Config Chat Perf Models Comfy Logs {liveLogs.length > 0 && ( {liveLogs.length} )} TTS System {/* Config tab */} {/* Chat tab */} {/* Perf tab */} {/* Models tab */} update("model", m)} onUseMmproj={(m) => update("mmprojPath", m)} onUseDraft={(m) => update("draftModel", m)} onUpload={handleUpload} onDelete={handleDeleteModel} downloadJobs={downloadJobs} downloadUrl={downloadUrl} setDownloadUrl={setDownloadUrl} onDownload={handleDownload} onCancelDownload={handleCancelDownload} civitaiToken={settings.civitaiToken} onSaveCivitaiToken={handleSaveCivitaiToken} urlPreview={urlPreview} /> {/* Comfy tab */} {/* Logs tab */} setLiveLogs([])} logsEndRef={logsEndRef} /> {/* System tab */} c.role === "tts")?.running} busy={busy} onServiceAction={handleServiceAction} />
{toast && setToast(null)} />}
); } // --------------------------------------------------------------------------- // 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 (

GPU Node Dashboard

Instance: {instance} {lastUpdated && ( <> {" · "} updated {lastUpdated} )}

{llamaStatus === "running" ? "Running" : llamaStatus === "stopped" ? "Stopped" : "Not created"}
); } // --------------------------------------------------------------------------- // 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: (key: K, value: DashboardConfig[K]) => void; onSavePreset: () => void; onLoadPreset: (id: string) => void; onDeletePreset: (id: string, name: string) => void; onReset: () => void; }) { return (
Launch Configuration Adjust llama.cpp parameters. Saved automatically on apply.
{presetDialogOpen && (
setPresetName(e.target.value)} placeholder="e.g. long-context-spec" />
)} {config.presets.length > 0 && (
{config.presets.map((p) => (
))}
)}
update("ctxSize", Number(e.target.value))} />
update("parallel", Number(e.target.value))} />
update("batchSize", Number(e.target.value))} />
update("nGpuLayers", Number(e.target.value))} />
update("threads", Number(e.target.value))} />
Speculative decoding

Draft model + spec algorithm. Off by default.

update("specDraftNMax", Number(e.target.value))} disabled={config.specType === "none"} />
{/* Multimodal (mmproj) — vision projector for VL models */}
Multimodal projector (mmproj)

Vision projector for VL models (Qwen3-VL, Llama 3.2 Vision, etc.). Select the mmproj .gguf file that matches your base model. Leave empty for text-only models.

{config.mmprojPath && (
--mmproj /models/{config.mmprojPath}
)}
update("ubatchSize", Number(e.target.value))} />
{/* KV cache */}
KV cache

Quantize KV cache to save VRAM. q8_0 ≈ 50% memory, q4_0 ≈ 25% (slight quality drop).

update("defragThold", Number(e.target.value))} />
{/* Performance flags */}
Performance flags
update("flashAttn", v)} /> update("contBatching", v)} /> update("noMmap", v)} /> update("mlock", v)} /> update("embeddings", v)} /> update("metrics", v)} /> update("perf", v)} />
{/* RoPE / YaRN */}
RoPE / YaRN context extension

For extending context beyond the model's training length. Leave at defaults unless you know what you're doing.

update("ropeScale", Number(e.target.value))} />
update("ropeFreqScale", Number(e.target.value))} />
update("yarnExtFactor", Number(e.target.value))} />
update("yarnAttnFactor", Number(e.target.value))} />
update("yarnBetaFast", Number(e.target.value))} />
update("yarnBetaSlow", Number(e.target.value))} />
{/* Sampling defaults */}
Default sampling

Applied as defaults to /completion & /v1/chat/completions requests (can be overridden per-request).

update("temperature", Number(e.target.value))} />
update("topK", Number(e.target.value))} />
update("topP", Number(e.target.value))} />
update("minP", Number(e.target.value))} />
update("repeatPenalty", Number(e.target.value))} />
update("nPredict", Number(e.target.value))} />

-1 = infinity (model decides). Sets --n-predict on the server.

{/* Reasoning / Jinja — for thinking models (Qwen3, DeepSeek-R1, etc.) */}

For Qwen3, DeepSeek-R1, gpt-oss. "auto" puts <think>...</think> blocks into a separate reasoning_content field shown in chat.

update("jinja", v)} />