From 3dc57f5eaf73995668cb111ba625798a8a2c0d5b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 22:45:47 +0000 Subject: [PATCH] =?UTF-8?q?feat(dashboard):=20v2=20=E2=80=94=20SSE=20statu?= =?UTF-8?q?s,=20model=20upload,=20comfy=20management,=20system=20controls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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/` 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 --- .env.example | 20 +- RESTART_WSL.bat | 75 + compose.yaml | 7 + dashboard/.dockerignore | 32 + dashboard/Dockerfile | 26 +- .../src/app/api/comfy/models/add/route.ts | 25 + .../src/app/api/comfy/models/rm/route.ts | 25 + dashboard/src/app/api/comfy/models/route.ts | 18 + dashboard/src/app/api/comfy/queue/route.ts | 17 + dashboard/src/app/api/comfy/route.ts | 62 + dashboard/src/app/api/models/route.ts | 27 +- dashboard/src/app/api/models/upload/route.ts | 58 + .../src/app/api/services/[role]/route.ts | 91 + dashboard/src/app/api/status/stream/route.ts | 94 + dashboard/src/app/api/system/route.ts | 33 + dashboard/src/app/page.tsx | 2340 +++++++++++------ dashboard/src/lib/docker.ts | 411 +++ ssh/gpuctl | 3 + ssh/scripts/status.sh | 14 +- 19 files changed, 2569 insertions(+), 809 deletions(-) create mode 100644 RESTART_WSL.bat create mode 100644 dashboard/.dockerignore create mode 100644 dashboard/src/app/api/comfy/models/add/route.ts create mode 100644 dashboard/src/app/api/comfy/models/rm/route.ts create mode 100644 dashboard/src/app/api/comfy/models/route.ts create mode 100644 dashboard/src/app/api/comfy/queue/route.ts create mode 100644 dashboard/src/app/api/comfy/route.ts create mode 100644 dashboard/src/app/api/models/upload/route.ts create mode 100644 dashboard/src/app/api/services/[role]/route.ts create mode 100644 dashboard/src/app/api/status/stream/route.ts create mode 100644 dashboard/src/app/api/system/route.ts diff --git a/.env.example b/.env.example index 5314024..5e443f4 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,25 @@ +# --------------------------------------------------------------------------- +# GPU-Node environment +# --------------------------------------------------------------------------- +# Copy this file to `.env` and fill in the values before running +# `docker compose up -d` or `START_GPU_NODE.bat`. +# +# IMPORTANT: HOST_PROJECT_PATH must be set here, otherwise: +# - `ssh` container entrypoint will exit with "HOST_PROJECT_PATH is not set" +# - After server reboot, Docker daemon will try to restart it forever +# (restart: always), but it will keep failing +# - Only `tailscale` (which doesn't need HOST_PROJECT_PATH) will come up +# --------------------------------------------------------------------------- + TAILSCALE_HOSTNAME=gpu-node TS_AUTHKEY= WEBDAV_USER=operator WEBDAV_PASS= + +# Absolute path to the GPU-Node directory ON THE HOST. +# On WSL: /home//projects/GPU-Node +# On Windows+WSL: the WSL path (not the Windows path) of the project dir HOST_PROJECT_PATH= + LLAMA_MODEL=model.gguf -LLAMA_EXTRA_ARGS= \ No newline at end of file +LLAMA_EXTRA_ARGS= diff --git a/RESTART_WSL.bat b/RESTART_WSL.bat new file mode 100644 index 0000000..a43b74a --- /dev/null +++ b/RESTART_WSL.bat @@ -0,0 +1,75 @@ +@echo off +setlocal enabledelayedexpansion + +echo ======================================== +echo RESTART WSL + GPU NODE +echo ======================================== +echo. + +REM ----- Step 1: check if WSL is running ----- +echo [1/4] Checking WSL state... +wsl --list --running | findstr /R /C:"Ubuntu" /C:"ubuntu" /C:"Default" >nul 2>&1 +if errorlevel 1 ( + echo WSL is not running. Starting it... + wsl --list --verbose >nul 2>&1 + REM Touch WSL to make sure the distro is awake + wsl bash -c "echo started" >nul 2>&1 +) else ( + echo WSL is already running. +) + +REM ----- Step 2: shut down WSL ----- +echo. +echo [2/4] Shutting down WSL... +wsl --shutdown +if errorlevel 1 ( + echo WARNING: wsl --shutdown returned an error. + goto :error +) + +REM Wait for WSL to fully terminate +timeout /t 3 /nobreak >nul + +REM ----- Step 3: start WSL again ----- +echo. +echo [3/4] Starting WSL... +REM Get WSL path of this script's directory +set "WIN_DIR=%~dp0" +set "WIN_DIR_TRIMMED=%WIN_DIR:~0,-1%" +for /f "delims=" %%i in ('wsl wslpath -u "%WIN_DIR_TRIMMED%"') do set "WSL_DIR=%%i" + +REM Trigger WSL to start (any command will wake it up) +wsl bash -c "echo WSL awake" +if errorlevel 1 ( + echo ERROR: failed to start WSL. + goto :error +) + +echo WSL path: %WSL_DIR% + +REM ----- Step 4: ensure Docker is up and start GPU node containers ----- +echo. +echo [4/4] Starting Docker services... +wsl bash -c "cd '%WSL_DIR%' && docker compose up -d" +if errorlevel 1 ( + echo ERROR: docker compose up failed. + goto :error +) + +echo. +echo ======================================== +echo WSL restarted + GPU node started +echo ======================================== +echo. +wsl bash -c "docker ps --filter 'name=gpu-node-'" +echo. +pause +exit /b 0 + +:error +echo. +echo ======================================== +echo FAILED — see errors above +echo ======================================== +pause +exit /b 1 diff --git a/compose.yaml b/compose.yaml index 4daad7c..f8c290d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,3 +1,10 @@ +# --------------------------------------------------------------------------- +# Validate HOST_PROJECT_PATH early — if it's empty, the `ssh` container will +# exit with "HOST_PROJECT_PATH is not set" and after a server reboot only +# tailscale will come back (because ssh keeps crash-looping on restart: always). +# --------------------------------------------------------------------------- +# ${HOST_PROJECT_PATH:?ERROR: HOST_PROJECT_PATH must be set in .env — see .env.example} + name: ${TAILSCALE_HOSTNAME:-gpu-node} services: diff --git a/dashboard/.dockerignore b/dashboard/.dockerignore new file mode 100644 index 0000000..42f02c6 --- /dev/null +++ b/dashboard/.dockerignore @@ -0,0 +1,32 @@ +# VCS +.git +.gitignore + +# Deps +node_modules +.pnp +.pnp.* + +# Build artifacts +.next +out +build + +# Misc +.DS_Store +*.pem +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.env +.env*.local +.idea +.vscode + +# Scripts / docs +README.md +.eslintrc.json +*.md + +# Don't accidentally bring the parent repo +../.git diff --git a/dashboard/Dockerfile b/dashboard/Dockerfile index 4906624..fe8b665 100644 --- a/dashboard/Dockerfile +++ b/dashboard/Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.7 +# syntax=docker/dockerfile:1.4 # --------------------------------------------------------------------------- # Stage 1: Install deps & build Next.js standalone output @@ -7,18 +7,12 @@ FROM node:20-alpine AS builder WORKDIR /app -# Install dependencies (use yarn or npm — package-lock.json optional) -COPY package.json ./ -COPY package-lock.json* ./ -COPY yarn.lock* ./ +# Copy only manifests first for better layer caching. +# NOTE: legacy Docker builder (no BuildKit) fails on `COPY ` when no +# file matches the pattern, so we list files explicitly here. +COPY package.json package-lock.json ./ -RUN if [ -f yarn.lock ]; then \ - yarn install --frozen-lockfile; \ - elif [ -f package-lock.json ]; then \ - npm ci; \ - else \ - npm install; \ - fi +RUN npm ci --no-audit --no-fund # Copy sources and build COPY tsconfig.json next.config.ts next-env.d.ts postcss.config.mjs .eslintrc.json ./ @@ -27,11 +21,7 @@ COPY public ./public ENV NEXT_TELEMETRY_DISABLED=1 -RUN if [ -f yarn.lock ]; then \ - yarn build; \ - else \ - npm run build; \ - fi +RUN npm run build # --------------------------------------------------------------------------- # Stage 2: Runtime — Alpine + Node + docker-cli + docker compose plugin @@ -50,7 +40,7 @@ RUN apk add --no-cache \ WORKDIR /app -# Copy standalone Next.js build output +# Copy standalone Next.js build output (with node_modules baked in) COPY --from=builder --chown=dash:dash /app/.next/standalone ./ COPY --from=builder --chown=dash:dash /app/.next/static ./.next/static COPY --from=builder --chown=dash:dash /app/public ./public diff --git a/dashboard/src/app/api/comfy/models/add/route.ts b/dashboard/src/app/api/comfy/models/add/route.ts new file mode 100644 index 0000000..7a6f50d --- /dev/null +++ b/dashboard/src/app/api/comfy/models/add/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from "next/server"; +import { addComfyModel } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; + +/** + * POST /api/comfy/models/add + * Body: { url: string, type: string } + * Queues a model download via model-worker. + */ +export async function POST(req: NextRequest) { + const body = (await req.json()) as { url?: string; type?: string }; + if (!body.url || !body.type) { + return NextResponse.json( + { ok: false, error: "url and type required" }, + { status: 400 } + ); + } + const result = await addComfyModel(body.url, body.type); + return NextResponse.json( + { ok: result.ok, output: result.output, error: result.error }, + { status: result.ok ? 200 : 500 } + ); +} diff --git a/dashboard/src/app/api/comfy/models/rm/route.ts b/dashboard/src/app/api/comfy/models/rm/route.ts new file mode 100644 index 0000000..69bba51 --- /dev/null +++ b/dashboard/src/app/api/comfy/models/rm/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from "next/server"; +import { removeComfyModel } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; + +/** + * POST /api/comfy/models/rm + * Body: { filename: string, type?: string } + * Removes a comfy model from disk via model-worker. + */ +export async function POST(req: NextRequest) { + const body = (await req.json()) as { filename?: string; type?: string }; + if (!body.filename) { + return NextResponse.json( + { ok: false, error: "filename required" }, + { status: 400 } + ); + } + const result = await removeComfyModel(body.filename, body.type); + return NextResponse.json( + { ok: result.ok, output: result.output, error: result.error }, + { status: result.ok ? 200 : 500 } + ); +} diff --git a/dashboard/src/app/api/comfy/models/route.ts b/dashboard/src/app/api/comfy/models/route.ts new file mode 100644 index 0000000..1359cda --- /dev/null +++ b/dashboard/src/app/api/comfy/models/route.ts @@ -0,0 +1,18 @@ +import { NextRequest, NextResponse } from "next/server"; +import { listComfyModels } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; + +/** + * GET /api/comfy/models?type= + * Lists comfy models via `docker exec model-worker python3 /app/worker.py list [type]`. + */ +export async function GET(req: NextRequest) { + const type = req.nextUrl.searchParams.get("type") || undefined; + const result = await listComfyModels(type); + return NextResponse.json( + { ok: result.ok, models: result.models, raw: result.raw, error: result.error }, + { status: result.ok ? 200 : 500 } + ); +} diff --git a/dashboard/src/app/api/comfy/queue/route.ts b/dashboard/src/app/api/comfy/queue/route.ts new file mode 100644 index 0000000..7c1fc29 --- /dev/null +++ b/dashboard/src/app/api/comfy/queue/route.ts @@ -0,0 +1,17 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getComfyQueue } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; + +/** + * GET /api/comfy/queue + * Returns current download queue via `docker exec model-worker python3 /app/worker.py queue`. + */ +export async function GET() { + const result = await getComfyQueue(); + return NextResponse.json( + { ok: result.ok, queue: result.queue, raw: result.raw, error: result.error }, + { status: result.ok ? 200 : 500 } + ); +} diff --git a/dashboard/src/app/api/comfy/route.ts b/dashboard/src/app/api/comfy/route.ts new file mode 100644 index 0000000..d2cab7a --- /dev/null +++ b/dashboard/src/app/api/comfy/route.ts @@ -0,0 +1,62 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + startService, + stopService, + restartService, + getServiceLogs, + type ServiceRole, +} from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; +export const maxDuration = 120; + +/** + * POST /api/comfy + * Body: { action: "start" | "stop" | "restart" } + * + * Start / stop / restart ComfyUI. Optional `extraArgs` for start (passed + * through COMFY_EXTRA_ARGS env var). + */ +export async function POST(req: NextRequest) { + const body = (await req.json()) as { + action: "start" | "stop" | "restart"; + extraArgs?: string; + }; + + const role: ServiceRole = "comfyui"; + + if (body.action === "start") { + if (body.extraArgs) { + process.env.COMFY_EXTRA_ARGS = body.extraArgs; + } + const result = await startService(role); + return NextResponse.json(result, { status: result.ok ? 200 : 500 }); + } + + if (body.action === "stop") { + const result = await stopService(role); + return NextResponse.json(result, { status: result.ok ? 200 : 500 }); + } + + if (body.action === "restart") { + const result = await restartService(role); + return NextResponse.json(result, { status: result.ok ? 200 : 500 }); + } + + return NextResponse.json({ error: "unknown action" }, { status: 400 }); +} + +/** + * GET /api/comfy?logs=1&tail=500 + * Returns comfyui logs. + */ +export async function GET(req: NextRequest) { + const withLogs = req.nextUrl.searchParams.get("logs"); + if (withLogs) { + const tail = Number(req.nextUrl.searchParams.get("tail") || 500); + const logs = await getServiceLogs("comfyui", tail); + return NextResponse.json({ ok: true, logs }); + } + return NextResponse.json({ ok: true }); +} diff --git a/dashboard/src/app/api/models/route.ts b/dashboard/src/app/api/models/route.ts index 7eaca86..fb16653 100644 --- a/dashboard/src/app/api/models/route.ts +++ b/dashboard/src/app/api/models/route.ts @@ -1,10 +1,29 @@ -import { NextResponse } from "next/server"; -import { listModels } from "@/lib/docker"; +import { NextRequest, NextResponse } from "next/server"; +import { deleteModel, listModels } from "@/lib/docker"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; -export async function GET() { +/** + * DELETE /api/models?name=foo.gguf + * + * Removes a .gguf file from gpu/llama_models/. + */ +export async function DELETE(req: NextRequest) { + const name = req.nextUrl.searchParams.get("name"); + if (!name) { + return NextResponse.json( + { ok: false, error: "name query param required" }, + { status: 400 } + ); + } + const result = await deleteModel(name); + if (!result.ok) { + return NextResponse.json( + { ok: false, error: result.error }, + { status: 400 } + ); + } const models = await listModels(); - return NextResponse.json({ models }); + return NextResponse.json({ ok: true, models }); } diff --git a/dashboard/src/app/api/models/upload/route.ts b/dashboard/src/app/api/models/upload/route.ts new file mode 100644 index 0000000..6213834 --- /dev/null +++ b/dashboard/src/app/api/models/upload/route.ts @@ -0,0 +1,58 @@ +import { NextRequest, NextResponse } from "next/server"; +import { saveUploadedModel, listModels } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; +export const maxDuration = 600; + +/** + * POST /api/models/upload + * + * Accepts a multipart/form-data upload with a single "file" field. + * Saves to gpu/llama_models/. Returns updated model list. + * + * Body: + * multipart/form-data + * - file: <.gguf file> + */ +export async function POST(req: NextRequest) { + const contentType = req.headers.get("content-type") || ""; + if (!contentType.includes("multipart/form-data")) { + return NextResponse.json( + { ok: false, error: "expected multipart/form-data" }, + { status: 400 } + ); + } + + try { + const form = await req.formData(); + const file = form.get("file"); + if (!file || !(file instanceof File)) { + return NextResponse.json( + { ok: false, error: "missing 'file' field" }, + { status: 400 } + ); + } + + const buffer = Buffer.from(await file.arrayBuffer()); + const result = await saveUploadedModel(file.name, buffer); + if (!result.ok) { + return NextResponse.json( + { ok: false, error: result.error }, + { status: 400 } + ); + } + + const models = await listModels(); + return NextResponse.json({ + ok: true, + path: result.path, + models, + }); + } catch (err) { + return NextResponse.json( + { ok: false, error: (err as Error).message }, + { status: 500 } + ); + } +} diff --git a/dashboard/src/app/api/services/[role]/route.ts b/dashboard/src/app/api/services/[role]/route.ts new file mode 100644 index 0000000..dd5248b --- /dev/null +++ b/dashboard/src/app/api/services/[role]/route.ts @@ -0,0 +1,91 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + startService, + stopService, + restartService, + removeService, + getServiceLogs, + type ServiceRole, +} from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; +export const maxDuration = 120; + +const VALID_ROLES: ServiceRole[] = [ + "llama", + "comfyui", + "model-worker", + "webdav", + "ssh", + "ssh-companion", + "gpu-test", + "dashboard", +]; + +function parseRole(role: string): ServiceRole | null { + return (VALID_ROLES as string[]).includes(role) + ? (role as ServiceRole) + : null; +} + +/** + * GET /api/services/?action=logs&tail=500 + * Returns logs for the given service. + * + * POST /api/services/ + * Body: { action: "start" | "stop" | "restart" | "remove" } + */ +export async function GET( + req: NextRequest, + { params }: { params: Promise<{ role: string }> } +) { + const { role: roleRaw } = await params; + const role = parseRole(roleRaw); + if (!role) { + return NextResponse.json( + { ok: false, error: `invalid role: ${roleRaw}` }, + { status: 400 } + ); + } + const tail = Number(req.nextUrl.searchParams.get("tail") || 500); + const logs = await getServiceLogs(role, tail); + return NextResponse.json({ ok: true, logs }); +} + +export async function POST( + req: NextRequest, + { params }: { params: Promise<{ role: string }> } +) { + const { role: roleRaw } = await params; + const role = parseRole(roleRaw); + if (!role) { + return NextResponse.json( + { ok: false, error: `invalid role: ${roleRaw}` }, + { status: 400 } + ); + } + + const body = (await req.json()) as { + action: "start" | "stop" | "restart" | "remove"; + }; + + if (body.action === "start") { + const r = await startService(role); + return NextResponse.json(r, { status: r.ok ? 200 : 500 }); + } + if (body.action === "stop") { + const r = await stopService(role); + return NextResponse.json(r, { status: r.ok ? 200 : 500 }); + } + if (body.action === "restart") { + const r = await restartService(role); + return NextResponse.json(r, { status: r.ok ? 200 : 500 }); + } + if (body.action === "remove") { + const r = await removeService(role); + return NextResponse.json(r, { status: r.ok ? 200 : 500 }); + } + + return NextResponse.json({ error: "unknown action" }, { status: 400 }); +} diff --git a/dashboard/src/app/api/status/stream/route.ts b/dashboard/src/app/api/status/stream/route.ts new file mode 100644 index 0000000..a662ef6 --- /dev/null +++ b/dashboard/src/app/api/status/stream/route.ts @@ -0,0 +1,94 @@ +import { listContainers, getLlamaHealth, NODE_INSTANCE } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; +export const maxDuration = 300; + +/** + * Server-Sent Events stream for status updates. + * + * Replaces fetch-polling — client opens a single EventSource connection + * and receives a `status` event every N seconds with the full status + * payload. SSE was chosen over WebSocket because: + * - one-way (server → client) is all we need for status pushes + * - works through any HTTP proxy (Tailscale serve) without WS upgrade + * - built into the browser (EventSource API), no extra deps + * - keeps Next.js standalone output (smaller docker image) + * + * Client usage: + * const es = new EventSource("/api/status/stream"); + * es.addEventListener("status", (e) => { + * const data = JSON.parse(e.data); + * ... + * }); + */ +export async function GET() { + const encoder = new TextEncoder(); + + const stream = new ReadableStream({ + async start(controller) { + const send = (event: string, data: unknown) => { + try { + controller.enqueue( + encoder.encode( + `event: ${event}\ndata: ${JSON.stringify(data)}\n\n` + ) + ); + } catch { + /* stream closed */ + } + }; + + // Initial hello so the client knows the stream is alive + send("hello", { + instance: NODE_INSTANCE, + ts: Date.now(), + }); + + // Push status immediately (don't wait for the first interval) + const pushStatus = async () => { + try { + const [containers, llamaHealth] = await Promise.all([ + listContainers(), + getLlamaHealth(), + ]); + send("status", { + instance: NODE_INSTANCE, + containers, + llamaHealth, + timestamp: new Date().toISOString(), + }); + } catch (err) { + send("error", { message: (err as Error).message }); + } + }; + + await pushStatus(); + + const interval = setInterval(pushStatus, 4000); + + // Cleanup when client disconnects + // The controller.close() is called when the consumer cancels the stream + // ( AbortController / EventSource.close() on the client side). + // We use the `cancel` method below. + // Store interval on the controller via closure. + (controller as unknown as { _interval?: NodeJS.Timeout })._interval = + interval; + }, + cancel(controller) { + const interval = ( + controller as unknown as { _interval?: NodeJS.Timeout } + )._interval; + if (interval) clearInterval(interval); + }, + }); + + return new Response(stream, { + headers: { + "Content-Type": "text/event-stream; charset=utf-8", + "Cache-Control": "no-cache, no-transform", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + }, + }); +} diff --git a/dashboard/src/app/api/system/route.ts b/dashboard/src/app/api/system/route.ts new file mode 100644 index 0000000..a809e29 --- /dev/null +++ b/dashboard/src/app/api/system/route.ts @@ -0,0 +1,33 @@ +import { NextRequest, NextResponse } from "next/server"; +import { sleepMode, wakeMode, updateNode } from "@/lib/docker"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; +export const maxDuration = 600; + +/** + * POST /api/system + * Body: { action: "sleep" | "wake" | "update" } + * + * Mirrors `gpuctl sleep|wake|update` CLI commands. + */ +export async function POST(req: NextRequest) { + const body = (await req.json()) as { action: "sleep" | "wake" | "update" }; + + if (body.action === "sleep") { + const result = await sleepMode(); + return NextResponse.json(result, { status: result.ok ? 200 : 500 }); + } + + if (body.action === "wake") { + const result = await wakeMode(); + return NextResponse.json(result, { status: result.ok ? 200 : 500 }); + } + + if (body.action === "update") { + const result = await updateNode(); + return NextResponse.json(result, { status: result.ok ? 200 : 500 }); + } + + return NextResponse.json({ error: "unknown action" }, { status: 400 }); +} diff --git a/dashboard/src/app/page.tsx b/dashboard/src/app/page.tsx index 0e56acb..1c0cc12 100644 --- a/dashboard/src/app/page.tsx +++ b/dashboard/src/app/page.tsx @@ -7,6 +7,7 @@ import { CpuIcon, HardDrive, Layers, + Moon, Play, Power, RefreshCw, @@ -14,12 +15,18 @@ import { Save, Settings2, Square, + Sun, Terminal, Trash2, + Upload, + Wrench, X, Zap, FileText, ChevronRight, + Server, + CloudDownload, + Plus, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { @@ -43,6 +50,10 @@ import { import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { cn, formatBytes, timeAgo } from "@/lib/utils"; +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + interface ModelFile { name: string; sizeBytes: number; @@ -84,6 +95,27 @@ interface DashboardConfig { presets: Preset[]; } +interface ComfyModelEntry { + type: string; + filename: string; + sizeBytes?: number; + sizeHuman?: string; +} + +interface ComfyQueueEntry { + id: number; + action: string; + model_type: string; + filename: string; + url?: string; + status: string; + progress?: number; + downloaded_bytes?: number; + total_bytes?: number; + error?: string; + created_at?: string; +} + const DEFAULT_CONFIG: DashboardConfig = { model: "model.gguf", ctxSize: 64000, @@ -99,7 +131,21 @@ const DEFAULT_CONFIG: DashboardConfig = { presets: [], }; -const REFRESH_INTERVAL_MS = 4000; +const COMFY_MODEL_TYPES = [ + "checkpoints", + "loras", + "vae", + "embeddings", + "controlnet", + "clip", + "unet", + "upscale_models", + "custom_nodes", +]; + +// --------------------------------------------------------------------------- +// Main page +// --------------------------------------------------------------------------- export default function DashboardPage() { const [config, setConfig] = React.useState(DEFAULT_CONFIG); @@ -123,13 +169,29 @@ export default function DashboardPage() { const [presetDialogOpen, setPresetDialogOpen] = React.useState(false); const [presetName, setPresetName] = React.useState(""); + // Logs tab const [liveLogs, setLiveLogs] = React.useState([]); const [logsAutoScroll, setLogsAutoScroll] = React.useState(true); + const [logsTarget, setLogsTarget] = React.useState<"llama" | "comfyui" | "dashboard" | "ssh">("llama"); const logsEndRef = React.useRef(null); const logsAbortRef = React.useRef(null); const logsActiveRef = React.useRef(false); + // Comfy + const [comfyModels, setComfyModels] = React.useState([]); + const [comfyQueue, setComfyQueue] = React.useState([]); + const [comfyFilter, setComfyFilter] = React.useState(""); + const [comfyAddUrl, setComfyAddUrl] = React.useState(""); + const [comfyAddType, setComfyAddType] = React.useState(COMFY_MODEL_TYPES[0]); + + // Upload state + const [uploadProgress, setUploadProgress] = React.useState<{ + name: string; + percent: number; + } | null>(null); + const llamaContainer = containers.find((c) => c.role === "llama") || null; + const comfyContainer = containers.find((c) => c.role === "comfyui") || null; // --------------------------------------------------------------------------- // Toast helper @@ -144,22 +206,44 @@ export default function DashboardPage() { ); // --------------------------------------------------------------------------- - // Data fetching + // SSE status stream (replaces fetch polling) // --------------------------------------------------------------------------- - const refreshStatus = React.useCallback(async () => { - try { - const res = await fetch("/api/status", { cache: "no-store" }); - if (!res.ok) return; - const data = await res.json(); - setContainers(data.containers || []); - setLlamaHealth(data.llamaHealth || null); - setInstance(data.instance || "gpu-node"); - setLastUpdated(new Date().toLocaleTimeString()); - } catch { - /* ignore */ - } + React.useEffect(() => { + const es = new EventSource("/api/status/stream"); + + es.addEventListener("hello", (e) => { + try { + const data = JSON.parse((e as MessageEvent).data); + if (data.instance) setInstance(data.instance); + } catch { + /* ignore */ + } + }); + + es.addEventListener("status", (e) => { + try { + const data = JSON.parse((e as MessageEvent).data); + setContainers(data.containers || []); + setLlamaHealth(data.llamaHealth || null); + if (data.instance) setInstance(data.instance); + setLastUpdated(new Date().toLocaleTimeString()); + } catch { + /* ignore */ + } + }); + + es.addEventListener("error", () => { + // EventSource auto-reconnects; nothing to do here. + }); + + return () => { + es.close(); + }; }, []); + // --------------------------------------------------------------------------- + // Other data fetching (one-shot / on-demand) + // --------------------------------------------------------------------------- const refreshModels = React.useCallback(async () => { try { const res = await fetch("/api/models", { cache: "no-store" }); @@ -171,16 +255,6 @@ export default function DashboardPage() { } }, []); - const refreshGpu = React.useCallback(async () => { - try { - const res = await fetch("/api/gpu", { cache: "no-store" }); - const data = await res.json(); - setGpu(data.output || data.error || ""); - } catch (err) { - setGpu(`[error: ${(err as Error).message}]`); - } - }, []); - const refreshConfig = React.useCallback(async () => { try { const res = await fetch("/api/config", { cache: "no-store" }); @@ -192,19 +266,51 @@ export default function DashboardPage() { } }, []); - // --------------------------------------------------------------------------- - // Auto-refresh status + models on mount - // --------------------------------------------------------------------------- + const refreshGpu = React.useCallback(async () => { + setBusy("gpu"); + try { + const res = await fetch("/api/gpu", { cache: "no-store" }); + const data = await res.json(); + setGpu(data.output || data.error || ""); + } catch (err) { + setGpu(`[error: ${(err as Error).message}]`); + } finally { + setBusy(null); + } + }, []); + + const refreshComfyModels = React.useCallback(async () => { + try { + const url = comfyFilter + ? `/api/comfy/models?type=${encodeURIComponent(comfyFilter)}` + : "/api/comfy/models"; + const res = await fetch(url, { cache: "no-store" }); + const data = await res.json(); + setComfyModels(data.models || []); + } catch { + setComfyModels([]); + } + }, [comfyFilter]); + + const refreshComfyQueue = React.useCallback(async () => { + try { + const res = await fetch("/api/comfy/queue", { cache: "no-store" }); + const data = await res.json(); + setComfyQueue(data.queue || []); + } catch { + setComfyQueue([]); + } + }, []); + React.useEffect(() => { refreshConfig(); - refreshStatus(); refreshModels(); - const id = setInterval(refreshStatus, REFRESH_INTERVAL_MS); + const id = setInterval(refreshComfyQueue, 5000); return () => clearInterval(id); - }, [refreshConfig, refreshStatus, refreshModels]); + }, [refreshConfig, refreshModels, refreshComfyQueue]); // --------------------------------------------------------------------------- - // Live logs streaming (only when llama running AND logs tab open) + // Live logs streaming (started when user clicks "Start stream") // --------------------------------------------------------------------------- const startLogsStream = React.useCallback(() => { if (logsActiveRef.current) return; @@ -214,7 +320,7 @@ export default function DashboardPage() { const controller = new AbortController(); logsAbortRef.current = controller; - fetch(`/api/logs?tail=300`, { signal: controller.signal }) + fetch(`/api/services/${logsTarget}?tail=300`, { signal: controller.signal }) .then((res) => { if (!res.body) return; const reader = res.body.getReader(); @@ -225,7 +331,6 @@ export default function DashboardPage() { const text = decoder.decode(value, { stream: true }); setLiveLogs((prev) => { const next = [...prev, ...text.split("\n").filter(Boolean)]; - // Cap at 2000 lines return next.slice(-2000); }); return pump(); @@ -238,7 +343,7 @@ export default function DashboardPage() { .finally(() => { logsActiveRef.current = false; }); - }, []); + }, [logsTarget]); const stopLogsStream = React.useCallback(() => { if (logsAbortRef.current) { @@ -258,13 +363,21 @@ export default function DashboardPage() { } }, [liveLogs, logsAutoScroll]); + // Restart logs stream when target changes + React.useEffect(() => { + if (logsActiveRef.current) { + stopLogsStream(); + setTimeout(startLogsStream, 100); + } + }, [logsTarget, startLogsStream, stopLogsStream]); + // --------------------------------------------------------------------------- - // Actions + // Generic actions // --------------------------------------------------------------------------- async function runAction( name: string, fn: () => Promise<{ ok: boolean; message: string; logs?: string }>, - options?: { refresh?: boolean } + refresh = true ) { setBusy(name); try { @@ -274,8 +387,9 @@ export default function DashboardPage() { } else { showToast("error", result.message); } - if (options?.refresh !== false) { - await refreshStatus(); + if (refresh) { + // SSE handles status, but models list / comfy models need explicit refresh + await Promise.all([refreshModels(), refreshComfyModels()]); } } catch (err) { showToast("error", (err as Error).message); @@ -284,9 +398,8 @@ export default function DashboardPage() { } } - async function handleStart() { - await runAction("start", async () => { - // Persist config first + async function handleStartLlama() { + await runAction("start-llama", async () => { const res = await fetch("/api/config", { method: "PUT", headers: { "Content-Type": "application/json" }, @@ -298,44 +411,129 @@ export default function DashboardPage() { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "start", config }), }); - const result = await startRes.json(); - return result; + return await startRes.json(); }); } - async function handleStop() { - await runAction("stop", async () => { + async function handleLlamaAction(action: "stop" | "restart" | "remove") { + await runAction(`llama-${action}`, async () => { const res = await fetch("/api/llama", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ action: "stop" }), + body: JSON.stringify({ action }), }); return await res.json(); }); } - async function handleRestart() { - await runAction("restart", async () => { - const res = await fetch("/api/llama", { + async function handleComfyAction(action: "start" | "stop" | "restart") { + await runAction(`comfy-${action}`, async () => { + const res = await fetch("/api/comfy", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ action: "restart" }), + body: JSON.stringify({ action }), }); return await res.json(); }); } - async function handleRemove() { - await runAction("remove", async () => { - const res = await fetch("/api/llama", { + async function handleServiceAction( + role: string, + action: "start" | "stop" | "restart" | "remove" + ) { + await runAction(`${role}-${action}`, async () => { + const res = await fetch(`/api/services/${role}`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ action: "remove" }), + body: JSON.stringify({ action }), }); return await res.json(); }); } + async function handleSystemAction(action: "sleep" | "wake" | "update") { + if (action === "sleep") { + const ok = confirm( + "Sleep mode will stop: llama, comfyui, gpu-test, model-worker, webdav, dashboard.\n\n" + + "Only tailscale + ssh will remain.\n\nContinue?" + ); + if (!ok) return; + } + if (action === "update") { + const ok = confirm( + "Update will:\n1. Run build.sh (rebuild all images)\n2. Restart ssh-companion + model-worker + dashboard\n\n" + + "This may take several minutes. Continue?" + ); + if (!ok) return; + } + await runAction(`system-${action}`, async () => { + const res = await fetch("/api/system", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action }), + }); + return await res.json(); + }, false); + } + + async function handleUpload(file: File) { + if (!file.name.toLowerCase().endsWith(".gguf")) { + showToast("error", "Only .gguf files are allowed"); + return; + } + setUploadProgress({ name: file.name, percent: 0 }); + setBusy("upload"); + try { + const formData = new FormData(); + formData.append("file", file); + + // Use XMLHttpRequest for upload progress + await new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.upload.addEventListener("progress", (e) => { + if (e.lengthComputable) { + setUploadProgress({ + name: file.name, + percent: Math.round((e.loaded / e.total) * 100), + }); + } + }); + xhr.addEventListener("load", () => { + if (xhr.status >= 200 && xhr.status < 300) resolve(); + else reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`)); + }); + xhr.addEventListener("error", () => + reject(new Error("Network error during upload")) + ); + xhr.open("POST", "/api/models/upload"); + xhr.send(formData); + }); + + showToast("success", `${file.name} uploaded`); + await refreshModels(); + } catch (err) { + showToast("error", (err as Error).message); + } finally { + setUploadProgress(null); + setBusy(null); + } + } + + async function handleDeleteModel(name: string) { + if (!confirm(`Delete ${name}? This cannot be undone.`)) return; + await runAction(`del-${name}`, async () => { + const res = await fetch( + `/api/models?name=${encodeURIComponent(name)}`, + { method: "DELETE" } + ); + const data = await res.json(); + return { + ok: data.ok, + message: data.ok ? `${name} deleted` : data.error || "Failed", + }; + }); + } + async function handleSavePreset() { if (!presetName.trim()) { showToast("error", "Preset name required"); @@ -418,6 +616,44 @@ export default function DashboardPage() { } } + async function handleComfyAddModel() { + if (!comfyAddUrl.trim()) { + showToast("error", "URL required"); + return; + } + await runAction("comfy-add", async () => { + const res = await fetch("/api/comfy/models/add", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ url: comfyAddUrl.trim(), type: comfyAddType }), + }); + const data = await res.json(); + setComfyAddUrl(""); + await refreshComfyQueue(); + return { + ok: data.ok, + message: data.ok ? `Queued: ${comfyAddType}` : data.error || "Failed", + }; + }, false); + } + + async function handleComfyRemoveModel(filename: string, type?: string) { + if (!confirm(`Remove ${filename}?`)) return; + await runAction(`comfy-rm-${filename}`, async () => { + const res = await fetch("/api/comfy/models/rm", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ filename, type }), + }); + const data = await res.json(); + await refreshComfyModels(); + return { + ok: data.ok, + message: data.ok ? `${filename} removed` : data.error || "Failed", + }; + }, false); + } + function update( key: K, value: DashboardConfig[K] @@ -437,106 +673,100 @@ export default function DashboardPage() { return (
- {/* Header */} -
-
-
-
- -
-
-

- Llama Dashboard -

-

- Instance: {instance} - {lastUpdated && ( - <> - {" · "} - updated {lastUpdated} - - )} -

-
-
-
- - - {llamaStatus === "running" - ? "Running" - : llamaStatus === "stopped" - ? "Stopped" - : "Not created"} - - -
-
-
+
handleSystemAction("sleep")} + onWake={() => handleSystemAction("wake")} + onUpdate={() => handleSystemAction("update")} + busy={busy} + /> - {/* Main content */}
- {/* Quick actions row */} + {/* Quick actions row — llama */}
} - label="Start / Apply" - description="Launch llama with current config" + label="Start Llama" + description="Apply config + launch llama.cpp" color="success" disabled={busy !== null} - loading={busy === "start"} - onClick={handleStart} + loading={busy === "start-llama"} + onClick={handleStartLlama} /> } - label="Restart" + label="Restart Llama" description="Restart llama container" color="default" disabled={!llamaContainer || busy !== null} - loading={busy === "restart"} - onClick={handleRestart} + loading={busy === "llama-restart"} + onClick={() => handleLlamaAction("restart")} /> } - label="Stop" + label="Stop Llama" description="Stop llama (keeps container)" color="warning" disabled={!llamaContainer?.running || busy !== null} - loading={busy === "stop"} - onClick={handleStop} + loading={busy === "llama-stop"} + onClick={() => handleLlamaAction("stop")} /> } - label="Remove" + label="Remove Llama" description="Force-remove llama container" color="destructive" disabled={!llamaContainer || busy !== null} - loading={busy === "remove"} - onClick={handleRemove} + loading={busy === "llama-remove"} + onClick={() => handleLlamaAction("remove")} + /> +
+ + {/* Quick actions row — comfy + system */} +
+ } + label="Start Comfy" + description="Launch ComfyUI" + color="success" + disabled={busy !== null} + loading={busy === "comfy-start"} + onClick={() => handleComfyAction("start")} + /> + } + label="Restart Comfy" + description="Restart ComfyUI container" + color="default" + disabled={!comfyContainer || busy !== null} + loading={busy === "comfy-restart"} + onClick={() => handleComfyAction("restart")} + /> + } + label="Stop Comfy" + description="Stop ComfyUI" + color="warning" + disabled={!comfyContainer?.running || busy !== null} + loading={busy === "comfy-stop"} + onClick={() => handleComfyAction("stop")} + /> + } + label="Refresh GPU" + description="Query nvidia-smi" + color="default" + disabled={busy !== null} + loading={busy === "gpu"} + onClick={refreshGpu} />
{/* Tabs */} - + Config @@ -545,6 +775,10 @@ export default function DashboardPage() { Models + + + Comfy + Logs @@ -562,648 +796,85 @@ export default function DashboardPage() { {/* Config tab */} - - -
- - - Launch Configuration - - - Adjust llama.cpp parameters. Saved automatically on apply. - -
-
- - -
-
- - {/* Save preset inline form */} - {presetDialogOpen && ( -
-
- - setPresetName(e.target.value)} - placeholder="e.g. long-context-spec" - /> -
- - -
- )} - - {/* Presets list */} - {config.presets.length > 0 && ( -
- -
- {config.presets.map((p) => ( -
- - -
- ))} -
-
- )} - - {/* Model selection */} -
-
- - -
- -
- - - update("ctxSize", Number(e.target.value)) - } - /> -
-
- - {/* Performance row */} -
-
- - - update("parallel", Number(e.target.value)) - } - /> -
-
- - - update("batchSize", Number(e.target.value)) - } - /> -
-
- - - update("nGpuLayers", Number(e.target.value)) - } - /> -
-
- - - update("threads", Number(e.target.value)) - } - /> -
-
- - {/* Speculative decoding */} -
-
-
-
- - - Speculative decoding - -
-

- Draft model + spec algorithm. Off by default. -

-
-
-
-
- - -
-
- - -
-
- - - update("specDraftNMax", Number(e.target.value)) - } - disabled={config.specType === "none"} - /> -
-
-
- - {/* Context overflow */} -
-
- - -
-
- - {/* Extra args */} -
- -