Commit Graph

11 Commits

Author SHA1 Message Date
Z User
cb92e32bdf feat(comfy): CivitAI URL transformation + token support for comfy models
## 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
2026-10-24 02:35:37 +00:00
Z User
664a2f336e fix(dashboard): chat survives tab switch, Enter to send, reasoning display, /health via fetch, n-predict + reasoning-format params
## User-reported issues addressed

### 1. Chat resets when switching tabs
Chat state lived inside `ChatTab` component → lost on unmount when user
switched to Models/Logs/System tabs.

**Fix:** lifted all chat state to the top-level component:
- `chatMessages`, `chatInput`, `chatStreaming`, `chatAutoScroll`
- `chatAbortRef` (for Stop button)
- `chatMessagesEndRef` (auto-scroll anchor)

ChatTab is now a controlled component that receives state + handlers as
props. Switching tabs unmounts the view but state survives.

### 2. Enter to send, Shift+Enter for newline
Was: Ctrl+Enter to send.
Now: Enter (without Shift/Ctrl/Meta/Alt) sends. Shift+Enter inserts a
newline (default textarea behavior).

### 3. Reasoning display (thinking models)
**Why no reasoning shown:** llama.cpp's `--reasoning-format auto` splits
`` blocks into a separate `delta.reasoning_content`
field. We weren't capturing it.

**Fix:**
- Added `--reasoning-format` config field (none/deepthink/auto, default
  `auto`).
- Added `--jinja` toggle (required for reasoning format to work).
- `/api/chat` now passes `reasoning_format` through.
- Frontend `handleChatSend` captures `delta.reasoning_content` and
  stores it in `message.reasoning`.
- MessageBubble shows reasoning as a collapsible block above content
  (▶ Reasoning, click to expand).

### 4. Prefill speed + TTFT in chat stats
**Was:** showed 'Prompt: N tok (Xs, Y tok/s)' on one line, easy to miss.
**Now:** explicit separate stats:
- `TPS:` — generation throughput (predicted_per_second)
- `TTFT:` — Time To First Token = prompt_ms / 1000 (with prompt token
  count in parens)
- `Prefill:` — prompt processing speed (prompt_per_second)
- `Cache hit:` — KV cache reuse rate
- `Spec decoding:` — accepted/drafted + acceptance rate

### 5. Max tokens limit
'У него же нет ограничений в объеме ответа кроме Context size?' — yes
there is: `--n-predict` (default -1 = infinity). Was not exposed.

**Fix:** added `nPredict` field to DashboardConfig (default -1). Sets
`--n-predict` on the server AND `max_tokens` per-request in /api/chat.
UI: input in the Default sampling section of ConfigTab.

### 6. /health 'Unreachable' — wget missing
**Was:** `docker exec ... wget -qO- http://127.0.0.1:8080/health` →
'OCI runtime exec failed: exec: "wget": executable file not found in
/home/z/.venv/bin:/home/z/.venv/bin:/home/z/.npm-global/bin:/home/z/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/bun-node-fallback-bin'. The llama.cpp:server-cuda image doesn't include wget.

**Fix:** `getLlamaHealth()` now uses Node's native `fetch()` to call
`http://llama:8080/health` directly — the dashboard container is on
the same Docker network as llama, so this works without exec'ing into
the llama container. (Same approach we already use for /api/chat and
/api/slots.)

### 7. 'зачем нам отдельно выделять лламму?'
`/api/llama` endpoint (start/stop/restart/remove) is functionally
identical to `/api/services/llama`. Keeping it for backwards compat
with the existing frontend code, but the System tab's per-container
action buttons (▶ ↻ ■ 🗑) already use the generic /api/services route.

## Backend

### `dashboard/src/lib/docker.ts`
- `DashboardConfig`: added `nPredict`, `reasoningFormat`, `jinja`
- `DEFAULT_CONFIG`: nPredict=-1, reasoningFormat='auto', jinja=true
- `buildLlamaExtraArgs()`: emits `--n-predict` (if >=0),
  `--reasoning-format <value>`, `--jinja` (if true)
- `parseLlamaExtraArgs()`: parses `--n-predict`/`--predict`/`-n`,
  `--reasoning-format`, `--jinja`. Added `isValue()` helper.
- `getLlamaHealth()`: rewrote to use fetch() instead of docker exec wget

### `dashboard/src/app/api/config/route.ts`
- `mergeConfig()` includes the 3 new fields

### `dashboard/src/app/api/chat/route.ts`
- Removed unused `spawn` import and the misleading wget comment
- Accepts `reasoning_format` in body, passes through to llama.cpp
- Sets `stream_options: { include_usage: true }` so timings come back
  in the final chunk

## Frontend

### `dashboard/src/app/page.tsx`
- Lifted chat state (chatMessages, chatInput, chatStreaming, chatAutoScroll,
  chatAbortRef, chatMessagesEndRef) to the top-level component
- ChatTab is now a controlled component (state + handlers as props)
- Enter key sends (Shift+Enter for newline)
- `handleChatSend()` captures `delta.reasoning_content` → message.reasoning
- MessageBubble: collapsible Reasoning block (▶ / ▼)
- MessageStats: explicit TPS / TTFT / Prefill / Cache hit / Spec decoding
- `DashboardConfig` interface + DEFAULT_CONFIG + buildPreviewArgs all
  include the 3 new fields
- ConfigTab 'Default sampling' section: added n-predict input,
  reasoning-format select, jinja toggle

## 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
```

Then:
1. Open Config tab → Default sampling → set Reasoning format to 'auto'
   (should be default), Jinja ON (should be default)
2. Start Llama
3. Open Chat tab → send a message to a thinking model (Qwen3, DeepSeek-R1)
   → see reasoning block above the response
4. Switch to Models tab and back → chat is preserved
5. Press Enter → sends. Shift+Enter → newline
6. Check System tab → Llama /health should show OK (no more wget error)

## Files changed

- dashboard/src/lib/docker.ts — new config fields + getLlamaHealth via fetch
- dashboard/src/app/api/config/route.ts — mergeConfig new fields
- dashboard/src/app/api/chat/route.ts — reasoning_format passthrough,
  stream_options.include_usage, removed wget cruft
- dashboard/src/app/page.tsx — lifted chat state, Enter-to-send,
  reasoning display, TTFT/Prefill stats, new config fields + UI
2026-10-24 02:16:45 +00:00
Z User
38d8d55c21 fix(dashboard): llama.cpp CLI arg changes — flash-attn value, load-mode, no-cont-batching
## Problem

llama.cpp latest (ghcr.io/ggml-org/llama.cpp:server-cuda) changed several CLI
flags, breaking llama launch from the dashboard:

  error while handling argument "--flash-attn": error: unknown value for
  --flash-attn: '--cont-batching'

  usage:
  -fa,   --flash-attn [on|off|auto]  set Flash Attention use ('on', 'off', or
                                       'auto', default: 'auto')

The dashboard was emitting bare flags like `--flash-attn` and the next
token (`--cont-batching`) was being consumed as the value, causing a parse
error.

## Changes in llama.cpp server

After checking the latest llama.cpp/tools/server/README.md and manpage:

- `--flash-attn` → now takes a value: `[on|off|auto]`. Bare flag fails.
- `--mlock` and `--no-mmap` → deprecated, replaced by unified
  `--load-mode {auto|none|mmap|mlock|mmap+mlock|dio}`.
- `--cont-batching` → enabled by default; disable with `--no-cont-batching`.
- `--rope-scaling` → was numeric (factor), now enum {none,linear,yarn}.
  Numeric factor moved to `--rope-scale`.
- `--metrics`, `--embeddings` → still bare flags (unchanged).

## Fix

### buildLlamaExtraArgs() (server-side, in src/lib/docker.ts)

- `--flash-attn` now emits `--flash-attn on` or `--flash-attn off`
  (always, never bare).
- `--mlock` + `--no-mmap` → unified `--load-mode`:
  - both set → `--load-mode mlock`
  - mlock only → `--load-mode mmap+mlock`
  - no-mmap only → `--load-mode none`
  - neither → emit nothing (default auto)
- `--cont-batching` no longer emitted (default-on). Only emit
  `--no-cont-batching` if user explicitly disabled cont-batching.
- `--rope-scaling <N>` → `--rope-scale <N>` (numeric factor uses new flag).

### parseLlamaExtraArgs() (reads .env)

Updated to handle both legacy and modern syntax:

- `--flash-attn on|off|auto` → set cfg.flashAttn accordingly.
- `--flash-attn` (bare, legacy) → treated as 'on'.
- `--load-mode mlock` → set mlock=true, noMmap=true.
- `--load-mode mmap+mlock` → set mlock=true (noMmap stays false).
- `--load-mode none` → set noMmap=true.
- `--mlock` / `--no-mmap` (legacy) → still parsed for backward compat.
- `--no-cont-batching` / `-nocb` → set contBatching=false.
- `--cont-batching` / `-cb` (legacy) → set contBatching=true (default anyway).
- `--rope-scaling <number>` → treated as `--rope-scale <number>`.
- `--rope-scaling {none,linear,yarn}` → ignored (it's the method, not the factor).
- `--rope-scale <number>` → parsed directly.

Helper `isValue(s)` added to detect whether the next token is a value or
another flag (avoids consuming a following flag as a value).

### buildPreviewArgs() (frontend, in src/app/page.tsx)

Same changes as buildLlamaExtraArgs — kept in sync so the .env preview in
the Config tab shows the exact args that will be passed.

## Verification

- `npm run build` — OK, all 26 routes
- `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓
- Manually verified the generated args by calling buildLlamaExtraArgs() with
  default config — produces valid llama.cpp server CLI.

## After deploy

```sh
git pull && sh build.sh
docker compose up -d --force-recreate dashboard
```

Then click 'Start Llama' — should now launch without the flash-attn error.

## Files changed

- dashboard/src/lib/docker.ts — buildLlamaExtraArgs + parseLlamaExtraArgs
- dashboard/src/app/page.tsx — buildPreviewArgs (frontend copy)
2026-10-24 02:00:47 +00:00
Z User
12fb97314b fix: comfyui mount uses HOST_PROJECT_PATH + add CivitAI download support
## 1. ComfyUI mount fix

### Problem
When the dashboard called `docker compose up -d comfyui`, the comfyui
service's volume mounts used ${COMFY_BASE_HOST:-./gpu/comfy} and
${COMFY_RUN_HOST:-./comfyui/run}. Without explicit env overrides, compose
resolved these to './gpu/comfy' relative to the CWD of the dashboard
container (= /project inside the container). Docker daemon on the host
tried to mount /project/gpu/comfy — but /project only exists inside the
dashboard container, not on the host.

The result: comfyui mounted to non-existent paths on the host, all
models missing.

### Fix
`startService('comfyui')` now explicitly passes the same env vars that
`gpuctl start comfy` does, mirroring `ssh/scripts/comfy.sh`:
  - COMFY_BASE_HOST=$HOST_PROJECT_PATH/gpu/comfy
  - COMFY_RUN_HOST=$HOST_PROJECT_PATH/comfyui/run

These are passed as extra env to `runCompose`, which forwards them to
the compose subprocess. Compose then resolves the volume mounts to the
real host path.

## 2. CivitAI download support

### Why
CivitAI URLs are special:
- `https://civitai.com/models/12345` is a model PAGE (HTML), not the
  file. curl would download the HTML page instead of the .gguf.
- The actual file is at `https://civitai.com/api/download/models/12345`
  which returns a 302 redirect to a signed Cloudflare URL.
- Downloads require an API token: `?token=XXX`. Without it, NSFW /
  gated models fail with 401.
- `civitai.red` is a mirror — it doesn't accept API requests the same
  way.

### Fix

#### Settings storage

New `DashboardSettings` interface with `civitaiToken: string`. Persisted
to `gpu/dashboard/settings.json` (separate from the llama config —
download settings shouldn't be part of a llama preset).

- `loadSettings()` / `saveSettings()` in `dashboard/src/lib/downloads.ts`
- Cache like the .env loader (read once per process lifetime)

#### URL transformation

`prepareCivitaiUrl(rawUrl, token)` — handles all CivitAI URL shapes:

  1. `https://civitai.com/models/12345` (model page) → converts to
     `https://civitai.com/api/download/models/12345` (preserves any
     `?modelVersionId=...` query param)
  2. `https://civitai.com/api/download/models/12345` → appends
     `?token=XXX` if missing
  3. `https://civitai.red/models/12345` → normalizes host to civitai.com
     (mirror doesn't accept API requests the same way)
  4. Non-CivitAI URLs (HuggingFace, GitHub releases, etc.) → passed
     through unchanged

Returns `{ url, note }` where note explains what we did (e.g.
'converted model page → API download URL, added API token').

#### startModelDownload integration

`startModelDownload()` now:
1. Loads settings (to get the token)
2. Calls `prepareCivitaiUrl()` on the input URL
3. Uses the transformed URL for curl
4. Records `originalUrl` and `urlNote` on the job object (shown in UI)

#### API routes (new)

`/api/settings`:
- `GET` — returns the persisted settings (civitai token etc)
- `PUT` — updates settings (body: `{ civitaiToken: '...' }`)
- `POST { action: 'preview-url', url: '...' }` — returns what the URL
  would be transformed into, without starting a download. Used by the
  frontend for live URL preview as the user types.

#### Frontend

- **Settings UI** in the Models tab: 'CivitAI token' button (with badge
  showing 'set' / 'empty'). Click to expand a form with password input,
  Save / Clear buttons, and a link to https://civitai.com/user/account
  to get a token.

- **URL preview**: as the user types in the download URL field, a
  debounced call to `POST /api/settings {action:'preview-url'}` runs.
  If the URL will be transformed (e.g. civitai.com/models/12345 →
  civitai.com/api/download/models/12345?token=...), a preview card
  appears below the input showing the transformed URL + note.

- **DownloadJobRow**: shows `originalUrl` (struck through) → `url`
  (the actual URL curled), plus the `urlNote` as italic text. So the
  user can see what happened to their pasted URL.

## Verification

- `npm run build` — OK, all 26 routes (1 new /api/settings route)
- `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
```

For ComfyUI:
1. Click 'Start Comfy' (or Start button in System tab → comfyui row)
2. Check `docker inspect <comfyui-container> | grep Mounts` — should
   show $HOST_PROJECT_PATH/gpu/comfy and $HOST_PROJECT_PATH/comfyui/run

For CivitAI:
1. Open Models tab → 'CivitAI token' button → paste your token from
   https://civitai.com/user/account → API Keys → Save
2. Paste any CivitAI URL (model page or API download URL) in the URL field
3. Watch the URL preview card show the transformed URL
4. Click Download — file fetches with token auth

## Files changed

- dashboard/src/lib/docker.ts — added DASHBOARD_SETTINGS_PATH export,
  startService() now passes COMFY_BASE_HOST / COMFY_RUN_HOST for comfyui
- dashboard/src/lib/downloads.ts — new DashboardSettings interface,
  loadSettings / saveSettings, prepareCivitaiUrl, startModelDownload
  integrates URL transformation
- dashboard/src/app/api/settings/route.ts — new (GET/PUT/POST preview)
- dashboard/src/app/page.tsx — settings state, civitai token UI,
  URL preview, DownloadJobRow shows originalUrl + urlNote
2026-10-24 01:53:37 +00:00
Z User
ab60962d76 feat(dashboard): favicon, fixed presets, more launch params, chat tab with TPS/TTFT metrics
## 1. Favicon

Added `dashboard/src/app/icon.svg` — Next.js App Router auto-detects
`src/app/icon.svg` and serves it as the browser tab icon. SVG chip design
with gradient background.

## 2. Presets — fixed 'all resets to original'

### Root cause
`POST /api/config { action: 'save-preset' }` was using `stripPresets(current)`
to snapshot the config — but `current` is the SERVER-side persisted config,
not what's currently in the UI form. If the user edited the form but didn't
click 'Apply' first, saving a preset would snapshot the OLD persisted config,
not what they see on screen.

### Fix
- API now accepts an optional `config` field in the POST body. If present,
  it's merged into `current` before performing the action.
- Frontend `handleSavePreset()` now sends the current form state:
  `{ action: 'save-preset', name: '...', config }`
- Refactored merge logic into a single `mergeConfig()` helper used by both
  PUT and POST handlers.

This also fixes the same issue for future actions that need the current
form state.

## 3. More launch parameters

Extended `DashboardConfig` with 21 new fields, all wired into
`buildLlamaExtraArgs()` and `parseLlamaExtraArgs()`:

### KV cache
- `ubatchSize` — micro-batch size (`--ubatch-size`)
- `cacheTypeK` — K cache dtype: f16/f32/q8_0/q4_0 (`--cache-type-k`)
- `cacheTypeV` — V cache dtype (`--cache-type-v`)
- `defragThold` — KV cache defrag threshold (`--defrag-thold`)

### Performance flags (boolean toggles)
- `flashAttn` (`--flash-attn`) — enabled by default
- `contBatching` (`--cont-batching`) — enabled by default
- `noMmap` (`--no-mmap`)
- `mlock` (`--mlock`)
- `embeddings` (`--embeddings`)
- `metrics` (`--metrics`)

### RoPE / YaRN context extension
- `ropeFreqScale` (`--rope-freq-scale`)
- `ropeScale` (`--rope-scaling`)
- `yarnExtFactor` (`--yarn-ext-factor`)
- `yarnAttnFactor` (`--yarn-attn-factor`)
- `yarnBetaFast` (`--yarn-beta-fast`, default 32.0)
- `yarnBetaSlow` (`--yarn-beta-slow`, default 1.0)

### Sampling defaults (server applies to /completion by default)
- `topK` (`--top-k`)
- `topP` (`--top-p`)
- `minP` (`--min-p`)
- `temperature` (`--temp`)
- `repeatPenalty` (`--repeat-penalty`)
- `systemPrompt` — default system prompt (used by chat tab)

### UI
- 5 new sections in ConfigTab, each in a styled card with grouped fields
- ToggleRow component for boolean flags
- `buildPreviewArgs()` (the .env preview) updated to include new fields

## 4. Chat tab

New tab between Config and Models — talk to the running llama model
directly from the dashboard.

### Backend
- `POST /api/chat` — proxies llama.cpp `/v1/chat/completions`. Uses Node's
  native `fetch()` to call `http://llama:8080/v1/chat/completions`
  (dashboard is on the same Docker network).
- Streams SSE response back to the browser.
- Forwards sampling params: temperature, top_p, top_k, min_p,
  repeat_penalty.

### Frontend
- Streaming chat with abort support (Stop button mid-generation)
- Auto-scroll toggle
- Ctrl+Enter to send
- System prompt auto-prepended from ConfigTab's `systemPrompt` field
- Per-message stats displayed under assistant responses:
  * TPS (predicted_per_second)
  * prompt tokens + processing time
  * cache hit rate
  * speculative decoding accept rate (spec_accepted / spec_drafted)

## 5. Perf tab

New tab — live performance metrics.

### Slots view (default)
Polls `GET /api/slots` every 1.5s. Shows per-slot:
- Status (processing / idle)
- ctx usage (n_past / n_ctx)
- TPS (predicted_per_second)
- TTFT (prompt_ms / 1000)
- Prompt TPS
- Cache hit rate
- Spec decoding stats (if --spec-* was used at startup):
  drafted, accepted, accept rate

### Prometheus view
Polls `GET /api/metrics` (llama.cpp's /metrics endpoint). Renders raw
Prometheus exposition format as <pre>. Requires llama started with
`--metrics` flag (now a toggle in ConfigTab).

### Backend
- `GET /api/slots` — proxies llama.cpp `http://llama:8080/slots`
- `GET /api/metrics` — proxies llama.cpp `http://llama:8080/metrics`

## Files changed

- dashboard/src/app/icon.svg — new (favicon)
- dashboard/src/app/page.tsx — added ChatTab + PerfTab + ToggleRow + new
  ConfigTab sections + types updates + handleSavePreset sends config
- dashboard/src/app/api/config/route.ts — mergeConfig() helper,
  POST accepts optional config field
- dashboard/src/app/api/chat/route.ts — new (chat proxy with SSE streaming)
- dashboard/src/app/api/metrics/route.ts — new (Prometheus proxy)
- dashboard/src/app/api/slots/route.ts — new (slot status proxy)
- dashboard/src/lib/docker.ts — extended DashboardConfig with 21 fields,
  updated buildLlamaExtraArgs() and parseLlamaExtraArgs()

## Verification

- `npm run build` — OK, 22 routes (1 page + 1 icon + 1 not-found + 19 API)
- `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓
2026-10-24 01:26:21 +00:00
Z User
93bf5cdc88 fix(dashboard): start-llama diagnostics + comfy/queue no longer 500s
## Two issues from user feedback

### Issue 1: Apply doesn't change model

User reports: 'if I select a model in the panel, it shows as the new model
but logs show the default model is still running'.

Most likely cause: the user has an old model-worker image without the
`--json` flag, OR the request body isn't including the new model name.

The fix here is purely diagnostic — add logging so we can see what's
happening:

- `startLlama()` now logs to console:
  * `[startLlama] model: <name>`
  * `[startLlama] extraArgs: <args>`
  * `[startLlama] compose exit: <code>`
  * `[startLlama] compose output: <full docker compose output>`

- `/api/llama` POST logs:
  * `[/api/llama] action: <action> config.model: <name>`
  * `[/api/llama] merged cfg.model: <name>`
  * `[/api/llama] startLlama result ok: <bool>`

- `handleStartLlama()` now includes the last 500 chars of compose logs
  in the toast message if start failed. Toast component renders multi-line
  messages as `<pre>` so the logs are readable.

- Toast now uses `max-w-md` (was `max-w-sm`) and supports multi-line
  content with `whitespace-pre-wrap`.

After deploying, run `docker logs -f gpu-node-win-dashboard` while
clicking Start Llama — you'll see exactly what model name is being sent
and what docker compose outputs.

### Issue 2: /api/comfy/queue returns 500 every 5s

User reports: 'in logs I see problems with queue — 500 Internal Server
Error'. Even when not downloading anything.

Most likely cause: model-worker image on prod is old and doesn't support
`queue --json` flag (added in PR #5). When `modelWorkerExec('queue',
'--json')` fails with non-zero exit code, `getComfyQueue()` returns
`ok: false`, and the endpoint returns 500. Frontend polls every 5s, so
we get a flood of 500s.

Fixes:

- `/api/comfy/queue` no longer returns 500 on worker failure. Always
  returns 200 with `{ ok: false, queue: [], error: <reason> }` —
  frontend shows empty queue, no error toast.

- `modelWorkerExec()` now logs failures to console.error with:
  * args being called
  * container name
  * exit code
  * stderr (truncated to 500 chars)

  This will show up in `docker logs gpu-node-win-dashboard` so we can
  see if it's a missing --json flag, container not running, etc.

## After deploying

```sh
git pull && sh build.sh
docker compose up -d --force-recreate dashboard model-worker
```

If model-worker is on old image (no --json support), the dashboard logs
will show:

  [modelWorkerExec] args=["queue","--json"] container=gpu-node-win-model-worker
  exitCode=1 stderr=Usage: ... worker.py queue [--watch] [--clear] ...

Recreate model-worker to pick up the new image:

  docker compose up -d --force-recreate model-worker

## Files changed

- dashboard/src/lib/docker.ts:
  * startLlama() now logs model + extraArgs + compose output
  * modelWorkerExec() now logs failures with exit code + stderr
- dashboard/src/app/api/llama/route.ts: logs action + model + result
- dashboard/src/app/api/comfy/queue/route.ts: returns 200 even on failure
- dashboard/src/app/page.tsx:
  * handleStartLlama includes compose logs in toast on failure
  * Toast component supports multi-line messages (renders as <pre>)
2026-10-24 01:07:37 +00:00
Z User
15892cf0d1 fix(dashboard): restore GET /api/models + fs fallbacks for comfy models/types
## Three bugs found from /api/debug output

User reported: 'in UI ни комфи (причем и типы и модели) ни ллама модели не
видны' — even though /api/debug shows the directories exist with files in
them.

### Bug 1: GET /api/models was deleted

In PR #5 I added `DELETE /api/models?name=...` but accidentally removed
the existing `GET /api/models` handler when I rewrote the file with the
Write tool. The frontend was getting 405 Method Not Allowed, but
`refreshModels()` silently swallowed the error (try/catch with no logging).

Fix: restore the GET handler alongside DELETE.

### Bug 2: refreshComfyModels() was never called

The initial useEffect only called refreshConfig, refreshModels,
refreshComfyTypes, and an interval for refreshComfyQueue.
refreshComfyModels was defined as a useCallback but never invoked on
mount — so the Comfy models table was always empty until the user
clicked Refresh manually.

Fix: add refreshComfyModels() to the initial useEffect.

### Bug 3: /api/comfy/types and /api/comfy/models fail when model-worker is offline

Both endpoints proxied to `docker exec model-worker python3 /app/worker.py` —
which fails (returns empty / error) when the model-worker container isn't
running (e.g. during sleep mode, or right after a reboot before wake).

The /api/debug endpoint showed that the directories exist on disk via
fs.readdir — so we have the data, just weren't using it.

Fix: add fs-based fallbacks in dashboard/src/lib/docker.ts:

  - `listComfyTypesFromFs()` — reads subdirectories of
    /project/gpu/comfy/models directly. Same as what `worker.py types` does,
    but no docker exec required.

  - `listComfyModelsFromFs(type?)` — walks each subdirectory and lists
    files. Same as what `worker.py list --json` does, but no docker exec.

  - `listComfyModels()` and `getComfyTypes()` now try the worker first,
    then fall back to fs. If both succeed, the worker's output wins (it
    filters out metadata files like .txt).

  - New export `COMFY_MODELS_DIR` — the internal mount path, used by both
    the fallback functions and /api/debug.

### Bonus: error visibility

All `refresh*()` callbacks in page.tsx now `console.error` on failure
instead of silently swallowing. The next time something breaks, you'll see
it in the browser DevTools console.

## Verification

- `npm run build` — OK, all 19 routes (including restored GET /api/models)
- `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓
- /api/debug still works (uses the same fs approach)

## Files changed

- dashboard/src/app/api/models/route.ts — restored GET handler
- dashboard/src/app/page.tsx — added refreshComfyModels() to initial
  useEffect, console.error on refresh failures
- dashboard/src/lib/docker.ts — added COMFY_MODELS_DIR export, fs-based
  fallbacks for comfy types/models, try-worker-first-then-fs flow
2026-10-24 00:08:04 +00:00
Z User
d742be2c3a fix(dashboard): properly pass .env vars to docker compose subprocess
## Problem

When the dashboard called `docker compose up -d llama` etc., it relied on:
  1. process.env inherited by the dashboard container — only contains the
     vars explicitly listed in compose.yaml's environment: section
     (HOST_PROJECT_PATH, PROJECT_DIR, LLAMA_MODELS_DIR, NODE_INSTANCE)
  2. compose's own --env-file (.env) lookup — but this depends on CWD which
     can differ

Critically, compose needs more than just HOST_PROJECT_PATH:
  - TAILSCALE_HOSTNAME  (used in container_name)
  - TS_AUTHKEY          (needed by tailscale service if started)
  - WEBDAV_USER, WEBDAV_PASS  (needed by webdav service)
  - 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)

Previously these were silently absent. `gpuctl` shells handle this by
explicitly exporting them before `docker compose` — the dashboard now does
the same.

## Fix

### `dashboard/src/lib/docker.ts`

- Added `loadEnvFile()` and `readEnvSync()` — parse `/project/.env` once
  and cache it. Handles quoted values, comments, blank lines.
- Added `envOrFile(key, fallback)` — resolves env value from process.env
  first, then .env file, then fallback.
- `HOST_PROJECT_PATH` and `TAILSCALE_HOSTNAME` now resolved via envOrFile
  (was hardcoded fallback to '/project').
- Added `validateComposeEnv()` — returns null if all required vars are set,
  or an error message describing the first missing var. Mirrors
  `require_host_project_path` in ssh/scripts/common.sh.
- `composeEnv()` now includes:
  * process.env (for PATH, HOME, etc.)
  * .env file contents (TS_AUTHKEY, WEBDAV_*, etc.)
  * Explicit overrides for TAILSCALE_HOSTNAME, HOST_PROJECT_PATH, NODE_INSTANCE
  * Caller-provided extras (LLAMA_MODEL, LLAMA_EXTRA_ARGS, COMFY_EXTRA_ARGS)
- `runCompose()` now calls `validateComposeEnv()` before any `up`/`start`
  operation. If validation fails, returns a clear error instead of letting
  compose silently resolve ${HOST_PROJECT_PATH:-./} to './'.
- `writeEnvLlamaConfig()` invalidates the .env cache after writing, so the
  next composeEnv() picks up the new LLAMA_MODEL/LLAMA_EXTRA_ARGS.

### `compose.yaml` — dashboard service

- Added `TAILSCALE_HOSTNAME: ${TAILSCALE_HOSTNAME:-gpu-node}` to the
  environment: section. Was previously missing — dashboard couldn't see the
  hostname without reading .env.

### `dashboard/src/app/api/debug/route.ts`

- Now also returns:
  * TAILSCALE_HOSTNAME in env block
  * comfyTypes (list of subdirs under gpu/comfy/models)
  * envValidation: { ok, error } — result of validateComposeEnv()
  * Whether LLAMA_MODELS_DIR actually exists and has files

After deploy, `curl http://gpu-node:8090/api/debug` will show:
  - Whether HOST_PROJECT_PATH is the real host path or just '/project'
  - Whether .env has all the vars compose needs
  - Whether /project/gpu/llama_models has any .gguf files
  - What subdirs /project/gpu/comfy/models has
2026-10-23 23:53:56 +00:00
Z User
41a921b3c2 fix(dashboard): live logs via SSE, comfy types, plain-text parsing, debug endpoint
## User-reported issues addressed

### 1. Logs show literal \\n (and don't update live)
- Old impl: GET /api/services/[role] returned a JSON snapshot {logs: '...'}
  with embedded \\n escape sequences that the UI rendered as plain text.
  Plus it wasn't actually streaming — fetch returned the whole body at once.
- New: GET /api/services/[role]/stream — proper Server-Sent Events endpoint.
  Emits one `log` event per line with {stream: stdout|stderr, line, ts}.
  Uses a line buffer so partial chunks don't get split mid-line.
  Client opens `new EventSource(...)` instead of fetch — gets genuine live
  updates (docker logs -f --tail 300 --timestamps).
- Added keep-alive comment every 15s for proxies that kill idle SSE.

### 2. 'Llama Dashboard' → 'GPU Node Dashboard'
- Renamed everywhere (browser title, header, footer)
- The dashboard now manages llama + comfy + system + services, so the old
  name was misleading.

### 3. Models not visible (llama + comfy)
- Root cause hypothesis: empty HOST_PROJECT_PATH → compose resolves
  ${HOST_PROJECT_PATH:-./} to './' relative to compose CWD inside the
  dashboard container, so volume mounts point to a path that doesn't exist
  on the host.
- Added /api/debug endpoint that returns:
  * All env vars the dashboard sees (PROJECT_DIR, HOST_PROJECT_PATH,
    LLAMA_MODELS_DIR, NODE_INSTANCE, SSH_ROLE, TAILSCALE_HOSTNAME)
  * Which paths exist (PROJECT_DIR, LLAMA_MODELS_DIR, comfy models dir)
  * Directory listings of each (so you can see what's actually there)
  * Contents of .env (so you can verify HOST_PROJECT_PATH was set)
  * Existence of dashboard-config.json
- This endpoint is for diagnosing 'models not visible' issues — call
  `curl http://gpu-node:8090/api/debug` after deployment.

### 4. Comfy models parsing
- worker.py `list` and `queue` commands output human-readable text, not
  JSON. The dashboard was trying to JSON.parse the output and silently
  returning empty arrays.
- Added --json flag to both commands (worker.py):
  * `worker.py list [type] --json` → {models: [{type, filename, sizeBytes}], total, totalBytes}
  * `worker.py queue --json` → {jobs: [...]}
  * `worker.py types` → ["checkpoints", "loras", ...] (new command)
- Updated dashboard to use --json everywhere.

### 5. Comfy model types — couldn't pick all available types
- Was hardcoded list of 9 types (checkpoints, loras, vae, etc.)
- Now fetched dynamically from /api/comfy/types, which calls the new
  `worker.py types` command — lists actual subdirectories of
  gpu/comfy/models.
- Falls back to hardcoded list if worker is offline or older version.

## Files changed

- model-worker/worker.py:
  * Added json import
  * Added command_list_json(model_type) — JSON variant of command_list
  * Added command_queue_json() — JSON variant of command_queue
  * Added `types` command (outputs JSON array of subdir names)
  * `list` command now accepts --json flag
  * `queue` command now accepts --json flag
  * print_usage() updated

- dashboard/src/app/api/services/[role]/stream/route.ts — new SSE endpoint
- dashboard/src/app/api/comfy/types/route.ts — new (proxy to worker.py types)
- dashboard/src/app/api/debug/route.ts — new (diagnostic endpoint)
- dashboard/src/lib/docker.ts:
  * listComfyModels uses --json flag
  * getComfyQueue uses --json flag
  * Added getComfyTypes() — calls worker.py types
  * Better error handling for type-not-found case
- dashboard/src/app/page.tsx:
  * Renamed 'Llama Dashboard' → 'GPU Node Dashboard'
  * LiveLogs type changed from string[] to {stream, line, ts}[]
  * startLogsStream uses EventSource instead of fetch+readablestream
  * Added comfyTypes state, refreshComfyTypes callback
  * ComfyTab receives dynamic types list (with fallback)
- dashboard/src/app/layout.tsx: title renamed
2026-10-23 23:45:48 +00:00
Claude
3dc57f5eaf 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
2026-10-23 22:45:47 +00:00
Claude
c4a91972b3 feat: add llama dashboard for managing launch config via web UI
Adds a small Next.js dashboard as a new Docker service ()
that replaces the need to manually edit  and call  over SSH
every time you want to tweak llama launch parameters.

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

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

Tech: Next.js 16 standalone, React 19, TypeScript 5, Tailwind 4,
shadcn-style components, Radix UI primitives.
2026-10-23 22:22:26 +00:00