import { exec, spawn, type ExecOptions } from "node:child_process"; import { promisify } from "node:util"; import { promises as fs, existsSync } 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"; /** * Path to the project's .env file. We parse it ourselves to ensure compose * always gets the right HOST_PROJECT_PATH / TAILSCALE_HOSTNAME, regardless * of how the dashboard container itself was started. */ export const ENV_FILE_PATH = path.join(PROJECT_DIR, ".env"); /** * Parsed contents of the .env file. Read once at startup, cached. * Falls back to {} if the file doesn't exist (only happens on dev machines). */ let _envCache: Record | null = null; async function loadEnvFile(): Promise> { if (_envCache !== null) return _envCache; const out: Record = {}; try { const raw = await fs.readFile(ENV_FILE_PATH, "utf-8"); for (const line of raw.split("\n")) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) continue; const eq = trimmed.indexOf("="); if (eq < 0) continue; const key = trimmed.slice(0, eq).trim(); let val = trimmed.slice(eq + 1).trim(); // Strip surrounding quotes if ( (val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'")) ) { val = val.slice(1, -1); } out[key] = val; } } catch { /* .env doesn't exist — fall through with empty out */ } _envCache = out; return out; } /** * Sync version (uses cache populated by loadEnvFile, or reads file on first * call). Used in places that can't be async (e.g. module-level exports). */ function readEnvSync(): Record { if (_envCache !== null) return _envCache; const out: Record = {}; if (existsSync(ENV_FILE_PATH)) { try { // eslint-disable-next-line @typescript-eslint/no-require-imports const raw = require("node:fs").readFileSync(ENV_FILE_PATH, "utf-8"); for (const line of raw.split("\n")) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) continue; const eq = trimmed.indexOf("="); if (eq < 0) continue; const key = trimmed.slice(0, eq).trim(); let val = trimmed.slice(eq + 1).trim(); if ( (val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'")) ) { val = val.slice(1, -1); } out[key] = val; } } catch { /* ignore */ } } _envCache = out; return out; } /** * Resolve an env value: process.env first (set by compose.yaml), then .env * file, then the given default. */ function envOrFile(key: string, fallback: string = ""): string { const fromProcess = process.env[key]; if (fromProcess && fromProcess.length > 0) return fromProcess; const fromFile = readEnvSync()[key]; if (fromFile && fromFile.length > 0) return fromFile; return fallback; } /** * 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). * * Reads from env first, then .env file. If neither is set, returns "/project" * (the internal mount) as a last-resort fallback — but operations that need * the real host path will fail with a clear error. */ export const HOST_PROJECT_PATH = envOrFile("HOST_PROJECT_PATH", "/project"); /** * Tailscale hostname — used for container_name and NODE_INSTANCE labels. * Read from env / .env so we always match what the rest of the stack is using. */ export const TAILSCALE_HOSTNAME = envOrFile("TAILSCALE_HOSTNAME", "gpu-node"); /** * Internal mount of the llama_models directory. */ export const LLAMA_MODELS_DIR = process.env.LLAMA_MODELS_DIR || path.join(PROJECT_DIR, "gpu", "llama_models"); /** * Internal mount of the comfy models directory (mirrors the host path that * the model-worker container mounts as /models). */ export const COMFY_MODELS_DIR = process.env.COMFY_MODELS_DIR || path.join(PROJECT_DIR, "gpu", "comfy", "models"); /** * Node instance name (used for filtering containers by label). */ export const NODE_INSTANCE = envOrFile("NODE_INSTANCE", "") || TAILSCALE_HOSTNAME; /** * 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" ); // --------------------------------------------------------------------------- // 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; 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 { 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 { 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 { try { const raw = await fs.readFile(ENV_FILE_PATH, "utf-8"); const env: Record = {}; 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 { const cfg: Omit = { ...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 { 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"); // Invalidate the in-memory .env cache so the next composeEnv() call picks // up the new values. _envCache = null; } // --------------------------------------------------------------------------- // Models // --------------------------------------------------------------------------- export async function listModels(): Promise { 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 // --------------------------------------------------------------------------- /** * Validate that the env vars needed by `docker compose` are actually set. * Returns null if all good, or an error message describing the first missing * var. Mirrors what `gpuctl` does via `require_host_project_path` etc. */ export async function validateComposeEnv(): Promise { // Make sure .env is loaded await loadEnvFile(); if (!HOST_PROJECT_PATH || HOST_PROJECT_PATH === "/project") { // /project is the internal mount — compose needs the actual host path return ( "HOST_PROJECT_PATH is not set. Set it in /project/.env to the absolute " + "path of the GPU-Node directory on the host (e.g. " + "/home/operator/projects/GPU-Node). Without it, compose will resolve " + "${HOST_PROJECT_PATH:-./} to './' relative to the dashboard container's " + "CWD — but the resulting path doesn't exist on the host." ); } if (!TAILSCALE_HOSTNAME) { return "TAILSCALE_HOSTNAME is not set in env or .env file"; } return null; } /** * Build the env for `docker compose` subprocess. * * IMPORTANT: we explicitly set every variable that compose.yaml references, * pulling from process.env (set by the dashboard container's own * environment: line in compose.yaml) and falling back to the .env file * parsed at startup. This mirrors how `gpuctl` shells pass `HOST_PROJECT_PATH=...` * before `docker compose`. * * The full list comes from the .env.example: * - TAILSCALE_HOSTNAME (used in container_name) * - TS_AUTHKEY (needed by tailscale service) * - WEBDAV_USER, WEBDAV_PASS (needed by webdav service) * - HOST_PROJECT_PATH (used in all volume mounts) * - LLAMA_MODEL, LLAMA_EXTRA_ARGS (used by llama service command) * - COMFY_RUN_HOST, COMFY_BASE_HOST (used by comfyui service) * - COMFY_EXTRA_ARGS (used by comfyui service) * - NODE_INSTANCE (set by dashboard service in compose.yaml) */ function composeEnv(extra: Record = {}): NodeJS.ProcessEnv { // Start from .env file contents (lowest precedence) const fileEnv = readEnvSync(); return { // Inherit the dashboard container's own process env (PATH, HOME, etc.) ...process.env, // .env file vars (these are also what compose would read if we didn't // pass them explicitly, but explicit is better — compose's --env-file // behaviour depends on CWD which may differ) ...fileEnv, // Explicit overrides for variables we know compose needs TAILSCALE_HOSTNAME, HOST_PROJECT_PATH, NODE_INSTANCE, LLAMA_MODELS_DIR: undefined, // unset to avoid leaking internal mount // Caller-provided overrides (e.g. LLAMA_MODEL, LLAMA_EXTRA_ARGS for `up`) ...extra, }; } async function runCompose( args: string[], env: Record = {} ): Promise<{ stdout: string; stderr: string; code: number }> { // Pre-validate env for `up`/`start` operations — fail fast with a clear // error instead of letting compose silently resolve ${HOST_PROJECT_PATH:-./} // to './' and then fail with a cryptic volume mount error. const isUp = args.some((a) => a === "up" || a === "start" || a === "create"); if (isUp) { const err = await validateComposeEnv(); if (err) { return { stdout: "", stderr: `[dashboard] ${err}`, code: 1, }; } } // Make sure .env is loaded (no-op if already cached) await loadEnvFile(); 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 { 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 = 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 { 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 ` does. */ export async function startLlama( config: DashboardConfig ): Promise { const extraArgs = buildLlamaExtraArgs(config); // Persist current config so reloads restore it. await saveConfig(config); await writeEnvLlamaConfig(config.model, extraArgs); // Log what we're actually starting with — helps diagnose "model didn't // change" issues (the most common cause is the request body not including // the new model, or compose picking up an old LLAMA_MODEL from .env). console.log("[startLlama] model:", config.model); console.log("[startLlama] extraArgs:", 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}` : ""); console.log("[startLlama] compose exit:", res.code); console.log("[startLlama] compose output:\n", combined); return { ok: res.code === 0, message: res.code === 0 ? `Llama started (model: ${config.model})` : `Failed to start (exit ${res.code})`, logs: combined, }; } export async function stopLlama(): Promise { 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 { 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 { // 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 `. * 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 `). */ export async function getLlamaContainerName(): Promise { 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 { 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, }; } } // --------------------------------------------------------------------------- // Generic service control (start / stop / restart / remove / logs) // --------------------------------------------------------------------------- export type ServiceRole = | "llama" | "comfyui" | "model-worker" | "webdav" | "ssh" | "ssh-companion" | "gpu-test" | "dashboard" | "tailscale"; const COMPOSE_PROFILES: Partial> = { llama: "llama", comfyui: "comfy", "gpu-test": "test", // ssh-companion / model-worker / webdav need the `wake` profile when // starting from scratch, but `docker compose up -d ` with explicit // service name overrides the profile check at the compose level. "ssh-companion": "wake", "model-worker": "wake", webdav: "wake", }; export async function startService( role: ServiceRole ): Promise { const profile = COMPOSE_PROFILES[role]; const args = ["up", "-d", "--force-recreate", role]; if (profile) args.unshift("--profile", profile); const res = await runCompose(args, {}); return { ok: res.code === 0, message: res.code === 0 ? `${role} started` : `Failed to start ${role}`, logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""), }; } export async function stopService(role: ServiceRole): Promise { // For profile services, we need to pass --profile too so compose knows about them const profile = COMPOSE_PROFILES[role]; const args = ["stop", role]; if (profile) args.unshift("--profile", profile); const res = await runCompose(args, {}); return { ok: res.code === 0, message: res.code === 0 ? `${role} stopped` : `Failed to stop ${role}`, logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""), }; } export async function restartService( role: ServiceRole ): Promise { const profile = COMPOSE_PROFILES[role]; const args = ["restart", role]; if (profile) args.unshift("--profile", profile); const res = await runCompose(args, {}); return { ok: res.code === 0, message: res.code === 0 ? `${role} restarted` : `Failed to restart ${role}`, logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""), }; } export async function removeService( role: ServiceRole ): Promise { // For services that the dashboard might want to nuke (e.g. llama), do a // hard `docker rm -f` on the container found via labels. This avoids // the profile problem entirely. const name = await getServiceContainerName(role); if (!name) { return { ok: false, message: `${role} not found`, logs: "" }; } try { await execAsync(`docker rm -f ${name}`, { maxBuffer: 1 * 1024 * 1024, }); return { ok: true, message: `${role} removed`, logs: `removed ${name}`, }; } catch (err) { return { ok: false, message: `Failed to remove ${role}`, logs: (err as Error).message, }; } } export async function getServiceContainerName( role: ServiceRole ): Promise { // Map service roles to docker-compose labels const labelRole = role === "ssh" ? "ssh-main" : role === "ssh-companion" ? "ssh-companion" : role; try { const { stdout } = await execAsync( `docker ps -a --filter label=node.role=${labelRole} --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 getServiceLogs( role: ServiceRole, tail: number = 500 ): Promise { const name = await getServiceContainerName(role); if (!name) return `[${role} container not found]`; try { const { stdout } = await execAsync(`docker logs --tail ${tail} ${name}`, { maxBuffer: 16 * 1024 * 1024, }); return String(stdout); } catch (err) { return `[failed: ${(err as Error).message}]`; } } // --------------------------------------------------------------------------- // ComfyUI model worker proxy (mirrors `gpuctl comfy models ...`) // --------------------------------------------------------------------------- async function modelWorkerExec( ...args: string[] ): Promise<{ ok: boolean; output: string; error: string }> { const container = await getServiceContainerName("model-worker"); if (!container) { return { ok: false, output: "", error: "model-worker container not found", }; } try { const quoted = args.map((a) => `'${a.replace(/'/g, "'\\''")}'`).join(" "); const cmd = `docker exec ${container} python3 /app/worker.py ${quoted}`; const { stdout, stderr } = await execAsync(cmd, { maxBuffer: 8 * 1024 * 1024, }); return { ok: true, output: String(stdout), error: String(stderr), }; } catch (err) { const e = err as { stdout?: string | Buffer; stderr?: string | Buffer; message: string; code?: number; }; // Log the failure so it's visible in dashboard container logs console.error( `[modelWorkerExec] args=${JSON.stringify(args)} container=${container} exitCode=${e.code} stderr=${e.stderr ? String(e.stderr).slice(0, 500) : "(empty)"} message=${e.message}` ); return { ok: false, output: e.stdout ? String(e.stdout) : "", error: e.stderr ? String(e.stderr) : e.message, }; } } export interface ComfyModelEntry { type: string; filename: string; sizeBytes?: number; sizeHuman?: string; } /** * Read comfy model types directly from the filesystem (subdirs of * /project/gpu/comfy/models). Used as a fallback when the model-worker * container isn't running. * * Returns the same shape as `worker.py types`. */ async function listComfyTypesFromFs(): Promise { try { const entries = await fs.readdir(COMFY_MODELS_DIR, { withFileTypes: true }); return entries .filter((e) => e.isDirectory() && !e.isSymbolicLink()) .map((e) => e.name) .sort(); } catch { return []; } } /** * Read comfy models directly from the filesystem. Walks each subdirectory * (one per model type) and lists all files inside. Used as a fallback when * the model-worker container isn't running. * * Returns the same shape as `worker.py list --json`. */ async function listComfyModelsFromFs( type?: string ): Promise { const out: ComfyModelEntry[] = []; try { if (type) { // Single type — list its contents const typeDir = path.join(COMFY_MODELS_DIR, type); const stat = await fs.stat(typeDir).catch(() => null); if (!stat || !stat.isDirectory()) return []; const entries = await fs.readdir(typeDir, { withFileTypes: true }); for (const entry of entries) { if (!entry.isFile()) continue; if (entry.name.startsWith(".")) continue; const full = path.join(typeDir, entry.name); const size = await fs.stat(full).then((s) => s.size).catch(() => 0); out.push({ type, filename: entry.name, sizeBytes: size, sizeHuman: size > 0 ? humanSize(size) : undefined, }); } } else { // All types — walk each subdir const types = await listComfyTypesFromFs(); for (const t of types) { const typeDir = path.join(COMFY_MODELS_DIR, t); const entries = await fs.readdir(typeDir, { withFileTypes: true }); for (const entry of entries) { if (!entry.isFile()) continue; if (entry.name.startsWith(".")) continue; const full = path.join(typeDir, entry.name); const size = await fs.stat(full).then((s) => s.size).catch(() => 0); out.push({ type: t, filename: entry.name, sizeBytes: size, sizeHuman: size > 0 ? humanSize(size) : undefined, }); } } } } catch { /* ignore */ } return out; } export async function listComfyModels( type?: string ): Promise<{ ok: boolean; models: ComfyModelEntry[]; raw: string; error?: string }> { // Try the model-worker first — it knows which files are real models vs // metadata files (.txt etc.) and follows ComfyUI's naming conventions. const args = ["list"]; if (type) args.push(type); args.push("--json"); const res = await modelWorkerExec(...args); if (res.ok) { try { const parsed = JSON.parse(res.output); if (parsed.error) { return { ok: false, models: [], raw: res.output, error: parsed.error, }; } const arr: ComfyModelEntry[] = (parsed.models || []).map( (m: { type: string; filename: string; sizeBytes?: number }) => ({ type: m.type, filename: m.filename, sizeBytes: m.sizeBytes, sizeHuman: m.sizeBytes ? humanSize(m.sizeBytes) : undefined, }) ); return { ok: true, models: arr, raw: res.output }; } catch { // Fall through to fs fallback } } // Fallback: read directly from the filesystem. Useful when: // - model-worker container isn't running (e.g. during sleep mode) // - worker.py doesn't support --json flag (older version) // - docker exec fails for any reason const models = await listComfyModelsFromFs(type); return { ok: true, models, raw: res.output || "", error: res.ok ? undefined : res.error, }; } export async function getComfyTypes(): Promise<{ ok: boolean; types: string[]; raw: string; error?: string; }> { // Try the model-worker first. const res = await modelWorkerExec("types"); if (res.ok) { try { const parsed = JSON.parse(res.output); const arr: string[] = Array.isArray(parsed) ? parsed : []; if (arr.length > 0) { return { ok: true, types: arr, raw: res.output }; } } catch { /* fall through */ } } // Fallback: read subdirectories of gpu/comfy/models directly. // The model-worker container might not be running (sleep mode), but the // directory is mounted into the dashboard container at /project/gpu/comfy. const types = await listComfyTypesFromFs(); return { ok: types.length > 0, types, raw: res.output || "", error: types.length > 0 ? undefined : res.error || "no types found", }; } export 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; started_at?: string; finished_at?: string; } export async function getComfyQueue(): Promise<{ ok: boolean; queue: ComfyQueueEntry[]; raw: string; error?: string; }> { // Use the new --json flag. const res = await modelWorkerExec("queue", "--json"); if (!res.ok) return { ok: false, queue: [], raw: res.output, error: res.error }; try { const parsed = JSON.parse(res.output); const arr: ComfyQueueEntry[] = parsed.jobs || []; return { ok: true, queue: arr, raw: res.output }; } catch { return { ok: true, queue: [], raw: res.output }; } } export async function addComfyModel( url: string, type: string ): Promise<{ ok: boolean; output: string; error?: string }> { const res = await modelWorkerExec("add", url, type); return { ok: res.ok, output: res.output, error: res.error }; } export async function removeComfyModel( filename: string, type?: string ): Promise<{ ok: boolean; output: string; error?: string }> { const args = ["rm", filename]; if (type) args.push(type); const res = await modelWorkerExec(...args); return { ok: res.ok, output: res.output, error: res.error }; } // --------------------------------------------------------------------------- // System actions (sleep / wake / update) // --------------------------------------------------------------------------- export async function sleepMode(): Promise { // Equivalent of `gpuctl sleep`: // - keep tailscale + (ssh-main OR ssh-companion), whichever is running // - remove: llama, comfyui, gpu-test, model-worker, webdav, dashboard // - remove the *other* ssh role container const main = await getServiceContainerName("ssh"); const companion = await getServiceContainerName("ssh-companion"); let keepRole: "ssh" | "ssh-companion" | "ssh"; let removeRole: "ssh" | "ssh-companion" | null = null; if (main) { keepRole = "ssh"; removeRole = "ssh-companion"; } else if (companion) { keepRole = "ssh-companion"; removeRole = "ssh"; } else { // Neither running — start ssh-main const r = await startService("ssh"); if (!r.ok) return r; keepRole = "ssh"; removeRole = "ssh-companion"; } const toRemove: ServiceRole[] = [ "llama", "comfyui", "gpu-test", "model-worker", "webdav", "dashboard", ]; if (removeRole) toRemove.push(removeRole); const logs: string[] = []; for (const role of toRemove) { const name = await getServiceContainerName(role); if (name) { try { await execAsync(`docker rm -f ${name}`, { maxBuffer: 1 * 1024 * 1024 }); logs.push(`removed ${role} (${name})`); } catch (err) { logs.push(`failed to remove ${role}: ${(err as Error).message}`); } } } return { ok: true, message: `Sleep mode: keeping tailscale + ${keepRole}`, logs: logs.join("\n"), }; } export async function wakeMode(): Promise { // Equivalent of `gpuctl wake`: // - swap ssh role (start the OTHER ssh service + model-worker + webdav + dashboard) // We can detect which one is currently running from inside the dashboard // container via SSH_ROLE env (set in compose.yaml). But for simplicity we // always start ssh-companion + model-worker + webdav + dashboard. // If user is already on ssh-companion, starting it again is a no-op. const sshRole = process.env.SSH_ROLE || "main"; const targetSsh = sshRole === "main" ? "ssh-companion" : "ssh"; const res = await runCompose( ["--profile", "wake", "up", "-d", targetSsh, "model-worker", "webdav", "dashboard"], {} ); return { ok: res.code === 0, message: res.code === 0 ? `Wake mode: started ${targetSsh} + model-worker + webdav + dashboard` : "Failed to wake", logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""), }; } export async function updateNode(): Promise { // Equivalent of `gpuctl update`: // - run build.sh // - swap ssh role + restart model-worker // The build.sh runs on the HOST (or inside the ssh container). We try to // exec it via the ssh-main container. const sshRole = process.env.SSH_ROLE || "main"; const targetSsh = sshRole === "main" ? "ssh-companion" : "ssh"; // Build images try { const { stdout, stderr } = await execAsync( `sh ${PROJECT_DIR}/build.sh`, { cwd: PROJECT_DIR, env: composeEnv(), maxBuffer: 32 * 1024 * 1024, timeout: 600000, } ); const buildLog = String(stdout) + String(stderr); // Now restart target ssh + model-worker + dashboard const res = await runCompose( ["--profile", "wake", "up", "-d", "--force-recreate", targetSsh, "model-worker", "dashboard"], {} ); return { ok: res.code === 0, message: res.code === 0 ? `Update complete: rebuilt + restarted ${targetSsh} + model-worker + dashboard` : "Build OK, restart failed", logs: buildLog + "\n---\n" + res.stdout + res.stderr, }; } catch (err) { return { ok: false, message: "Build failed", logs: (err as Error).message, }; } } // --------------------------------------------------------------------------- // Model upload (.gguf) // --------------------------------------------------------------------------- export async function saveUploadedModel( filename: string, data: Buffer ): Promise<{ ok: boolean; path: string; error?: string }> { // Sanitize filename — only allow .gguf extension, no path traversal const safe = path.basename(filename).replace(/[^\w.\-]/g, "_"); if (!safe.toLowerCase().endsWith(".gguf")) { return { ok: false, path: "", error: "Only .gguf files are allowed" }; } const full = path.join(LLAMA_MODELS_DIR, safe); await fs.writeFile(full, data); return { ok: true, path: full }; } export async function deleteModel( filename: string ): Promise<{ ok: boolean; error?: string }> { const safe = path.basename(filename).replace(/[^\w.\-]/g, "_"); if (!safe.toLowerCase().endsWith(".gguf")) { return { ok: false, error: "Only .gguf files are allowed" }; } const full = path.join(LLAMA_MODELS_DIR, safe); try { await fs.unlink(full); return { ok: true }; } catch (err) { return { ok: false, error: (err as Error).message }; } }