feat(dashboard): v2 — SSE status, model upload, comfy management, system controls

## Fixes

- **Dockerfile build failure on legacy builder**: removed `COPY yarn.lock*`
  wildcard (legacy builder fails when no file matches). Now uses explicit
  `COPY package.json package-lock.json ./`.
- Added `dashboard/.dockerignore` to exclude node_modules/.next from build
  context (faster builds, smaller context).

## New features

### Real-time status via SSE (replaces fetch polling)
- New `/api/status/stream` endpoint emits `status` event every 4s with
  full containers + llama health payload.
- Frontend opens single `EventSource` connection instead of polling.
  Auto-reconnects on disconnect.
- SSE chosen over WebSocket: one-way push (server→client) is all we need
  for status, works through any HTTP proxy (Tailscale serve), built into
  the browser, no extra deps, keeps Next.js standalone output.

### .gguf model upload
- New `/api/models/upload` (multipart/form-data) saves files to
  `gpu/llama_models/`.
- Drag-and-drop dropzone + click-to-upload in the Models tab.
- Live progress bar via XMLHttpRequest upload progress event.
- New `DELETE /api/models?name=...` removes a model.
- Filename sanitization: only .gguf, no path traversal.

### ComfyUI models management (mirrors `gpuctl comfy models ...`)
- New API routes:
  - `GET /api/comfy/models?type=` — list models via model-worker
  - `GET /api/comfy/queue` — show download queue
  - `POST /api/comfy/models/add` {url, type} — queue download
  - `POST /api/comfy/models/rm` {filename, type?} — remove model
- New Comfy tab with: download queue (live progress), add-model form,
  models table (filter by type, remove button).
- All proxied through `docker exec model-worker python3 /app/worker.py ...`.

### ComfyUI start/stop/restart
- New `POST /api/comfy` {action: start|stop|restart}.
- 4 new quick-action cards on the dashboard home.

### System controls (sleep / wake / update)
- New `POST /api/system` {action: sleep|wake|update}.
- Header buttons (Sleep / Wake / Update) with confirmation dialogs.
- `update` runs `sh build.sh` then `docker compose up -d --force-recreate`.

### Generic service management
- New `/api/services/[role]` route handles start/stop/restart/remove/logs
  for any service: llama, comfyui, model-worker, webdav, ssh,
  ssh-companion, gpu-test, dashboard.
- System tab → Containers table shows per-container action buttons
  (start/restart/stop/remove), tailscale is protected.

### Live logs for any service
- Logs tab now has a target selector (llama / comfyui / dashboard / ssh).
- Uses `/api/services/<role>` streaming endpoint.

## Shell script updates (`gpuctl` integration)

- `ssh/scripts/status.sh`:
  - `sleep_mode()` now also removes the `dashboard` container
  - `wake_mode()` now also starts the `dashboard` container
  - Both `wake_mode()` and `update_ssh()` now pass `--profile wake`
    when starting profile-gated services (this fixes a subtle bug where
    `ssh-companion`/`model-worker`/`webdav`/`dashboard` would fail
    to start without the wake profile flag).
- `ssh/gpuctl` usage text updated to list `dashboard`.

## WSL restart script

- New `RESTART_WSL.bat` next to `START_GPU_NODE.bat`:
  1. Checks if WSL is running, starts it if not
  2. `wsl --shutdown` + 3s wait
  3. Wakes WSL back up
  4. `docker compose up -d` to start GPU node services
  5. Shows running containers

## ssh-only-tailscale-after-reboot investigation

Most likely cause: empty `HOST_PROJECT_PATH` in `.env`.
- `ssh/entrypoint.sh` exits 1 if `HOST_PROJECT_PATH` is unset
- With `restart: always`, Docker daemon keeps trying to restart it on
  every boot, but it crashes immediately each time
- `tailscale` doesn't need this env var, so it starts cleanly

Fix: added a hard fail at the top of `compose.yaml`:
```yaml
# ${HOST_PROJECT_PATH:?ERROR: HOST_PROJECT_PATH must be set in .env}
```
(commented out by default to avoid breaking existing setups; uncomment to
enable fail-fast validation). Also updated `.env.example` with a clear
warning about this gotcha.

Alternative cause (less likely): if `gpuctl sleep` was called before the
reboot, the `ssh` container may have been removed entirely. After reboot,
Docker has no container to restart, so only `tailscale` (which `sleep_mode`
preserves) comes back. Fix: run `docker compose up -d` after reboot to
re-create the ssh container, or just call `gpuctl wake` from the dashboard.

## Files added/changed

- `dashboard/Dockerfile` — fixed COPY commands
- `dashboard/.dockerignore` — new
- `dashboard/src/app/page.tsx` — major rewrite (comfy, sleep/wake, upload, SSE)
- `dashboard/src/app/api/status/stream/route.ts` — new SSE endpoint
- `dashboard/src/app/api/models/route.ts` — added DELETE
- `dashboard/src/app/api/models/upload/route.ts` — new
- `dashboard/src/app/api/comfy/route.ts` — new
- `dashboard/src/app/api/comfy/models/route.ts` — new
- `dashboard/src/app/api/comfy/queue/route.ts` — new
- `dashboard/src/app/api/comfy/models/add/route.ts` — new
- `dashboard/src/app/api/comfy/models/rm/route.ts` — new
- `dashboard/src/app/api/system/route.ts` — new
- `dashboard/src/app/api/services/[role]/route.ts` — new
- `dashboard/src/lib/docker.ts` — added start/stop/restart/remove services,
  comfy models proxy, sleep/wake/update, model upload/delete
- `ssh/scripts/status.sh` — sleep_mode + wake_mode + update_ssh updated
- `ssh/gpuctl` — usage text updated
- `compose.yaml` — added HOST_PROJECT_PATH validation comment
- `.env.example` — added HOST_PROJECT_PATH warning, LLAMA_EXTRA_ARGS
- `RESTART_WSL.bat` — new
This commit is contained in:
Claude
2026-10-23 22:45:47 +00:00
parent 1b2c5e8508
commit 3dc57f5eaf
19 changed files with 2569 additions and 809 deletions

View File

@@ -618,3 +618,414 @@ export async function getLlamaHealth(): Promise<{
};
}
}
// ---------------------------------------------------------------------------
// 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);
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<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 { stdout, stderr } = await execAsync(
`docker exec ${container} python3 /app/worker.py ${quoted}`,
{ 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;
};
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;
}
export async function listComfyModels(
type?: string
): Promise<{ ok: boolean; models: ComfyModelEntry[]; raw: string; error?: string }> {
const args = ["list"];
if (type) args.push(type);
const res = await modelWorkerExec(...args);
if (!res.ok) {
return { ok: false, models: [], raw: res.output, error: res.error };
}
// worker.py outputs JSON; parse it
try {
const parsed = JSON.parse(res.output);
const arr: ComfyModelEntry[] = Array.isArray(parsed)
? parsed
: parsed.models || parsed.items || [];
return { ok: true, models: arr, raw: res.output };
} catch {
// Probably plain text
return { ok: true, models: [], raw: res.output };
}
}
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;
}> {
const res = await modelWorkerExec("queue");
if (!res.ok) return { ok: false, queue: [], raw: res.output, error: res.error };
try {
const parsed = JSON.parse(res.output);
const arr: ComfyQueueEntry[] = Array.isArray(parsed)
? parsed
: parsed.jobs || parsed.queue || [];
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<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 };
}
}