## Problem
'цивитай в comfy models нужен скорее' — the CivitAI URL transformation
(model page → API download URL, token append) was only applied to llama
model downloads via `/api/models/download`. ComfyUI model downloads via
`/api/comfy/models/add` just passed the raw URL straight to
model-worker, so CivitAI model page URLs would download HTML instead of
the actual file, and gated/NSFW models would 401 without a token.
## Fix
### Backend
#### `dashboard/src/lib/docker.ts` — addComfyModel()
Now applies the same `prepareCivitaiUrl()` transformation as
`startModelDownload()`:
1. Loads settings (to get the saved civitaiToken)
2. Calls `prepareCivitaiUrl(rawUrl, token)`:
- civitai.com/models/12345 → civitai.com/api/download/models/12345
- civitai.red/... → normalize host to civitai.com
- append ?token=XXX if missing
3. Passes the transformed URL to `modelWorkerExec('add', url, type)`
4. Returns `originalUrl`, `transformedUrl`, `urlNote` in the response
so the frontend can show what happened
Uses lazy `await import('./downloads')` to avoid a circular import
between docker.ts (which exports paths) and downloads.ts (which imports
them).
#### `dashboard/src/app/api/comfy/models/add/route.ts`
Returns the transformation metadata (`originalUrl`, `transformedUrl`,
`urlNote`) in the JSON response.
### Frontend
#### `dashboard/src/app/page.tsx`
- New state: `comfyUrlPreview` — separate from `urlPreview` (which is
for the llama Models tab) so switching tabs doesn't mix them up.
- New debounced effect: watches `comfyAddUrl` and calls
`POST /api/settings {action:'preview-url'}` to get the transformed URL.
- `handleComfyAddModel()` now reads `urlNote` and `transformedUrl`
from the response and includes them in the toast message (multi-line)
so the user sees what happened to their pasted URL.
- `<ComfyTab>` now accepts `civitaiToken`, `onSaveCivitaiToken`, and
`urlPreview` props.
- ComfyTab 'Queue Download' section:
- 'CivitAI token' button (with badge 'set' / 'empty') in the header —
opens a settings panel with password input, Save/Clear buttons, and
a link to https://civitai.com/user/account.
- The settings panel notes that the token is shared with the
llama-models downloader (same settings.json).
- URL input placeholder updated to show CivitAI URLs are accepted.
- Enter key in the URL field queues the download (no need to click
Queue button).
- URL preview card appears below the input when the URL will be
transformed (e.g. civitai.com/models/12345 →
civitai.com/api/download/models/12345?token=...), showing the
transformed URL + note.
## How it works end-to-end
1. User opens Comfy tab → 'CivitAI token' button → pastes token → Save
(stored in `gpu/dashboard/settings.json`, shared with llama downloader)
2. User pastes `https://civitai.com/models/12345` in URL field
3. URL preview card shows:
```
[CivitAI] converted model page → API download URL, added API token
https://civitai.com/api/download/models/12345?token=XXX...
```
4. User selects type (checkpoints/loras/etc) and clicks Queue (or Enter)
5. Backend `addComfyModel()` transforms URL → calls
`docker exec model-worker python3 /app/worker.py add <transformed-url> <type>`
6. Worker downloads the file with token auth → saves to
`gpu/comfy/models/<type>/<filename>`
7. Toast shows: 'Queued: checkpoints\nconverted model page → API download
URL, added API token\n→ https://civitai.com/api/download/models/...'
## Verification
- `npm run build` — OK, 26 routes
- `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓
## After deploy
```sh
git pull && sh build.sh
docker compose up -d --force-recreate dashboard
```
Open Comfy tab → 'CivitAI token' button → paste token → Save.
Paste any CivitAI URL (model page or API download URL) → see preview →
Queue. The model fetches with token auth and lands in the right type
subdirectory.
## Files changed
- dashboard/src/lib/docker.ts — addComfyModel() applies prepareCivitaiUrl
- dashboard/src/app/api/comfy/models/add/route.ts — returns transformation metadata
- dashboard/src/app/page.tsx — comfyUrlPreview state, debounced preview
effect, handleComfyAddModel shows transformation in toast, ComfyTab
gets civitai token UI + URL preview + Enter-to-queue
1699 lines
52 KiB
TypeScript
1699 lines
52 KiB
TypeScript
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<string, string> | null = null;
|
|
|
|
async function loadEnvFile(): Promise<Record<string, string>> {
|
|
if (_envCache !== null) return _envCache;
|
|
const out: Record<string, string> = {};
|
|
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<string, string> {
|
|
if (_envCache !== null) return _envCache;
|
|
const out: Record<string, string> = {};
|
|
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 settings (civitai token, etc).
|
|
*/
|
|
export const DASHBOARD_SETTINGS_PATH = path.join(
|
|
PROJECT_DIR,
|
|
"gpu",
|
|
"dashboard",
|
|
"settings.json"
|
|
);
|
|
|
|
/**
|
|
* 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 (prompt processing batch) */
|
|
batchSize: number;
|
|
/** Micro-batch size (physical batch on GPU) */
|
|
ubatchSize: number;
|
|
/** UB / KV cache size etc */
|
|
contextOverflow: "none" | "shift" | "evict";
|
|
/** KV cache type for K */
|
|
cacheTypeK: "f16" | "f32" | "q8_0" | "q4_0";
|
|
/** KV cache type for V */
|
|
cacheTypeV: "f16" | "f32" | "q8_0" | "q4_0";
|
|
/** KV cache defragmentation threshold (0..1) */
|
|
defragThold: number;
|
|
/** Enable Flash Attention */
|
|
flashAttn: boolean;
|
|
/** Don't mmap model (load to RAM) */
|
|
noMmap: boolean;
|
|
/** Lock model in RAM (prevents swap) */
|
|
mlock: boolean;
|
|
/** Continuous batching */
|
|
contBatching: boolean;
|
|
/** Enable /embeddings endpoint */
|
|
embeddings: boolean;
|
|
/** Enable /metrics (Prometheus) endpoint */
|
|
metrics: boolean;
|
|
/** RoPE frequency scale (NTK-aware, 1.0 = default) */
|
|
ropeFreqScale: number;
|
|
/** RoPE context scaling factor (1.0 = default) */
|
|
ropeScale: number;
|
|
/** YaRN extrapolation factor (1.0 = default) */
|
|
yarnExtFactor: number;
|
|
/** YaRN attention factor (1.0 = default) */
|
|
yarnAttnFactor: number;
|
|
/** YaRN beta fast (32.0 = default) */
|
|
yarnBetaFast: number;
|
|
/** YaRN beta slow (1.0 = default) */
|
|
yarnBetaSlow: number;
|
|
/** Default system prompt for chat completions (empty = none) */
|
|
systemPrompt: string;
|
|
/** Sampling: top-k (0 = disabled) */
|
|
topK: number;
|
|
/** Sampling: top-p (1.0 = disabled) */
|
|
topP: number;
|
|
/** Sampling: min-p (0 = disabled) */
|
|
minP: number;
|
|
/** Sampling: temperature (1.0 = default) */
|
|
temperature: number;
|
|
/** Sampling: repeat penalty (1.0 = disabled) */
|
|
repeatPenalty: number;
|
|
/**
|
|
* Max tokens to predict per response. -1 = infinity (model decides).
|
|
* Sets --n-predict on the server side; also passed as max_tokens
|
|
* per-request in /api/chat.
|
|
*/
|
|
nPredict: number;
|
|
/**
|
|
* Reasoning format for thinking models (Qwen3, DeepSeek-R1, gpt-oss).
|
|
* - "auto": llama.cpp auto-detects and splits <think>...</think> into
|
|
* the reasoning_content field (recommended)
|
|
* - "deepthink": force thinking even if model wouldn't normally
|
|
* - "none": passthrough raw (thinking tags appear in content)
|
|
*/
|
|
reasoningFormat: "none" | "deepthink" | "auto";
|
|
/** Enable Jinja chat templates (required for tool calling + reasoning) */
|
|
jinja: boolean;
|
|
/** 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,
|
|
ubatchSize: 512,
|
|
contextOverflow: "none",
|
|
cacheTypeK: "f16",
|
|
cacheTypeV: "f16",
|
|
defragThold: 0.1,
|
|
flashAttn: true,
|
|
noMmap: false,
|
|
mlock: false,
|
|
contBatching: true,
|
|
embeddings: false,
|
|
metrics: false,
|
|
ropeFreqScale: 1.0,
|
|
ropeScale: 1.0,
|
|
yarnExtFactor: 1.0,
|
|
yarnAttnFactor: 1.0,
|
|
yarnBetaFast: 32.0,
|
|
yarnBetaSlow: 1.0,
|
|
systemPrompt: "",
|
|
topK: 40,
|
|
topP: 0.95,
|
|
minP: 0.05,
|
|
temperature: 0.8,
|
|
repeatPenalty: 1.1,
|
|
nPredict: -1,
|
|
reasoningFormat: "auto",
|
|
jinja: true,
|
|
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];
|
|
// Helper: check if next token is a value (not another flag)
|
|
const isValue = (s: string | undefined) =>
|
|
s != null && !s.startsWith("--") && !s.startsWith("-");
|
|
|
|
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 "--ubatch-size":
|
|
case "-ub":
|
|
cfg.ubatchSize = Number(next) || cfg.ubatchSize;
|
|
i++;
|
|
break;
|
|
case "--cache-type-k":
|
|
cfg.cacheTypeK = (next as DashboardConfig["cacheTypeK"]) || cfg.cacheTypeK;
|
|
i++;
|
|
break;
|
|
case "--cache-type-v":
|
|
cfg.cacheTypeV = (next as DashboardConfig["cacheTypeV"]) || cfg.cacheTypeV;
|
|
i++;
|
|
break;
|
|
case "--defrag-thold":
|
|
cfg.defragThold = Number(next) || cfg.defragThold;
|
|
i++;
|
|
break;
|
|
case "--flash-attn":
|
|
case "-fa":
|
|
// Modern: --flash-attn on|off|auto (default auto).
|
|
// Legacy: --flash-attn (bare flag, no value).
|
|
if (isValue(next) && /^(on|off|auto)$/i.test(next)) {
|
|
cfg.flashAttn = next.toLowerCase() !== "off";
|
|
i++;
|
|
} else {
|
|
cfg.flashAttn = true;
|
|
}
|
|
break;
|
|
case "--load-mode":
|
|
case "-lm":
|
|
// Replaces --mlock / --no-mmap in modern llama.cpp
|
|
if (isValue(next)) {
|
|
const mode = next.toLowerCase();
|
|
if (mode === "mlock") {
|
|
cfg.mlock = true;
|
|
cfg.noMmap = true;
|
|
} else if (mode === "mmap+mlock") {
|
|
cfg.mlock = true;
|
|
cfg.noMmap = false;
|
|
} else if (mode === "none") {
|
|
cfg.noMmap = true;
|
|
}
|
|
i++;
|
|
}
|
|
break;
|
|
case "--no-mmap":
|
|
cfg.noMmap = true;
|
|
break;
|
|
case "--mlock":
|
|
cfg.mlock = true;
|
|
break;
|
|
case "--cont-batching":
|
|
case "-cb":
|
|
cfg.contBatching = true;
|
|
break;
|
|
case "--no-cont-batching":
|
|
case "-nocb":
|
|
cfg.contBatching = false;
|
|
break;
|
|
case "--embeddings":
|
|
cfg.embeddings = true;
|
|
break;
|
|
case "--metrics":
|
|
cfg.metrics = true;
|
|
break;
|
|
case "--rope-freq-scale":
|
|
cfg.ropeFreqScale = Number(next) || cfg.ropeFreqScale;
|
|
i++;
|
|
break;
|
|
case "--rope-scale":
|
|
cfg.ropeScale = Number(next) || cfg.ropeScale;
|
|
i++;
|
|
break;
|
|
case "--rope-scaling":
|
|
// Modern: enum {none,linear,yarn}. Legacy: numeric factor.
|
|
// If numeric, treat as --rope-scale (the new flag for the factor).
|
|
if (isValue(next) && /^\d/.test(next)) {
|
|
cfg.ropeScale = Number(next) || cfg.ropeScale;
|
|
i++;
|
|
} else if (isValue(next)) {
|
|
// enum value like 'yarn' — ignore, it's the scaling method not the factor
|
|
i++;
|
|
}
|
|
break;
|
|
case "--yarn-ext-factor":
|
|
cfg.yarnExtFactor = Number(next) || cfg.yarnExtFactor;
|
|
i++;
|
|
break;
|
|
case "--yarn-attn-factor":
|
|
cfg.yarnAttnFactor = Number(next) || cfg.yarnAttnFactor;
|
|
i++;
|
|
break;
|
|
case "--yarn-beta-fast":
|
|
cfg.yarnBetaFast = Number(next) || cfg.yarnBetaFast;
|
|
i++;
|
|
break;
|
|
case "--yarn-beta-slow":
|
|
cfg.yarnBetaSlow = Number(next) || cfg.yarnBetaSlow;
|
|
i++;
|
|
break;
|
|
case "--top-k":
|
|
cfg.topK = Number(next);
|
|
i++;
|
|
break;
|
|
case "--top-p":
|
|
cfg.topP = Number(next);
|
|
i++;
|
|
break;
|
|
case "--min-p":
|
|
cfg.minP = Number(next);
|
|
i++;
|
|
break;
|
|
case "--temp":
|
|
case "--temperature":
|
|
cfg.temperature = Number(next);
|
|
i++;
|
|
break;
|
|
case "--repeat-penalty":
|
|
cfg.repeatPenalty = Number(next);
|
|
i++;
|
|
break;
|
|
case "--n-predict":
|
|
case "--predict":
|
|
case "-n":
|
|
cfg.nPredict = Number(next);
|
|
i++;
|
|
break;
|
|
case "--reasoning-format":
|
|
if (isValue(next)) {
|
|
cfg.reasoningFormat = next as DashboardConfig["reasoningFormat"];
|
|
i++;
|
|
}
|
|
break;
|
|
case "--jinja":
|
|
cfg.jinja = true;
|
|
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}`);
|
|
parts.push(`--ubatch-size ${cfg.ubatchSize}`);
|
|
if (cfg.contextOverflow !== "none")
|
|
parts.push(`--context-overflow ${cfg.contextOverflow}`);
|
|
// KV cache types
|
|
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}`);
|
|
// Performance flags
|
|
// --flash-attn takes a value (on/off/auto) since llama.cpp changed the CLI
|
|
// (https://github.com/ggml-org/llama.cpp/issues/...). Passing it as a bare
|
|
// flag causes 'unknown value for --flash-attn: <next-flag>'.
|
|
parts.push(`--flash-attn ${cfg.flashAttn ? "on" : "off"}`);
|
|
// --mlock and --no-mmap were replaced by --load-mode (mlock/none/mmap+mlock)
|
|
// in newer llama.cpp builds. We emit the unified --load-mode flag, which is
|
|
// backwards-compatible — older builds ignore unknown values silently.
|
|
if (cfg.mlock && cfg.noMmap) {
|
|
// mlock the file after loading to RAM (no mmap)
|
|
parts.push("--load-mode mlock");
|
|
} else if (cfg.mlock) {
|
|
// mmap + mlock (default mmap, but also keep in RAM)
|
|
parts.push("--load-mode mmap+mlock");
|
|
} else if (cfg.noMmap) {
|
|
// no mmap at all
|
|
parts.push("--load-mode none");
|
|
}
|
|
// --cont-batching is enabled by default in modern llama.cpp. Only emit
|
|
// --no-cont-batching if the user explicitly disabled it.
|
|
if (!cfg.contBatching) parts.push("--no-cont-batching");
|
|
if (cfg.embeddings) parts.push("--embeddings");
|
|
if (cfg.metrics) parts.push("--metrics");
|
|
// RoPE / YaRN
|
|
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}`);
|
|
// Speculative decoding
|
|
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}`);
|
|
}
|
|
}
|
|
// Default sampling (server applies these as defaults for /completion)
|
|
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}`);
|
|
// Max tokens per response (default -1 = infinity)
|
|
if (cfg.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
|
|
// Reasoning format for thinking models (Qwen3, DeepSeek-R1, gpt-oss)
|
|
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
|
|
// Jinja chat templates (required for reasoning format to work properly)
|
|
if (cfg.jinja) parts.push("--jinja");
|
|
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");
|
|
|
|
// Invalidate the in-memory .env cache so the next composeEnv() call picks
|
|
// up the new values.
|
|
_envCache = null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 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
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* 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<string | null> {
|
|
// 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<string, string> = {}): 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<string, string> = {}
|
|
): 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<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);
|
|
|
|
// 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<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 /health returns "ok" / "loading model" / "error".
|
|
//
|
|
// We use Node's native fetch() to call http://llama:8080 directly — the
|
|
// dashboard container is on the same Docker network as llama, so this
|
|
// works without exec'ing into the llama container.
|
|
//
|
|
// (Previous impl used `docker exec ... wget -qO-` — but the llama.cpp
|
|
// server-cuda image doesn't include wget, causing "executable file not
|
|
// found in $PATH" errors.)
|
|
try {
|
|
const res = await fetch("http://llama:8080/health", {
|
|
signal: AbortSignal.timeout(3000),
|
|
});
|
|
const text = await res.text();
|
|
if (res.ok && text.includes("ok")) {
|
|
return { reachable: true, detail: text.trim() };
|
|
}
|
|
return {
|
|
reachable: false,
|
|
detail: `HTTP ${res.status}: ${text.trim().slice(0, 200)}`,
|
|
};
|
|
} 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<Record<ServiceRole, string>> = {
|
|
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 <svc>` 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<StartResult> {
|
|
const profile = COMPOSE_PROFILES[role];
|
|
const args = ["up", "-d", "--force-recreate", role];
|
|
if (profile) args.unshift("--profile", profile);
|
|
|
|
// Service-specific env overrides. Mirrors what gpuctl shells do — they
|
|
// explicitly export these vars before `docker compose` so compose's
|
|
// ${VAR:-default} syntax picks the real host path instead of the relative
|
|
// default (which would resolve to a path inside the dashboard container,
|
|
// not on the host).
|
|
const extra: Record<string, string> = {};
|
|
if (role === "comfyui") {
|
|
// These mirror `ssh/scripts/comfy.sh`:
|
|
// COMFY_BASE_HOST="$HOST_PROJECT_PATH/gpu/comfy"
|
|
// COMFY_RUN_HOST="$HOST_PROJECT_PATH/comfyui/run"
|
|
extra.COMFY_BASE_HOST = `${HOST_PROJECT_PATH}/gpu/comfy`;
|
|
extra.COMFY_RUN_HOST = `${HOST_PROJECT_PATH}/comfyui/run`;
|
|
}
|
|
|
|
const res = await runCompose(args, extra);
|
|
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<StartResult> {
|
|
// 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<StartResult> {
|
|
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<StartResult> {
|
|
// 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<string | null> {
|
|
// 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<string> {
|
|
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<string[]> {
|
|
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<ComfyModelEntry[]> {
|
|
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(
|
|
rawUrl: string,
|
|
type: string
|
|
): Promise<{
|
|
ok: boolean;
|
|
output: string;
|
|
error?: string;
|
|
originalUrl?: string;
|
|
transformedUrl?: string;
|
|
urlNote?: string;
|
|
}> {
|
|
// Apply CivitAI URL transformation (model page → API download URL, append token).
|
|
// We lazy-load the imports here so docker.ts doesn't pull in downloads.ts at
|
|
// module-load time (avoids circular import concerns).
|
|
const { prepareCivitaiUrl, loadSettings } = await import("./downloads");
|
|
const settings = await loadSettings();
|
|
const { url, note } = prepareCivitaiUrl(rawUrl, settings.civitaiToken || "");
|
|
|
|
const res = await modelWorkerExec("add", url, type);
|
|
return {
|
|
ok: res.ok,
|
|
output: res.output,
|
|
error: res.error,
|
|
// Only include transformation metadata if we actually changed something
|
|
originalUrl: rawUrl !== url ? rawUrl : undefined,
|
|
transformedUrl: rawUrl !== url ? url : undefined,
|
|
urlNote: note || undefined,
|
|
};
|
|
}
|
|
|
|
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<StartResult> {
|
|
// 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<StartResult> {
|
|
// 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<StartResult> {
|
|
// 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 };
|
|
}
|
|
}
|