Files
GPU-Node/dashboard/src/app/page.tsx
Z User a2e9bac081 fix: TTS logs + voices list — stream VALID_ROLES + file-based voice scan + v0.9.2
## 3 fixes

### 1. TTS logs not working in dashboard
The stream route (/api/services/[role]/stream) had its own VALID_ROLES
list that was missing 'tts'. Added 'tts' to the list.

### 2. Dashboard doesn't show voices
/api/tts/voices only queried the TTS API (http://tts:8000/v1/audio/voices).
If TTS was not running or the API didn't return custom voices, the list
was empty.

Rewrote /api/tts/voices to use 3 sources:
1. TTS API (if running)
2. voice_to_speaker.yaml (parse voice names from config file)
3. Scan gpu/tts/voices/ directory for .onnx and .wav files
   - .onnx files: ru_RU-irina-medium.onnx → 'irina'
   - .wav files: myvoice.wav → 'myvoice'
4. Always include defaults (alloy, echo, fable, onyx, nova, shimmer)

### 3. Voices not loading on page open
refreshVoices() was only called when ttsRunning was true. Changed to
always fetch on mount — the API now works even when TTS is stopped
because it reads from config files and directory.

## Version → 0.9.2

## After merge

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

TTS tab should now show irina, denis, dmitri, ruslan in the voice
dropdown (even if TTS is stopped). TTS logs should work in Logs tab.
2026-10-29 23:39:55 +00:00

4993 lines
172 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,
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<DashboardConfig, "presets">;
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<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" | "tts"
>("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);
// Separate preview state for the Comfy tab's URL field (same logic as urlPreview,
// just tracks a different input)
const [comfyUrlPreview, setComfyUrlPreview] = React.useState<UrlPreview | null>(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<ChatMessage[]>([]);
const [chatInput, setChatInput] = React.useState("");
const [chatStreaming, setChatStreaming] = React.useState(false);
const [chatAutoScroll, setChatAutoScroll] = React.useState(true);
const chatAbortRef = React.useRef<AbortController | null>(null);
const chatMessagesEndRef = React.useRef<HTMLDivElement | 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, 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<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]);
// Same debounced preview, but for the Comfy tab's URL field
const comfyPreviewDebounceRef = React.useRef<ReturnType<typeof setTimeout> | 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<void> =>
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<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="tts" className="gap-1.5">
<Volume2 className="h-3.5 w-3.5" />
<span className="hidden sm:inline">TTS</span>
</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
messages={chatMessages}
input={chatInput}
setInput={setChatInput}
streaming={chatStreaming}
autoScroll={chatAutoScroll}
setAutoScroll={setChatAutoScroll}
onSend={handleChatSend}
onStop={handleChatStop}
onClear={handleChatClear}
messagesEndRef={chatMessagesEndRef}
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)}
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}
/>
</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}
civitaiToken={settings.civitaiToken}
onSaveCivitaiToken={handleSaveCivitaiToken}
urlPreview={comfyUrlPreview}
/>
</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="tts">
<TTSTab
ttsRunning={!!containers.find((c) => c.role === "tts")?.running}
busy={busy}
onServiceAction={handleServiceAction}
/>
</TabsContent>
<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 className="flex items-center gap-2">
<span className="font-mono font-medium text-foreground">
v{DASHBOARD_VERSION}
</span>
<span>·</span>
<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.filter((m) => m.kind === "base").map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<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
.filter((m) => m.kind === "mtp" || m.kind === "draft")
.map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<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>
{/* Multimodal (mmproj) — vision projector for VL models */}
<div className="rounded-md border p-4 space-y-3 bg-muted/20">
<div>
<span className="text-sm font-medium flex items-center gap-2">
<Zap className="h-4 w-4 text-warning" />
Multimodal projector (mmproj)
</span>
<p className="text-xs text-muted-foreground mt-0.5">
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.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="mmproj-select">mmproj file</Label>
<Select
value={config.mmprojPath || "__none__"}
onValueChange={(v) => update("mmprojPath", v === "__none__" ? "" : v)}
>
<SelectTrigger id="mmproj-select">
<SelectValue placeholder="None (text-only)" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">— None (text-only) —</SelectItem>
{models
.filter((m) => m.kind === "mmproj")
.map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<span className="font-mono">{m.name}</span>
<span className="ml-2 text-muted-foreground text-xs">{m.sizeHuman}</span>
</SelectItem>
))}
{/* Also show base models as fallback (some mmproj files
don't have 'mmproj' in the name) */}
{models.filter((m) => m.kind === "mmproj").length === 0 && (
models.map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<span className="font-mono">{m.name}</span>
</SelectItem>
))
)}
</SelectContent>
</Select>
{config.mmprojPath && (
<div className="text-[10px] text-muted-foreground font-mono">
--mmproj /models/{config.mmprojPath}
</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)}
/>
<ToggleRow
label="Perf timings"
hint="Per-slot TPS/TTFT in /slots (needed for Perf tab)"
checked={config.perf}
onChange={(v) => update("perf", 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 className="space-y-1.5">
<Label htmlFor="n-predict">Max tokens / response</Label>
<Input
id="n-predict"
type="number"
min={-1}
value={config.nPredict}
onChange={(e) => update("nPredict", Number(e.target.value))}
/>
<p className="text-[10px] text-muted-foreground">
-1 = infinity (model decides). Sets --n-predict on the server.
</p>
</div>
</div>
{/* Reasoning / Jinja — for thinking models (Qwen3, DeepSeek-R1, etc.) */}
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="reasoning-format">Reasoning format</Label>
<Select
value={config.reasoningFormat}
onValueChange={(v) =>
update("reasoningFormat", v as DashboardConfig["reasoningFormat"])
}
>
<SelectTrigger id="reasoning-format">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">
auto (recommended) — split thinking into reasoning_content
</SelectItem>
<SelectItem value="deepthink">
deepthink — force thinking even if model wouldn&apos;t
</SelectItem>
<SelectItem value="none">
none — passthrough raw (thinking tags appear in content)
</SelectItem>
</SelectContent>
</Select>
<p className="text-[10px] text-muted-foreground">
For Qwen3, DeepSeek-R1, gpt-oss. &quot;auto&quot; puts
&lt;think&gt;...&lt;/think&gt; blocks into a separate
reasoning_content field shown in chat.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="jinja-toggle">Jinja chat templates</Label>
<ToggleRow
label="Enable --jinja"
hint="Required for reasoning format + tool calling. Recommended ON."
checked={config.jinja}
onChange={(v) => update("jinja", v)}
/>
</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,
onUseMmproj,
onUseDraft,
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;
onUseMmproj: (m: string) => void;
onUseDraft: (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-20">Kind</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-44 text-right">Actions</th>
</tr>
</thead>
<tbody>
{models.map((m) => {
const isActiveBase = config.model === m.relativePath;
const isActiveMmproj = config.mmprojPath === m.relativePath;
const isActiveDraft = config.draftModel === m.name;
const isActive = isActiveBase || isActiveMmproj || isActiveDraft;
const kindBadge = {
base: <Badge variant="outline" className="text-[10px]">base</Badge>,
mmproj: <Badge variant="default" className="text-[10px]">mmproj</Badge>,
mtp: <Badge variant="secondary" className="text-[10px]">mtp</Badge>,
draft: <Badge variant="secondary" className="text-[10px]">draft</Badge>,
}[m.kind];
return (
<tr
key={m.relativePath}
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" />
{m.subdir && (
<span className="font-mono text-[10px] text-muted-foreground">
{m.subdir}/
</span>
)}
<span className="font-mono text-xs truncate">{m.name}</span>
{isActive && (
<Badge variant="success" className="text-[10px]">
{isActiveBase ? "active" : isActiveMmproj ? "mmproj" : "draft"}
</Badge>
)}
</div>
</td>
<td className="py-2 px-2">{kindBadge}</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 flex-wrap">
{m.kind === "base" && (
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={isActiveBase || busy !== null}
onClick={() => onSelectModel(m.relativePath)}
>
Use
<ChevronRight className="h-3 w-3" />
</Button>
)}
{m.kind === "mmproj" && (
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={isActiveMmproj || busy !== null}
onClick={() => onUseMmproj(m.relativePath)}
>
{isActiveMmproj ? "✓ mmproj" : "Set mmproj"}
</Button>
)}
{(m.kind === "mtp" || m.kind === "draft") && (
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={isActiveDraft || busy !== null}
onClick={() => onUseDraft(m.name)}
>
{isActiveDraft ? "✓ draft" : "Set draft"}
</Button>
)}
<Button
size="sm"
variant="ghost"
className="h-7 hover:text-destructive"
disabled={busy !== null}
onClick={() => onDelete(m.relativePath)}
>
<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,
civitaiToken,
onSaveCivitaiToken,
urlPreview,
}: {
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;
civitaiToken: string;
onSaveCivitaiToken: (token: string) => void;
urlPreview: UrlPreview | null;
}) {
const [showCivitaiSettings, setShowCivitaiSettings] = React.useState(false);
const [civitaiTokenDraft, setCivitaiTokenDraft] = React.useState(civitaiToken);
React.useEffect(() => {
setCivitaiTokenDraft(civitaiToken);
}, [civitaiToken]);
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 className="flex flex-row items-start justify-between gap-2">
<div>
<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>.
{" "}CivitAI URLs auto-converted (model page → API download),
token appended.
</CardDescription>
</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>
</CardHeader>
<CardContent className="space-y-3">
{showCivitaiSettings && (
<div className="rounded-md border bg-card p-3 space-y-2">
<Label htmlFor="comfy-civitai-token">CivitAI API token</Label>
<Input
id="comfy-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">
Shared with the llama-models downloader. Stored in{" "}
<code className="font-mono">gpu/dashboard/settings.json</code>.
</p>
</div>
)}
<div className="grid gap-2 sm:grid-cols-[1fr_180px_auto]">
<Input
placeholder="https://civitai.com/models/12345 or HF/GitHub URL"
value={addUrl}
onChange={(e) => setAddUrl(e.target.value)}
className="font-mono text-xs"
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
if (addUrl.trim() && busy === null) onAdd();
}
}}
/>
<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 || !addUrl.trim()}>
<Plus className="h-3.5 w-3.5" />
Queue
</Button>
</div>
{/* URL preview — shows what we'll actually send to the worker */}
{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>
)}
</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)
{" · "}
{formatBytes(models.reduce((s, m) => s + (m.sizeBytes || 0), 0))} total
</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" | "tts";
setTarget: (t: "llama" | "comfyui" | "dashboard" | "ssh" | "tts") => 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>
<SelectItem value="tts">tts</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 — reasoning content (thinking blocks) when
// --reasoning-format auto is enabled on the server. Streamed separately
// via delta.reasoning_content.
reasoning?: 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({
messages,
input,
setInput,
streaming,
autoScroll,
setAutoScroll,
onSend,
onStop,
onClear,
messagesEndRef,
llamaRunning,
}: {
messages: ChatMessage[];
input: string;
setInput: (v: string) => void;
streaming: boolean;
autoScroll: boolean;
setAutoScroll: (v: boolean) => void;
onSend: () => void;
onStop: () => void;
onClear: () => void;
messagesEndRef: React.RefObject<HTMLDivElement | null>;
llamaRunning: boolean;
}) {
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={onClear} disabled={messages.length === 0}>
<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... (Enter to send, Shift+Enter for newline)"
rows={2}
onKeyDown={(e) => {
// Enter = send. Shift+Enter = newline (default behavior).
if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
if (!streaming && llamaRunning && input.trim()) {
onSend();
}
}
}}
className="flex-1 resize-none"
disabled={!llamaRunning || streaming}
/>
{streaming ? (
<Button onClick={onStop} variant="destructive">
<Square className="h-3.5 w-3.5" />
Stop
</Button>
) : (
<Button
onClick={onSend}
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";
const [reasoningExpanded, setReasoningExpanded] = React.useState(false);
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"
)}
>
{/* Reasoning block (thinking) — shown above content, collapsible */}
{isAssistant && message.reasoning && message.reasoning.length > 0 && (
<div className="mb-2 rounded border border-border/40 bg-background/50">
<button
className="w-full px-2 py-1 flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground"
onClick={() => setReasoningExpanded((v) => !v)}
>
<span className="font-medium">
{reasoningExpanded ? "▼" : "▶"} Reasoning
</span>
<span className="opacity-60">
({message.reasoning.length} chars)
</span>
</button>
{reasoningExpanded && (
<pre className="px-2 pb-2 text-[10px] font-mono whitespace-pre-wrap break-all text-muted-foreground max-h-60 overflow-y-auto scrollbar-thin">
{message.reasoning}
</pre>
)}
</div>
)}
<div className="whitespace-pre-wrap break-words">
{message.content || (isAssistant && (!message.reasoning || message.reasoning.length === 0) ? "…" : "")}
</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">
{/* TPS — generation speed */}
{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>
)}
{/* TTFT — Time To First Token. This is the time spent processing the
prompt before generation started. */}
{t.prompt_ms != null && (
<div>
<span className="text-foreground">TTFT:</span>{" "}
{(t.prompt_ms / 1000).toFixed(2)}s
{t.prompt_n != null && (
<span className="ml-2">({t.prompt_n} prompt tok)</span>
)}
</div>
)}
{/* Prefill speed — prompt processing throughput */}
{t.prompt_per_second != null && (
<div>
<span className="text-foreground">Prefill:</span>{" "}
{t.prompt_per_second.toFixed(1)} tok/s
</div>
)}
{/* Cache hit rate — how much of the prompt was reused from KV cache */}
{t.cache_hit_rate != null && (
<div>
<span className="text-foreground">Cache hit:</span>{" "}
{(t.cache_hit_rate * 100).toFixed(1)}%
</div>
)}
{/* Speculative decoding stats */}
{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;
// Newer llama.cpp field names
n_prompt_tokens?: number;
n_prompt_tokens_processed?: number;
n_prompt_tokens_cache?: number;
speculative?: boolean;
// Legacy field names (older versions)
n_past?: number;
n_eval?: number;
prompt?: number[];
// Next token info (newer versions)
next_token?: Array<{
has_next_token?: boolean;
has_new_line?: boolean;
n_remain?: number;
n_decoded?: number;
}>;
// Per-slot params (newer versions include these)
params?: Record<string, unknown>;
// Timings — only present after generation in some versions
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;
};
spec?: {
accepted: number;
drafted: number;
rate: number;
};
}
function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
const [slots, setSlots] = React.useState<SlotInfo[]>([]);
const [props, setProps] = React.useState<Record<string, unknown> | null>(null);
const [metricsRaw, setMetricsRaw] = React.useState<string>("");
const [active, setActive] = React.useState(false);
const [view, setView] = React.useState<"overview" | "slots" | "metrics">("overview");
const [errors, setErrors] = React.useState<string>("");
React.useEffect(() => {
if (!active || !llamaRunning) return;
let cancelled = false;
async function poll() {
if (cancelled) return;
setErrors("");
try {
if (view === "overview") {
// Fetch props + slots in parallel for the overview
const [propsRes, slotsRes] = await Promise.all([
fetch("/api/props", { cache: "no-store" }).catch(() => null),
fetch("/api/slots", { cache: "no-store" }).catch(() => null),
]);
if (propsRes && propsRes.ok) {
const pd = await propsRes.json();
if (!cancelled && pd.ok) setProps(pd.props);
}
if (slotsRes && slotsRes.ok) {
const sd = await slotsRes.json();
if (!cancelled) setSlots(sd.slots || []);
}
} else 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);
} else {
const text = await res.text().catch(() => "");
if (!cancelled) setMetricsRaw(`[${res.status}] ${text.slice(0, 300)}`);
}
}
} catch (err) {
if (!cancelled) setErrors((err as Error).message);
}
}
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 "overview" | "slots" | "metrics")}>
<SelectTrigger className="w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="overview">Overview</SelectItem>
<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>
) : !active ? (
<div className="text-center py-12 text-muted-foreground">
<Play className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Click Live to start polling</p>
<p className="text-xs mt-1">Polls every 1.5s while active</p>
</div>
) : errors ? (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm">
<span className="font-mono text-xs text-destructive">{errors}</span>
</div>
) : view === "slots" ? (
<SlotsView slots={slots} />
) : view === "metrics" ? (
<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>
) : (
<OverviewView props={props} slots={slots} />
)}
</CardContent>
</Card>
);
}
function OverviewView({
props,
slots,
}: {
props: Record<string, unknown> | null;
slots: SlotInfo[];
}) {
if (!props) {
return (
<p className="text-sm text-muted-foreground text-center py-8">
Loading…
</p>
);
}
// Extract params from nested structure
// Newer llama.cpp: default_generation_settings.params.temperature
// Older: default_generation_settings.temperature
const dgs = (props.default_generation_settings ||
props.generation_settings) as Record<string, unknown> | undefined;
const gen = (dgs?.params || dgs) as
| {
n_predict?: number;
max_tokens?: number;
temperature?: number;
top_k?: number;
top_p?: number;
min_p?: number;
repeat_penalty?: number;
}
| undefined;
// Cumulative timings across all slots
const totalPredictedN = slots.reduce(
(s, x) =>
s +
(x.timings?.predicted_n || x.next_token?.[0]?.n_decoded || 0),
0
);
const totalPromptN = slots.reduce(
(s, x) =>
s +
(x.timings?.prompt_n ||
x.n_prompt_tokens_processed ||
x.n_past ||
0),
0
);
// Average TPS — from timings (if available)
const activeSlots = slots.filter((s) => s.timings?.predicted_per_second);
const avgTps =
activeSlots.length > 0
? activeSlots.reduce(
(s, x) => s + (x.timings?.predicted_per_second || 0),
0
) / activeSlots.length
: null;
// Multimodal — newer: modalities.vision, older: has_multimodal
const modalities = props.modalities as
| { vision?: boolean; audio?: boolean; video?: boolean }
| undefined;
const hasMultimodal = Boolean(
modalities?.vision ||
modalities?.audio ||
props.has_multimodal ||
props.is_multimodal
);
const totalSlots =
(props.total_slots as number) ||
(props.n_slots as number) ||
slots.length;
// Ctx usage — try newer field names first
const ctxUsed = slots.reduce(
(s, x) =>
s +
(x.n_prompt_tokens_processed ?? x.n_past ?? 0),
0
);
const ctxTotal = slots.reduce(
(s, x) => s + (x.n_ctx ?? 0),
0
);
// Total ctx from props: newer: default_generation_settings.n_ctx
const totalCtx =
(dgs?.n_ctx as number) ||
(props.n_context as number) ||
(props.n_ctx_total as number) ||
ctxTotal ||
null;
// Speculative decoding
const specSlots = slots.filter((s) => s.speculative);
const hasSpec = specSlots.length > 0;
// Build info
const buildInfo = props.build_info as string | undefined;
const [showRaw, setShowRaw] = React.useState(false);
return (
<div className="space-y-4">
{/* Key metrics */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<MetricCell
label="Avg TPS"
value={avgTps != null ? `${avgTps.toFixed(1)}` : "—"}
hint="tok/s generated"
/>
<MetricCell
label="Total slots"
value={`${totalSlots}`}
hint={`${activeSlots.length} with timings`}
/>
<MetricCell
label="Ctx usage"
value={
ctxTotal > 0
? `${ctxUsed} / ${ctxTotal}`
: ctxUsed > 0
? `${ctxUsed}`
: "—"
}
hint="prompt tokens processed / ctx"
/>
<MetricCell
label="Multimodal"
value={hasMultimodal ? "yes" : "no"}
hint={hasMultimodal ? "vision/audio loaded" : "text-only"}
/>
</div>
{/* Cumulative stats */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
<MetricCell
label="Generated"
value={totalPredictedN > 0 ? `${totalPredictedN}` : "—"}
hint="tokens decoded"
/>
<MetricCell
label="Prompt"
value={totalPromptN > 0 ? `${totalPromptN}` : "—"}
hint="tokens processed"
/>
<MetricCell
label="Model"
value={
typeof props.model_path === "string"
? (props.model_path as string).split("/").pop() || "?"
: "?"
}
hint={typeof props.model_path === "string" ? props.model_path : ""}
/>
<MetricCell
label="Speculative"
value={hasSpec ? "yes" : "no"}
hint={hasSpec ? `${specSlots.length} slots` : "disabled"}
/>
</div>
{/* Active slots breakdown */}
{slots.length > 0 && (
<div>
<div className="text-xs text-muted-foreground mb-2 font-medium uppercase tracking-wide">
Slots ({totalCtx != null ? `${totalCtx} ctx` : ""}{buildInfo ? ` · ${buildInfo}` : ""})
</div>
<SlotsView slots={slots} />
</div>
)}
{/* Generation defaults */}
{gen && (
<div>
<div className="text-xs text-muted-foreground mb-2 font-medium uppercase tracking-wide">
Default sampling
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2 text-xs font-mono">
<span>
<span className="text-muted-foreground">temp:</span> {gen.temperature?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">top_k:</span> {gen.top_k ?? "?"}
</span>
<span>
<span className="text-muted-foreground">top_p:</span> {gen.top_p?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">min_p:</span> {gen.min_p?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">rep:</span> {gen.repeat_penalty?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">n_pred:</span> {gen.n_predict ?? gen.max_tokens ?? "?"}
</span>
</div>
</div>
)}
{/* Raw JSON dump — for debugging when fields are missing */}
<div>
<button
className="text-xs text-muted-foreground hover:text-foreground underline-offset-2 hover:underline"
onClick={() => setShowRaw((v) => !v)}
>
{showRaw ? "▼" : "▶"} Raw /props + /slots JSON
</button>
{showRaw && (
<div className="mt-2 space-y-2">
<div>
<div className="text-[10px] text-muted-foreground mb-1">/props:</div>
<pre className="text-[10px] font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-2 max-h-40 overflow-y-auto scrollbar-thin">
{JSON.stringify(props, null, 2)}
</pre>
</div>
<div>
<div className="text-[10px] text-muted-foreground mb-1">/slots:</div>
<pre className="text-[10px] font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-2 max-h-40 overflow-y-auto scrollbar-thin">
{JSON.stringify(slots, null, 2)}
</pre>
</div>
</div>
)}
</div>
</div>
);
}
function SlotsView({ slots }: { slots: SlotInfo[] }) {
if (slots.length === 0) {
return (
<p className="text-sm text-muted-foreground text-center py-8">
No slots. (Llama might be loading the model still.)
</p>
);
}
return (
<div className="space-y-3">
{slots.map((s) => {
// Use n_prompt_tokens_processed (newer) or n_past (legacy)
const promptTokens =
s.n_prompt_tokens_processed ?? s.n_past ?? null;
const totalPromptTokens =
s.n_prompt_tokens ?? null;
const cacheTokens = s.n_prompt_tokens_cache ?? null;
const decodedTokens = s.next_token?.[0]?.n_decoded ?? null;
const remainTokens = s.next_token?.[0]?.n_remain ?? null;
const hasTimings = !!s.timings;
return (
<div key={s.id} className="rounded-md border p-3 bg-card space-y-3">
<div className="flex items-center justify-between gap-2 flex-wrap">
<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>
{s.speculative && (
<Badge variant="outline" className="text-[10px]">
spec
</Badge>
)}
</div>
<div className="text-xs text-muted-foreground font-mono">
ctx: {promptTokens ?? "?"}/{s.n_ctx ?? "?"}
{totalPromptTokens != null && ` (${totalPromptTokens} prompt)`}
{cacheTokens != null && ` · ${cacheTokens} cached`}
</div>
</div>
{hasTimings ? (
<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>
) : (
<div className="space-y-1">
<p className="text-xs text-muted-foreground italic">
No per-token timings (idle or no generation yet).
</p>
{decodedTokens != null && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
<MetricCell
label="Decoded"
value={`${decodedTokens}`}
hint="tokens generated"
/>
<MetricCell
label="Remaining"
value={remainTokens != null ? `${remainTokens}` : "—"}
hint="tokens left"
/>
<MetricCell
label="Cache"
value={cacheTokens != null ? `${cacheTokens}` : "—"}
hint="cached prompt tokens"
/>
</div>
)}
</div>
)}
{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>
);
}
// ---------------------------------------------------------------------------
// TTS Tab — text-to-speech generation
// ---------------------------------------------------------------------------
function TTSTab({
ttsRunning,
busy,
onServiceAction,
}: {
ttsRunning: boolean;
busy: string | null;
onServiceAction: (role: string, action: "start" | "stop" | "restart" | "remove") => void;
}) {
const [voices, setVoices] = React.useState<string[]>([
"alloy", "echo", "fable", "onyx", "nova", "shimmer"
]);
const [selectedVoice, setSelectedVoice] = React.useState("alloy");
const [model, setModel] = React.useState<"tts-1" | "tts-1-hd">("tts-1-hd");
const [input, setInput] = React.useState("");
const [speed, setSpeed] = React.useState(1.0);
const [format, setFormat] = React.useState<"mp3" | "wav" | "opus" | "flac">("mp3");
const [generating, setGenerating] = React.useState(false);
const [audioUrl, setAudioUrl] = React.useState<string | null>(null);
const [error, setError] = React.useState<string>("");
const [uploadProgress, setUploadProgress] = React.useState<string | null>(null);
const [voiceLanguage, setVoiceLanguage] = React.useState<string>("ru");
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const refreshVoices = React.useCallback(async () => {
try {
const res = await fetch("/api/tts/voices", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
if (data.ok && data.voices) {
const voiceIds = data.voices.map((v: { voice_id?: string; name?: string }) => v.voice_id || v.name).filter(Boolean);
if (voiceIds.length > 0) {
setVoices(voiceIds);
}
}
} catch {
/* keep defaults */
}
}, []);
// Refresh voices on mount (even if TTS is not running — we read config + files)
React.useEffect(() => {
refreshVoices();
}, [refreshVoices]);
async function handleGenerate() {
if (!input.trim() || !ttsRunning || generating) return;
setGenerating(true);
setError("");
setAudioUrl(null);
try {
const res = await fetch("/api/tts/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model,
voice: selectedVoice,
input: input.trim(),
response_format: format,
speed,
}),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
setError(errData.error || `HTTP ${res.status}`);
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
setAudioUrl(url);
} catch (err) {
setError((err as Error).message);
} finally {
setGenerating(false);
}
}
async function handleUploadVoice(file: File, language: string = "ru") {
if (!file.name.match(/\.(wav|mp3|flac)$/i)) {
setError("Voice sample must be WAV/MP3/FLAC");
return;
}
setUploadProgress(file.name);
setError("");
try {
const formData = new FormData();
formData.append("file", file);
const name = file.name.replace(/\.[^.]+$/, "").replace(/[^\w\-]/g, "_");
formData.append("name", name);
formData.append("language", language);
const res = await fetch("/api/tts/upload-voice", {
method: "POST",
body: formData,
});
const data = await res.json();
if (data.ok) {
setError(`Voice "${data.voice}" uploaded (${language}). Restart TTS to apply.`);
refreshVoices();
} else {
setError(data.error || "Upload failed");
}
} catch (err) {
setError((err as Error).message);
} finally {
setUploadProgress(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">
<Volume2 className="h-4 w-4" />
Text-to-Speech
</CardTitle>
<CardDescription>
OpenAI-compatible TTS · openedai-speech (XTTSv2)
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Badge variant={ttsRunning ? "success" : "secondary"}>
{ttsRunning ? "running" : "stopped"}
</Badge>
{!ttsRunning ? (
<Button
size="sm"
variant="success"
disabled={busy !== null}
onClick={() => onServiceAction("tts", "start")}
>
<Play className="h-3.5 w-3.5" />
Start TTS
</Button>
) : (
<>
<Button
size="sm"
variant="outline"
disabled={busy !== null}
onClick={() => onServiceAction("tts", "restart")}
>
<RotateCw className="h-3.5 w-3.5" />
Restart
</Button>
<Button
size="sm"
variant="ghost"
className="hover:text-destructive"
disabled={busy !== null}
onClick={() => onServiceAction("tts", "stop")}
>
<Square className="h-3.5 w-3.5" />
Stop
</Button>
</>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
{!ttsRunning && (
<div className="rounded-md border border-warning/30 bg-warning/5 p-3 text-sm">
<span className="text-warning font-medium">TTS is not running.</span>{" "}
<span className="text-muted-foreground">
Click &quot;Start TTS&quot; to launch the openedai-speech container.
Port 8100 is exposed via Tailscale serve.
</span>
</div>
)}
{error && (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm">
<span className="font-mono text-xs text-destructive">{error}</span>
</div>
)}
{/* Settings */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="space-y-1.5">
<Label>Model</Label>
<Select value={model} onValueChange={(v) => setModel(v as "tts-1" | "tts-1-hd")}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="tts-1">tts-1 (Piper, faster)</SelectItem>
<SelectItem value="tts-1-hd">tts-1-hd (XTTSv2, better)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Voice</Label>
<Select value={selectedVoice} onValueChange={setSelectedVoice}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{voices.map((v) => (
<SelectItem key={v} value={v}>
{v}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Format</Label>
<Select value={format} onValueChange={(v) => setFormat(v as typeof format)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="mp3">MP3</SelectItem>
<SelectItem value="wav">WAV</SelectItem>
<SelectItem value="opus">Opus</SelectItem>
<SelectItem value="flac">FLAC</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Speed ({speed.toFixed(2)}x)</Label>
<Input
type="range"
min={0.25}
max={4.0}
step={0.05}
value={speed}
onChange={(e) => setSpeed(Number(e.target.value))}
className="w-full"
/>
</div>
</div>
{/* Text input */}
<div className="space-y-2">
<Label>Text to synthesize</Label>
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Введите текст для озвучивания..."
rows={4}
className="resize-none"
disabled={!ttsRunning || generating}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
handleGenerate();
}
}}
/>
<div className="flex items-center justify-between">
<span className="text-xs text-muted-foreground">
{input.length} characters
{input.length > 4096 && " (recommended max: 4096)"}
</span>
<Button
onClick={handleGenerate}
disabled={!ttsRunning || !input.trim() || generating}
>
{generating ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<Volume2 className="h-3.5 w-3.5" />
)}
Generate
</Button>
</div>
</div>
{/* Audio output */}
{audioUrl && (
<div className="rounded-md border p-3 space-y-2">
<Label>Result</Label>
<audio controls className="w-full">
<source src={audioUrl} type={`audio/${format}`} />
</audio>
<a
href={audioUrl}
download={`tts-${selectedVoice}-${Date.now()}.${format}`}
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:underline"
>
<CloudDownload className="h-3 w-3" />
Download
</a>
</div>
)}
{/* Russian Piper voices info */}
<div className="rounded-md border p-3 space-y-2 bg-muted/20">
<Label>Russian voices</Label>
<p className="text-[10px] text-muted-foreground">
For natural Russian speech without accent, use <strong>tts-1</strong> model
with Piper Russian voices: <code className="font-mono">irina</code> (female),
<code className="font-mono"> denis</code> (male),
<code className="font-mono"> dmitri</code> (male),
<code className="font-mono"> ruslan</code> (male).
These are native Russian-trained voices — no accent, correct stress.
</p>
<p className="text-[10px] text-muted-foreground">
<strong className="text-foreground">Download voices:</strong>
<code className="font-mono ml-1">sh gpu/tts/download-ru-voices.sh</code>
then restart TTS. The default voice_to_speaker.yaml (auto-created on first
start) already includes <code className="font-mono">irina</code> and
<code className="font-mono"> denis</code>.
</p>
<p className="text-[10px] text-muted-foreground">
For <strong>tts-1-hd</strong> (XTTSv2) with custom cloned voices — upload
a WAV sample below. Quality depends on the sample; XTTSv2 is less natural
for Russian than Piper.
</p>
</div>
{/* Voice upload (for XTTS custom voices) */}
<div className="rounded-md border p-3 space-y-2 bg-muted/20">
<Label>Custom voices (XTTSv2)</Label>
<div className="flex items-center gap-2 flex-wrap">
<Button
size="sm"
variant="outline"
onClick={() => fileInputRef.current?.click()}
disabled={!ttsRunning}
>
<Upload className="h-3.5 w-3.5" />
Upload voice sample
</Button>
<input
ref={fileInputRef}
type="file"
accept=".wav,.mp3,.flac"
className="hidden"
onChange={(e) => {
const f = e.target.files?.[0];
if (f) handleUploadVoice(f, voiceLanguage);
}}
/>
<Select value={voiceLanguage} onValueChange={setVoiceLanguage}>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ru">Russian (ru)</SelectItem>
<SelectItem value="en">English (en)</SelectItem>
<SelectItem value="es">Spanish (es)</SelectItem>
<SelectItem value="fr">French (fr)</SelectItem>
<SelectItem value="de">German (de)</SelectItem>
<SelectItem value="it">Italian (it)</SelectItem>
<SelectItem value="pt">Portuguese (pt)</SelectItem>
<SelectItem value="pl">Polish (pl)</SelectItem>
<SelectItem value="tr">Turkish (tr)</SelectItem>
<SelectItem value="nl">Dutch (nl)</SelectItem>
<SelectItem value="cs">Czech (cs)</SelectItem>
<SelectItem value="ar">Arabic (ar)</SelectItem>
<SelectItem value="zh-cn">Chinese (zh-cn)</SelectItem>
<SelectItem value="ja">Japanese (ja)</SelectItem>
<SelectItem value="ko">Korean (ko)</SelectItem>
<SelectItem value="hi">Hindi (hi)</SelectItem>
</SelectContent>
</Select>
</div>
{uploadProgress && (
<p className="text-xs text-muted-foreground">
Uploading: {uploadProgress}...
</p>
)}
<p className="text-[10px] text-muted-foreground">
<strong className="text-foreground">For natural Russian:</strong>{" "}
built-in voices (alloy, nova, shimmer) are English-trained and will
speak Russian with an accent. Upload a clean WAV sample of a Russian
speaker (10-20s, mono 22050 Hz, no noise), select the language, and
restart TTS. The new voice will appear in the dropdown above.
<br />
<span className="mt-1 block">
Good sources: audiobook samples (lib.ru), news clips, or record
yourself. Avoid music, breathing, or partial words.
</span>
</p>
</div>
</CardContent>
</Card>
);
}
// ---------------------------------------------------------------------------
// 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.perf) parts.push("--perf");
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.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
if (cfg.jinja) parts.push("--jinja");
if (cfg.mmprojPath) parts.push(`--mmproj /models/${cfg.mmprojPath}`);
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}