feat: add llama dashboard for managing launch config via web UI

Adds a small Next.js dashboard as a new Docker service ()
that replaces the need to manually edit  and call  over SSH
every time you want to tweak llama launch parameters.

Features:
- Live status panel for all GPU-node containers (auto-refresh)
- Models list with file sizes, click-to-select active model
- Structured launch config form:
  * Model, ctx-size, parallel, batch-size, n-gpu-layers, threads
  * Context overflow (none / shift / evict)
  * Speculative decoding (spec-type, draft model, spec-draft-n-max)
  * Free-form extra args textarea for anything else
- Named presets (save / load / delete)
- Start / Restart / Stop / Remove llama actions
- Live streaming logs viewer (docker logs -f)
- GPU status (nvidia-smi via docker exec on llama)
- Auto-writes LLAMA_MODEL and LLAMA_EXTRA_ARGS back to .env so the
  existing workflow keeps working, and persists full structured config
  to gpu/dashboard/config.json for reload on next visit

Integration:
- New  service in compose.yaml (no profile, runs always)
- Mounts /var/run/docker.sock + HOST_PROJECT_PATH
- Tailscale serve exposes port 8090 -> dashboard:3000
- build.sh extended to build the dashboard image

Tech: Next.js 16 standalone, React 19, TypeScript 5, Tailwind 4,
shadcn-style components, Radix UI primitives.
This commit is contained in:
Claude
2026-10-23 22:22:26 +00:00
parent 23fb14a5fc
commit c4a91972b3
35 changed files with 10832 additions and 2 deletions

620
dashboard/src/lib/docker.ts Normal file
View File

@@ -0,0 +1,620 @@
import { exec, spawn, type ExecOptions } from "node:child_process";
import { promisify } from "node:util";
import { promises as fs } from "node:fs";
import path from "node:path";
const execAsync = promisify(exec);
// ---------------------------------------------------------------------------
// Environment / paths
// ---------------------------------------------------------------------------
/**
* Internal mount of the GPU-Node project (compose.yaml lives here).
*/
export const PROJECT_DIR = process.env.PROJECT_DIR || "/project";
/**
* Host-side absolute path of the GPU-Node project. Required so that when the
* dashboard spawns `docker compose`, the compose file's relative volume mounts
* resolve correctly on the host (where Docker daemon actually runs).
*/
export const HOST_PROJECT_PATH =
process.env.HOST_PROJECT_PATH || "/project";
/**
* Internal mount of the llama_models directory.
*/
export const LLAMA_MODELS_DIR =
process.env.LLAMA_MODELS_DIR || path.join(PROJECT_DIR, "gpu", "llama_models");
/**
* Node instance name (used for filtering containers by label).
*/
export const NODE_INSTANCE =
process.env.NODE_INSTANCE || process.env.TAILSCALE_HOSTNAME || "gpu-node";
/**
* Compose file path (relative to PROJECT_DIR).
*/
const COMPOSE_FILE = path.join(PROJECT_DIR, "compose.yaml");
/**
* Path to the persisted dashboard config (last-used + saved presets).
*/
export const DASHBOARD_CONFIG_PATH = path.join(
PROJECT_DIR,
"gpu",
"dashboard",
"config.json"
);
/**
* Path to the project's .env file (used to persist LLAMA_MODEL/LLAMA_EXTRA_ARGS
* so users can still inspect the .env if they prefer).
*/
export const ENV_FILE_PATH = path.join(PROJECT_DIR, ".env");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface ContainerInfo {
name: string;
status: string;
state: string;
running: boolean;
ports: string;
image: string;
role: string | null;
createdAt: string;
/** Formatted "Up X minutes" or "Exited N minutes ago" */
statusText: string;
}
export interface ModelFile {
name: string;
sizeBytes: number;
sizeHuman: string;
modifiedAt: string;
}
export interface DashboardConfig {
/** Currently-selected model file (e.g., "model.gguf") */
model: string;
/** ctx-size parameter */
ctxSize: number;
/** parallel slots */
parallel: number;
/** Number of GPU layers, -1 = all */
nGpuLayers: number;
/** Number of threads, -1 = default */
threads: number;
/** Optional draft model file */
draftModel: string;
/** Speculative decoding type */
specType: "none" | "draft-mtp" | "draft-llama";
/** Max draft tokens */
specDraftNMax: number;
/** Batch size */
batchSize: number;
/** UB / KV cache size etc */
contextOverflow: "none" | "shift" | "evict";
/** Free-form extra args (advanced) */
extraArgs: string;
/** Saved presets */
presets: Preset[];
}
export interface Preset {
id: string;
name: string;
config: Omit<DashboardConfig, "presets">;
createdAt: string;
}
export const DEFAULT_CONFIG: DashboardConfig = {
model: "model.gguf",
ctxSize: 64000,
parallel: 1,
nGpuLayers: -1,
threads: -1,
draftModel: "",
specType: "none",
specDraftNMax: 4,
batchSize: 512,
contextOverflow: "none",
extraArgs: "",
presets: [],
};
// ---------------------------------------------------------------------------
// Config persistence
// ---------------------------------------------------------------------------
export async function loadConfig(): Promise<DashboardConfig> {
try {
const raw = await fs.readFile(DASHBOARD_CONFIG_PATH, "utf-8");
const parsed = JSON.parse(raw);
return { ...DEFAULT_CONFIG, ...parsed, presets: parsed.presets ?? [] };
} catch {
// Try to seed from .env if present
const envConfig = await readConfigFromEnv();
if (envConfig) return envConfig;
return DEFAULT_CONFIG;
}
}
export async function saveConfig(config: DashboardConfig): Promise<void> {
await fs.mkdir(path.dirname(DASHBOARD_CONFIG_PATH), { recursive: true });
await fs.writeFile(
DASHBOARD_CONFIG_PATH,
JSON.stringify(config, null, 2),
"utf-8"
);
}
async function readConfigFromEnv(): Promise<DashboardConfig | null> {
try {
const raw = await fs.readFile(ENV_FILE_PATH, "utf-8");
const env: Record<string, string> = {};
for (const line of raw.split("\n")) {
const m = line.match(/^([A-Z_]+)=(.*)$/);
if (m) env[m[1]] = m[2];
}
if (env.LLAMA_MODEL || env.LLAMA_EXTRA_ARGS) {
const cfg = parseLlamaExtraArgs(
env.LLAMA_EXTRA_ARGS || "",
env.LLAMA_MODEL || DEFAULT_CONFIG.model
);
return { ...DEFAULT_CONFIG, ...cfg };
}
} catch {
/* ignore */
}
return null;
}
/**
* Parse LLAMA_EXTRA_ARGS string into structured config fields.
* Anything we can't recognize lands in extraArgs.
*/
export function parseLlamaExtraArgs(
raw: string,
model: string
): Omit<DashboardConfig, "presets"> {
const cfg: Omit<DashboardConfig, "presets"> = { ...DEFAULT_CONFIG, model };
const remaining: string[] = [];
// Split respecting quoted args
const tokens = (raw.match(/(?:[^\s"]+|"[^"]*")+/g) || []).map((t) =>
t.replace(/^"|"$/g, "")
);
for (let i = 0; i < tokens.length; i++) {
const tok = tokens[i];
const next = tokens[i + 1];
switch (tok) {
case "--ctx-size":
cfg.ctxSize = Number(next) || cfg.ctxSize;
i++;
break;
case "--parallel":
cfg.parallel = Number(next) || cfg.parallel;
i++;
break;
case "--n-gpu-layers":
case "-ngl":
cfg.nGpuLayers = Number(next);
i++;
break;
case "--threads":
case "-t":
cfg.threads = Number(next);
i++;
break;
case "--batch-size":
case "-b":
cfg.batchSize = Number(next) || cfg.batchSize;
i++;
break;
case "--model-draft":
cfg.draftModel = path.basename(next || "");
i++;
break;
case "--spec-type":
cfg.specType = (next as DashboardConfig["specType"]) || cfg.specType;
i++;
break;
case "--spec-draft-n-max":
cfg.specDraftNMax = Number(next) || cfg.specDraftNMax;
i++;
break;
case "--context-overflow":
cfg.contextOverflow =
(next as DashboardConfig["contextOverflow"]) || cfg.contextOverflow;
i++;
break;
default:
if (tok.startsWith("--") && next && !next.startsWith("--")) {
remaining.push(`${tok} ${next}`);
i++;
} else {
remaining.push(tok);
}
}
}
cfg.extraArgs = remaining.join(" ").trim();
return cfg;
}
/**
* Convert structured config into LLAMA_EXTRA_ARGS string.
*/
export function buildLlamaExtraArgs(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}`);
if (cfg.contextOverflow !== "none")
parts.push(`--context-overflow ${cfg.contextOverflow}`);
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.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}
/**
* Persist LLAMA_MODEL and LLAMA_EXTRA_ARGS to the .env file so the existing
* workflow (and anyone reading .env) still sees the active configuration.
* Other env keys are preserved.
*/
export async function writeEnvLlamaConfig(
model: string,
extraArgs: string
): Promise<void> {
let lines: string[] = [];
try {
const raw = await fs.readFile(ENV_FILE_PATH, "utf-8");
lines = raw.split("\n");
} catch {
/* no .env yet */
}
let hasModel = false;
let hasExtra = false;
const out: string[] = [];
for (const line of lines) {
if (/^LLAMA_MODEL=/.test(line)) {
out.push(`LLAMA_MODEL=${model}`);
hasModel = true;
} else if (/^LLAMA_EXTRA_ARGS=/.test(line)) {
out.push(`LLAMA_EXTRA_ARGS=${extraArgs}`);
hasExtra = true;
} else {
out.push(line);
}
}
if (!hasModel) out.push(`LLAMA_MODEL=${model}`);
if (!hasExtra) out.push(`LLAMA_EXTRA_ARGS=${extraArgs}`);
await fs.writeFile(ENV_FILE_PATH, out.join("\n").replace(/\n+$/, "\n"), "utf-8");
}
// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------
export async function listModels(): Promise<ModelFile[]> {
try {
const entries = await fs.readdir(LLAMA_MODELS_DIR, { withFileTypes: true });
const models: ModelFile[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
if (entry.name.startsWith(".")) continue;
if (!entry.name.toLowerCase().endsWith(".gguf")) continue;
const full = path.join(LLAMA_MODELS_DIR, entry.name);
const stat = await fs.stat(full);
models.push({
name: entry.name,
sizeBytes: stat.size,
sizeHuman: humanSize(stat.size),
modifiedAt: stat.mtime.toISOString(),
});
}
models.sort((a, b) => b.sizeBytes - a.sizeBytes);
return models;
} catch {
return [];
}
}
function humanSize(bytes: number): string {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const v = bytes / Math.pow(1024, i);
return `${v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : 2)} ${units[i]}`;
}
// ---------------------------------------------------------------------------
// Docker / Compose control
// ---------------------------------------------------------------------------
function composeEnv(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
return {
...process.env,
HOST_PROJECT_PATH,
NODE_INSTANCE,
...extra,
};
}
async function runCompose(
args: string[],
env: Record<string, string> = {}
): Promise<{ stdout: string; stderr: string; code: number }> {
const opts: ExecOptions = {
cwd: PROJECT_DIR,
env: composeEnv(env),
maxBuffer: 16 * 1024 * 1024,
};
try {
const { stdout, stderr } = await execAsync(
`docker compose -f "${COMPOSE_FILE}" ${args.join(" ")}`,
opts
);
return {
stdout: String(stdout),
stderr: String(stderr),
code: 0,
};
} catch (err: unknown) {
const e = err as {
stdout?: string | Buffer;
stderr?: string | Buffer;
code?: number;
message: string;
};
return {
stdout: e.stdout ? String(e.stdout) : "",
stderr: e.stderr ? String(e.stderr) : e.message,
code: e.code ?? 1,
};
}
}
export async function listContainers(): Promise<ContainerInfo[]> {
const filter = `--filter label=node.instance=${NODE_INSTANCE}`;
const cmd = `docker ps -a ${filter} --format json`;
try {
const { stdout } = await execAsync(cmd, {
maxBuffer: 16 * 1024 * 1024,
});
const text = String(stdout);
const lines = text.split("\n").filter(Boolean);
const containers: ContainerInfo[] = [];
for (const line of lines) {
try {
const c = JSON.parse(line);
const labels: Record<string, string> = Object.fromEntries(
(c.Labels || "").split(",").map((kv: string) => {
const [k, v] = kv.split("=");
return [k, v ?? ""];
})
);
containers.push({
name: c.Names || c.Name,
status: c.Status,
state: c.State,
running: c.State === "running",
ports: c.Ports || "",
image: c.Image,
role: labels["node.role"] || null,
createdAt: c.CreatedAt || c.Created,
statusText: c.Status,
});
} catch {
/* skip malformed line */
}
}
return containers.sort((a, b) => a.name.localeCompare(b.name));
} catch {
return [];
}
}
export async function getLlamaContainer(): Promise<ContainerInfo | null> {
const list = await listContainers();
return list.find((c) => c.role === "llama") || null;
}
export interface StartResult {
ok: boolean;
message: string;
logs: string;
}
/**
* Start (or force-recreate) the llama service with the given config.
* Mirrors what `gpuctl start llama <model> <args>` does.
*/
export async function startLlama(
config: DashboardConfig
): Promise<StartResult> {
const extraArgs = buildLlamaExtraArgs(config);
// Persist current config so reloads restore it.
await saveConfig(config);
await writeEnvLlamaConfig(config.model, extraArgs);
const res = await runCompose(
[
"--profile",
"llama",
"up",
"-d",
"--force-recreate",
"llama",
],
{
LLAMA_MODEL: config.model,
LLAMA_EXTRA_ARGS: extraArgs,
}
);
const combined = res.stdout + (res.stderr ? `\n${res.stderr}` : "");
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama instance started" : "Failed to start",
logs: combined,
};
}
export async function stopLlama(): Promise<StartResult> {
const res = await runCompose(["stop", "llama"], {});
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama stopped" : "Failed to stop",
logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""),
};
}
export async function restartLlama(): Promise<StartResult> {
const res = await runCompose(["restart", "llama"], {});
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama restarted" : "Failed to restart",
logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""),
};
}
export async function removeLlama(): Promise<StartResult> {
// Equivalent to `gpuctl stop llama` followed by `docker rm -f` semantics.
const res = await runCompose(["rm", "-sf", "llama"], {});
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama instance removed" : "Failed to remove",
logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""),
};
}
// ---------------------------------------------------------------------------
// Logs
// ---------------------------------------------------------------------------
/**
* Returns a Node ReadableStream of `docker logs -f <container>`.
* Caller pipes it to a Response stream.
*/
export function streamLlamaLogs(tail: number = 200) {
const child = spawn("docker", [
"logs",
"-f",
"--tail",
String(tail),
"--timestamps",
`--filter=label=node.role=llama`,
`--filter=label=node.instance=${NODE_INSTANCE}`,
]);
return child;
}
/**
* Get the actual llama container name (so we can `docker logs -f <name>`).
*/
export async function getLlamaContainerName(): Promise<string | null> {
try {
const { stdout } = await execAsync(
`docker ps -a --filter label=node.role=llama --filter label=node.instance=${NODE_INSTANCE} --format {{.Names}}`,
{ maxBuffer: 1 * 1024 * 1024 }
);
return String(stdout).trim().split("\n")[0] || null;
} catch {
return null;
}
}
export async function getLlamaLogsSnapshot(tail: number = 500): Promise<string> {
const name = await getLlamaContainerName();
if (!name) return "[llama container not found]";
try {
const { stdout } = await execAsync(
`docker logs --tail ${tail} ${name}`,
{ maxBuffer: 8 * 1024 * 1024 }
);
return String(stdout);
} catch (err) {
return `[failed to read logs: ${(err as Error).message}]`;
}
}
// ---------------------------------------------------------------------------
// GPU
// ---------------------------------------------------------------------------
export async function getGpuStatus(): Promise<{
ok: boolean;
output: string;
}> {
// Try to exec nvidia-smi on the llama container first; if not running,
// fall back to running `docker compose run --rm gpu-test nvidia-smi ...`
const name = await getLlamaContainerName();
if (name) {
try {
const { stdout } = await execAsync(
`docker exec ${name} nvidia-smi --query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw --format=csv`,
{ maxBuffer: 4 * 1024 * 1024 }
);
return { ok: true, output: String(stdout) };
} catch {
/* fall through */
}
}
const res = await runCompose(
[
"--profile",
"test",
"run",
"--rm",
"gpu-test",
"nvidia-smi",
"--query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw",
"--format=csv",
],
{}
);
return { ok: res.code === 0, output: res.stdout + res.stderr };
}
// ---------------------------------------------------------------------------
// Llama server health
// ---------------------------------------------------------------------------
export async function getLlamaHealth(): Promise<{
reachable: boolean;
detail: string;
}> {
// Llama.cpp /completion endpoint returns 405 on GET /, but /health works.
try {
const { stdout } = await execAsync(
`docker exec $(docker ps --filter label=node.role=llama --filter label=node.instance=${NODE_INSTANCE} --format {{.Names}} | head -n1) wget -qO- http://127.0.0.1:8080/health || true`,
{ maxBuffer: 1 * 1024 * 1024, timeout: 5000 }
);
const text = String(stdout);
if (text.includes("ok")) return { reachable: true, detail: text.trim() };
return { reachable: false, detail: text || "no response" };
} catch (err) {
return {
reachable: false,
detail: (err as Error).message,
};
}
}