Compare commits

...

4 Commits

Author SHA1 Message Date
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
ff180be9b5 Merge pull request 'fix(dashboard): restore GET /api/models + fs fallbacks for comfy models/types' (#6) from fix/dashboard-ui-visibility into master
Reviewed-on: #6
2026-10-24 00:35:57 +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
41da236ee6 Merge pull request 'fix(dashboard): live logs via SSE, comfy types, plain-text parsing, debug endpoint' (#5) from fix/dashboard-v3-improvements into master
Reviewed-on: #5
2026-10-23 23:57:41 +00:00
5 changed files with 237 additions and 61 deletions

View File

@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from "next/server";
import { NextResponse } from "next/server";
import { getComfyQueue } from "@/lib/docker";
export const dynamic = "force-dynamic";
@@ -6,12 +6,20 @@ export const runtime = "nodejs";
/**
* GET /api/comfy/queue
* Returns current download queue via `docker exec model-worker python3 /app/worker.py queue`.
*
* Returns current download queue via `docker exec model-worker python3
* /app/worker.py queue --json`.
*
* Returns 200 even when model-worker is offline (queue is empty in that
* case) — frontend polls this every 5s, returning 500 on every poll when
* worker isn't running would spam the browser console.
*/
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 }
);
return NextResponse.json({
ok: result.ok,
queue: result.queue,
raw: result.raw,
error: result.error,
});
}

View File

@@ -17,13 +17,17 @@ export async function POST(req: NextRequest) {
config?: Partial<DashboardConfig>;
};
console.log("[/api/llama] action:", body.action, "config.model:", body.config?.model);
if (body.action === "start") {
const current = await loadConfig();
const cfg: DashboardConfig = {
...current,
...(body.config || {}),
} as DashboardConfig;
console.log("[/api/llama] merged cfg.model:", cfg.model);
const result = await startLlama(cfg);
console.log("[/api/llama] startLlama result ok:", result.ok);
return NextResponse.json(result, { status: result.ok ? 200 : 500 });
}

View File

@@ -4,6 +4,17 @@ import { deleteModel, listModels } from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* GET /api/models
*
* Lists all .gguf files in gpu/llama_models/. Returns:
* { models: [{ name, sizeBytes, sizeHuman, modifiedAt }] }
*/
export async function GET() {
const models = await listModels();
return NextResponse.json({ models });
}
/**
* DELETE /api/models?name=foo.gguf
*

View File

@@ -254,11 +254,14 @@ export default function DashboardPage() {
const refreshModels = React.useCallback(async () => {
try {
const res = await fetch("/api/models", { cache: "no-store" });
if (!res.ok) return;
if (!res.ok) {
console.error("[refreshModels] HTTP", res.status, await res.text().catch(() => ""));
return;
}
const data = await res.json();
setModels(data.models || []);
} catch {
/* ignore */
} catch (err) {
console.error("[refreshModels] error:", err);
}
}, []);
@@ -268,8 +271,8 @@ export default function DashboardPage() {
if (!res.ok) return;
const data = await res.json();
setConfig(data.config || DEFAULT_CONFIG);
} catch {
/* ignore */
} catch (err) {
console.error("[refreshConfig] error:", err);
}
}, []);
@@ -296,8 +299,8 @@ export default function DashboardPage() {
// If current selection isn't in the new list, switch to first available
setComfyAddType((cur) => (types.includes(cur) ? cur : types[0]));
}
} catch {
/* keep fallback list */
} catch (err) {
console.error("[refreshComfyTypes] error:", err);
}
}, []);
@@ -309,7 +312,8 @@ export default function DashboardPage() {
const res = await fetch(url, { cache: "no-store" });
const data = await res.json();
setComfyModels(data.models || []);
} catch {
} catch (err) {
console.error("[refreshComfyModels] error:", err);
setComfyModels([]);
}
}, [comfyFilter]);
@@ -319,7 +323,8 @@ export default function DashboardPage() {
const res = await fetch("/api/comfy/queue", { cache: "no-store" });
const data = await res.json();
setComfyQueue(data.queue || []);
} catch {
} catch (err) {
// Queue refresh runs every 5s — don't spam console on network blips
setComfyQueue([]);
}
}, []);
@@ -328,9 +333,16 @@ export default function DashboardPage() {
refreshConfig();
refreshModels();
refreshComfyTypes();
refreshComfyModels();
const id = setInterval(refreshComfyQueue, 5000);
return () => clearInterval(id);
}, [refreshConfig, refreshModels, refreshComfyTypes, refreshComfyQueue]);
}, [
refreshConfig,
refreshModels,
refreshComfyTypes,
refreshComfyModels,
refreshComfyQueue,
]);
// ---------------------------------------------------------------------------
// Live logs streaming via Server-Sent Events (replaces fetch+readablestream)
@@ -440,6 +452,7 @@ export default function DashboardPage() {
async function handleStartLlama() {
await runAction("start-llama", async () => {
// Persist config first so reloads restore it.
const res = await fetch("/api/config", {
method: "PUT",
headers: { "Content-Type": "application/json" },
@@ -451,7 +464,17 @@ export default function DashboardPage() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "start", config }),
});
return await startRes.json();
const result = await startRes.json();
// If start failed, include compose logs in the message so the user can
// see what went wrong (common cause: model-worker still on old image
// without --json flag, or env not set, etc).
if (!result.ok && result.logs) {
return {
ok: false,
message: `${result.message}\n\n${result.logs.slice(-500)}`,
};
}
return result;
});
}
@@ -2113,10 +2136,13 @@ function Toast({
toast: { type: "success" | "error" | "info"; message: string };
onClose: () => void;
}) {
// If message has multiple lines, render as pre-formatted text (so logs are
// readable); otherwise normal flow.
const isMultiLine = toast.message.includes("\n");
return (
<div
className={cn(
"fixed bottom-4 right-4 z-50 max-w-sm rounded-md border bg-card shadow-lg p-3 pr-9 text-sm",
"fixed bottom-4 right-4 z-50 max-w-md rounded-md border bg-card shadow-lg p-3 pr-9 text-sm",
toast.type === "success" && "border-success/30",
toast.type === "error" && "border-destructive/30",
toast.type === "info" && "border-border"
@@ -2131,7 +2157,13 @@ function Toast({
toast.type === "info" && "bg-muted-foreground"
)}
/>
<span className="text-foreground">{toast.message}</span>
{isMultiLine ? (
<pre className="text-foreground whitespace-pre-wrap break-all font-mono text-[11px] leading-tight max-h-60 overflow-y-auto scrollbar-thin">
{toast.message}
</pre>
) : (
<span className="text-foreground">{toast.message}</span>
)}
</div>
<button
onClick={onClose}

View File

@@ -124,6 +124,14 @@ export const TAILSCALE_HOSTNAME = envOrFile("TAILSCALE_HOSTNAME", "gpu-node");
export const LLAMA_MODELS_DIR =
process.env.LLAMA_MODELS_DIR || path.join(PROJECT_DIR, "gpu", "llama_models");
/**
* Internal mount of the comfy models directory (mirrors the host path that
* the model-worker container mounts as /models).
*/
export const COMFY_MODELS_DIR =
process.env.COMFY_MODELS_DIR ||
path.join(PROJECT_DIR, "gpu", "comfy", "models");
/**
* Node instance name (used for filtering containers by label).
*/
@@ -626,6 +634,12 @@ export async function startLlama(
await saveConfig(config);
await writeEnvLlamaConfig(config.model, extraArgs);
// Log what we're actually starting with — helps diagnose "model didn't
// change" issues (the most common cause is the request body not including
// the new model, or compose picking up an old LLAMA_MODEL from .env).
console.log("[startLlama] model:", config.model);
console.log("[startLlama] extraArgs:", extraArgs);
const res = await runCompose(
[
"--profile",
@@ -642,9 +656,14 @@ export async function startLlama(
);
const combined = res.stdout + (res.stderr ? `\n${res.stderr}` : "");
console.log("[startLlama] compose exit:", res.code);
console.log("[startLlama] compose output:\n", combined);
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama instance started" : "Failed to start",
message: res.code === 0
? `Llama started (model: ${config.model})`
: `Failed to start (exit ${res.code})`,
logs: combined,
};
}
@@ -937,10 +956,10 @@ async function modelWorkerExec(
}
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 }
);
const cmd = `docker exec ${container} python3 /app/worker.py ${quoted}`;
const { stdout, stderr } = await execAsync(cmd, {
maxBuffer: 8 * 1024 * 1024,
});
return {
ok: true,
output: String(stdout),
@@ -951,7 +970,12 @@ async function modelWorkerExec(
stdout?: string | Buffer;
stderr?: string | Buffer;
message: string;
code?: number;
};
// Log the failure so it's visible in dashboard container logs
console.error(
`[modelWorkerExec] args=${JSON.stringify(args)} container=${container} exitCode=${e.code} stderr=${e.stderr ? String(e.stderr).slice(0, 500) : "(empty)"} message=${e.message}`
);
return {
ok: false,
output: e.stdout ? String(e.stdout) : "",
@@ -967,43 +991,127 @@ export interface ComfyModelEntry {
sizeHuman?: string;
}
/**
* Read comfy model types directly from the filesystem (subdirs of
* /project/gpu/comfy/models). Used as a fallback when the model-worker
* container isn't running.
*
* Returns the same shape as `worker.py types`.
*/
async function listComfyTypesFromFs(): Promise<string[]> {
try {
const entries = await fs.readdir(COMFY_MODELS_DIR, { withFileTypes: true });
return entries
.filter((e) => e.isDirectory() && !e.isSymbolicLink())
.map((e) => e.name)
.sort();
} catch {
return [];
}
}
/**
* Read comfy models directly from the filesystem. Walks each subdirectory
* (one per model type) and lists all files inside. Used as a fallback when
* the model-worker container isn't running.
*
* Returns the same shape as `worker.py list --json`.
*/
async function listComfyModelsFromFs(
type?: string
): Promise<ComfyModelEntry[]> {
const out: ComfyModelEntry[] = [];
try {
if (type) {
// Single type — list its contents
const typeDir = path.join(COMFY_MODELS_DIR, type);
const stat = await fs.stat(typeDir).catch(() => null);
if (!stat || !stat.isDirectory()) return [];
const entries = await fs.readdir(typeDir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isFile()) continue;
if (entry.name.startsWith(".")) continue;
const full = path.join(typeDir, entry.name);
const size = await fs.stat(full).then((s) => s.size).catch(() => 0);
out.push({
type,
filename: entry.name,
sizeBytes: size,
sizeHuman: size > 0 ? humanSize(size) : undefined,
});
}
} else {
// All types — walk each subdir
const types = await listComfyTypesFromFs();
for (const t of types) {
const typeDir = path.join(COMFY_MODELS_DIR, t);
const entries = await fs.readdir(typeDir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isFile()) continue;
if (entry.name.startsWith(".")) continue;
const full = path.join(typeDir, entry.name);
const size = await fs.stat(full).then((s) => s.size).catch(() => 0);
out.push({
type: t,
filename: entry.name,
sizeBytes: size,
sizeHuman: size > 0 ? humanSize(size) : undefined,
});
}
}
}
} catch {
/* ignore */
}
return out;
}
export async function listComfyModels(
type?: string
): Promise<{ ok: boolean; models: ComfyModelEntry[]; raw: string; error?: string }> {
// Use the new --json flag so we get structured output instead of having to
// parse the human-readable table.
// Try the model-worker first — it knows which files are real models vs
// metadata files (.txt etc.) and follows ComfyUI's naming conventions.
const args = ["list"];
if (type) args.push(type);
args.push("--json");
const res = await modelWorkerExec(...args);
if (!res.ok) {
return { ok: false, models: [], raw: res.output, error: res.error };
}
try {
const parsed = JSON.parse(res.output);
// worker.py outputs {"models": [...], "total": N, "totalBytes": N}
// or {"error": "...", "available_types": [...]} on type-not-found
if (parsed.error) {
return {
ok: false,
models: [],
raw: res.output,
error: parsed.error,
};
if (res.ok) {
try {
const parsed = JSON.parse(res.output);
if (parsed.error) {
return {
ok: false,
models: [],
raw: res.output,
error: parsed.error,
};
}
const arr: ComfyModelEntry[] = (parsed.models || []).map(
(m: { type: string; filename: string; sizeBytes?: number }) => ({
type: m.type,
filename: m.filename,
sizeBytes: m.sizeBytes,
sizeHuman: m.sizeBytes ? humanSize(m.sizeBytes) : undefined,
})
);
return { ok: true, models: arr, raw: res.output };
} catch {
// Fall through to fs fallback
}
const arr: ComfyModelEntry[] = (parsed.models || []).map(
(m: { type: string; filename: string; sizeBytes?: number }) => ({
type: m.type,
filename: m.filename,
sizeBytes: m.sizeBytes,
sizeHuman: m.sizeBytes ? humanSize(m.sizeBytes) : undefined,
})
);
return { ok: true, models: arr, raw: res.output };
} catch {
// Probably worker.py without --json support (older version)
return { ok: true, models: [], raw: res.output };
}
// Fallback: read directly from the filesystem. Useful when:
// - model-worker container isn't running (e.g. during sleep mode)
// - worker.py doesn't support --json flag (older version)
// - docker exec fails for any reason
const models = await listComfyModelsFromFs(type);
return {
ok: true,
models,
raw: res.output || "",
error: res.ok ? undefined : res.error,
};
}
export async function getComfyTypes(): Promise<{
@@ -1012,17 +1120,30 @@ export async function getComfyTypes(): Promise<{
raw: string;
error?: string;
}> {
// Uses the new `worker.py types` command — outputs JSON array of strings.
// Falls back to an empty list if the worker version doesn't support it yet.
// Try the model-worker first.
const res = await modelWorkerExec("types");
if (!res.ok) return { ok: false, types: [], raw: res.output, error: res.error };
try {
const parsed = JSON.parse(res.output);
const arr: string[] = Array.isArray(parsed) ? parsed : [];
return { ok: true, types: arr, raw: res.output };
} catch {
return { ok: true, types: [], raw: res.output };
if (res.ok) {
try {
const parsed = JSON.parse(res.output);
const arr: string[] = Array.isArray(parsed) ? parsed : [];
if (arr.length > 0) {
return { ok: true, types: arr, raw: res.output };
}
} catch {
/* fall through */
}
}
// Fallback: read subdirectories of gpu/comfy/models directly.
// The model-worker container might not be running (sleep mode), but the
// directory is mounted into the dashboard container at /project/gpu/comfy.
const types = await listComfyTypesFromFs();
return {
ok: types.length > 0,
types,
raw: res.output || "",
error: types.length > 0 ? undefined : res.error || "no types found",
};
}
export interface ComfyQueueEntry {