Compare commits

...

6 Commits

Author SHA1 Message Date
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
a94d14faaf Merge pull request 'fix(dashboard): llama.cpp CLI arg changes — flash-attn value, load-mode, no-cont-batching' (#11) from fix/llama-cli-args into master
Reviewed-on: #11
2026-10-24 02:04:10 +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
b0e03cdb99 Merge pull request 'fix: comfyui mount uses HOST_PROJECT_PATH + add CivitAI download support' (#10) from fix/comfy-mount-and-civitai into master
Reviewed-on: #10
2026-10-24 01:55:42 +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
e02b0e57a3 Merge pull request 'feat(dashboard): download .gguf models from URL with live progress' (#9) from feature/llama-model-download into master
Reviewed-on: #9
2026-10-24 01:40:19 +00:00
6 changed files with 985 additions and 265 deletions

View File

@@ -1,6 +1,4 @@
import { NextRequest, NextResponse } from "next/server";
import { getLlamaContainerName } from "@/lib/docker";
import { spawn } from "node:child_process";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -10,13 +8,26 @@ export const maxDuration = 300;
* POST /api/chat
*
* Streams a chat completion from llama.cpp /v1/chat/completions (OpenAI-compatible).
* The dashboard container is on the same Docker network as llama, so we call
* http://llama:8080/v1/chat/completions directly via Node's native fetch().
*
* Body: {
* messages: [{role, content}],
* temperature?, top_p?, top_k?, min_p?, repeat_penalty?, max_tokens?, stream?
* temperature?, top_p?, top_k?, min_p?, repeat_penalty?,
* max_tokens?, // OpenAI-style; default -1 = infinity
* stream?, // default true
* reasoning_format?, // 'auto' | 'deepthink' | 'none' (server-side default is 'auto')
* }
*
* Returns: SSE stream of OpenAI-compatible chat completion chunks.
*
* Each chunk can have:
* choices[0].delta.content — regular response token
* choices[0].delta.reasoning_content — thinking tokens (when --reasoning-format auto
* and the model emits blockDim)
* choices[0].timings — present in final chunk if --perf or timings enabled
* (prompt_n, prompt_ms, prompt_per_second, predicted_n, predicted_ms,
* predicted_per_second, cache_hit_rate, spec_accepted, spec_drafted)
*/
interface ChatMessage {
role: "system" | "user" | "assistant";
@@ -33,6 +44,7 @@ export async function POST(req: NextRequest) {
repeat_penalty?: number;
max_tokens?: number;
stream?: boolean;
reasoning_format?: string;
};
if (!body.messages || !Array.isArray(body.messages) || body.messages.length === 0) {
@@ -42,16 +54,7 @@ export async function POST(req: NextRequest) {
);
}
const containerName = await getLlamaContainerName();
if (!containerName) {
return NextResponse.json(
{ ok: false, error: "llama container not running" },
{ status: 503 }
);
}
// Build the request payload for llama.cpp /v1/chat/completions endpoint.
// llama.cpp supports OpenAI-compatible API.
// Build the OpenAI-compatible payload for llama.cpp
const payload: Record<string, unknown> = {
messages: body.messages,
stream: body.stream !== false,
@@ -62,16 +65,13 @@ export async function POST(req: NextRequest) {
if (body.min_p != null) payload.min_p = body.min_p;
if (body.repeat_penalty != null) payload.repeat_penalty = body.repeat_penalty;
if (body.max_tokens != null) payload.max_tokens = body.max_tokens;
if (body.reasoning_format != null) payload.reasoning_format = body.reasoning_format;
// Always ask for timings — llama.cpp includes them in the final stream chunk
// when stream_options.include_usage is set (or in the last non-streaming
// response body).
payload.stream_options = { include_usage: true, continuous_usage_stats: false };
const payloadJson = JSON.stringify(payload);
// Build the docker exec command to send the request to llama.cpp inside
// the container. We use `docker exec ... wget` because we can't reach
// the container's port from the dashboard directly (different network
// namespace). Actually — the dashboard IS on the same Docker network,
// so we can just fetch http://llama:8080/v1/chat/completions directly.
// But wget is more reliable for streaming.
const useStream = body.stream !== false;
const encoder = new TextEncoder();
@@ -79,9 +79,6 @@ export async function POST(req: NextRequest) {
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
try {
// Use Node's fetch (available in Node 18+) to call llama.cpp
// directly over the Docker network. The dashboard container is
// on the same network as llama, so http://llama:8080 works.
const res = await fetch("http://llama:8080/v1/chat/completions", {
method: "POST",
headers: {
@@ -164,6 +161,3 @@ export async function POST(req: NextRequest) {
}
}
}
// Suppress unused warning
void spawn;

View File

@@ -52,6 +52,9 @@ function mergeConfig(
minP: patch.minP ?? base.minP,
temperature: patch.temperature ?? base.temperature,
repeatPenalty: patch.repeatPenalty ?? base.repeatPenalty,
nPredict: patch.nPredict ?? base.nPredict,
reasoningFormat: patch.reasoningFormat ?? base.reasoningFormat,
jinja: patch.jinja ?? base.jinja,
extraArgs: patch.extraArgs ?? base.extraArgs,
presets: patch.presets ?? base.presets,
};

View File

@@ -0,0 +1,78 @@
import { NextRequest, NextResponse } from "next/server";
import {
loadSettings,
saveSettings,
prepareCivitaiUrl,
type DashboardSettings,
} from "@/lib/downloads";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* GET /api/settings
*
* Returns the persisted dashboard settings (civitai token etc).
*
* NOTE: The civitai token is returned in plain text. The dashboard has no
* auth and is intended for use within a trusted tailnet only (Tailscale
* serve on port 8090). If you expose this externally, add auth first.
*/
export async function GET() {
const settings = await loadSettings();
return NextResponse.json({ settings });
}
/**
* PUT /api/settings
*
* Body: Partial<DashboardSettings> — only the fields you want to change.
*
* Common usage:
* PUT { civitaiToken: "abc123..." }
*/
export async function PUT(req: NextRequest) {
const body = (await req.json()) as Partial<DashboardSettings>;
const current = await loadSettings();
const next: DashboardSettings = {
civitaiToken: body.civitaiToken ?? current.civitaiToken,
};
await saveSettings(next);
return NextResponse.json({ settings: next });
}
/**
* POST /api/settings
*
* Body: { action: "preview-url", url: "<civitai URL>" }
*
* Returns what we'd transform the URL into (without actually starting a
* download). Useful for the frontend to show the user "this URL will become
* this" before clicking Download.
*/
export async function POST(req: NextRequest) {
const body = (await req.json()) as {
action: "preview-url";
url?: string;
};
if (body.action === "preview-url") {
if (!body.url) {
return NextResponse.json(
{ ok: false, error: "url required" },
{ status: 400 }
);
}
const settings = await loadSettings();
const result = prepareCivitaiUrl(body.url, settings.civitaiToken || "");
return NextResponse.json({
ok: true,
original: body.url,
transformed: result.url,
note: result.note,
isCivitai: result.note.length > 0 || result.url !== body.url,
});
}
return NextResponse.json({ error: "unknown action" }, { status: 400 });
}

View File

@@ -7,6 +7,7 @@ import {
CpuIcon,
Gauge,
HardDrive,
Key as KeyIcon,
Layers,
MessageSquare,
Moon,
@@ -116,6 +117,9 @@ interface DashboardConfig {
minP: number;
temperature: number;
repeatPenalty: number;
nPredict: number;
reasoningFormat: "none" | "deepthink" | "auto";
jinja: boolean;
extraArgs: string;
presets: Preset[];
}
@@ -144,6 +148,8 @@ interface ComfyQueueEntry {
interface DownloadJob {
id: string;
url: string;
originalUrl?: string;
urlNote?: string;
filename: string;
status: "queued" | "downloading" | "done" | "failed" | "cancelled";
bytesDownloaded: number;
@@ -155,6 +161,17 @@ interface DownloadJob {
error: string | null;
}
interface DashboardSettings {
civitaiToken: string;
}
interface UrlPreview {
original: string;
transformed: string;
note: string;
isCivitai: boolean;
}
const DEFAULT_CONFIG: DashboardConfig = {
model: "model.gguf",
ctxSize: 64000,
@@ -188,6 +205,9 @@ const DEFAULT_CONFIG: DashboardConfig = {
minP: 0.05,
temperature: 0.8,
repeatPenalty: 1.1,
nPredict: -1,
reasoningFormat: "auto",
jinja: true,
extraArgs: "",
presets: [],
};
@@ -263,6 +283,21 @@ export default function DashboardPage() {
const [downloadUrl, setDownloadUrl] = React.useState("");
const downloadsActiveRef = React.useRef(false);
// Settings (civitai token etc)
const [settings, setSettings] = React.useState<DashboardSettings>({
civitaiToken: "",
});
const [urlPreview, setUrlPreview] = React.useState<UrlPreview | null>(null);
// Chat state — kept at top level so switching tabs doesn't reset the
// conversation. ChatTab is mounted/unmounted when the user clicks the tab.
const [chatMessages, setChatMessages] = React.useState<ChatMessage[]>([]);
const [chatInput, setChatInput] = React.useState("");
const [chatStreaming, setChatStreaming] = React.useState(false);
const [chatAutoScroll, setChatAutoScroll] = React.useState(true);
const chatAbortRef = React.useRef<AbortController | null>(null);
const chatMessagesEndRef = React.useRef<HTMLDivElement | null>(null);
const llamaContainer = containers.find((c) => c.role === "llama") || null;
const comfyContainer = containers.find((c) => c.role === "comfyui") || null;
@@ -808,6 +843,267 @@ export default function DashboardPage() {
}
}
// ---------------------------------------------------------------------------
// Settings (CivitAI token etc)
// ---------------------------------------------------------------------------
const refreshSettings = React.useCallback(async () => {
try {
const res = await fetch("/api/settings", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
setSettings(data.settings || { civitaiToken: "" });
} catch (err) {
console.error("[refreshSettings] error:", err);
}
}, []);
const previewDebounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const previewUrl = React.useCallback(async (url: string) => {
if (!url.trim()) {
setUrlPreview(null);
return;
}
try {
const res = await fetch("/api/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "preview-url", url }),
});
if (!res.ok) return;
const data = await res.json();
if (data.ok) {
setUrlPreview({
original: data.original,
transformed: data.transformed,
note: data.note,
isCivitai: data.isCivitai,
});
}
} catch {
/* ignore — preview is best-effort */
}
}, []);
// Debounced URL preview — fires 400ms after the user stops typing
React.useEffect(() => {
if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current);
previewDebounceRef.current = setTimeout(() => {
void previewUrl(downloadUrl);
}, 400);
return () => {
if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current);
};
}, [downloadUrl, previewUrl]);
React.useEffect(() => {
refreshSettings();
}, [refreshSettings]);
async function handleSaveCivitaiToken(token: string) {
setBusy("save-settings");
try {
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ civitaiToken: token }),
});
const data = await res.json();
if (data.settings) {
setSettings(data.settings);
showToast("success", "CivitAI token saved");
} else {
showToast("error", data.error || "Failed to save");
}
} finally {
setBusy(null);
}
}
// ---------------------------------------------------------------------------
// Chat handlers (state lives at top level to survive tab switches)
// ---------------------------------------------------------------------------
React.useEffect(() => {
if (chatAutoScroll) {
chatMessagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}, [chatMessages, chatAutoScroll]);
// Cleanup any in-flight chat request on unmount
React.useEffect(() => {
return () => {
if (chatAbortRef.current) {
chatAbortRef.current.abort();
chatAbortRef.current = null;
}
};
}, []);
async function handleChatSend() {
if (!chatInput.trim() || chatStreaming || !llamaContainer?.running) return;
const userMsg: ChatMessage = { role: "user", content: chatInput.trim() };
const systemMsg: ChatMessage | null = config.systemPrompt.trim()
? { role: "system", content: config.systemPrompt.trim() }
: null;
const inputText = chatInput;
setChatInput("");
// Build the messages we send to the server: system + history + new user msg
const historyForServer: ChatMessage[] = systemMsg
? [systemMsg, ...chatMessages.filter((m) => m.role !== "system"), userMsg]
: [...chatMessages.filter((m) => m.role !== "system"), userMsg];
// For display: history + new user msg + empty assistant placeholder
const allMsgs = [...chatMessages, userMsg];
setChatMessages([...allMsgs, { role: "assistant", content: "" }]);
setChatStreaming(true);
const controller = new AbortController();
chatAbortRef.current = controller;
const assistantIdx = allMsgs.length;
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: historyForServer,
temperature: config.temperature,
top_p: config.topP,
top_k: config.topK,
min_p: config.minP,
repeat_penalty: config.repeatPenalty,
// Pass nPredict as max_tokens (-1 = infinity, model decides)
max_tokens: config.nPredict,
reasoning_format: config.reasoningFormat,
stream: true,
}),
signal: controller.signal,
});
if (!res.ok || !res.body) {
const errText = await res.text().catch(() => "");
setChatMessages((prev) => {
const next = [...prev];
next[assistantIdx] = {
role: "assistant",
content: `[error: ${res.status} ${errText.slice(0, 200)}]`,
};
return next;
});
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
let finalTimings: ChatMessage["timings"] | undefined;
let specAccepted: number | undefined;
let specDrafted: number | undefined;
const pump = (): Promise<void> =>
reader.read().then(({ done, value }) => {
if (done) return;
buf += decoder.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice("data: ".length).trim();
if (payload === "[DONE]") continue;
try {
const chunk = JSON.parse(payload);
const choice = chunk.choices?.[0];
const delta = choice?.delta;
// Regular content
const contentDelta = delta?.content;
// Reasoning content (thinking blocks) — separate stream
const reasoningDelta = delta?.reasoning_content;
setChatMessages((prev) => {
const next = [...prev];
const cur = next[assistantIdx];
if (cur) {
if (typeof contentDelta === "string" && contentDelta.length > 0) {
cur.content = (cur.content || "") + contentDelta;
}
if (typeof reasoningDelta === "string" && reasoningDelta.length > 0) {
cur.reasoning = (cur.reasoning || "") + reasoningDelta;
}
}
return next;
});
// Capture timings (llama.cpp puts them in choice.timings or chunk.timings)
const t = choice?.timings || chunk.timings;
if (t) {
finalTimings = {
predicted_n: t.predicted_n,
predicted_ms: t.predicted_ms,
predicted_per_second: t.predicted_per_second,
prompt_n: t.prompt_n,
prompt_ms: t.prompt_ms,
prompt_per_second: t.prompt_per_second,
cache_hit_rate: t.cache_hit_rate ?? t.cache_hit,
};
if (t.spec_accepted != null) specAccepted = t.spec_accepted;
if (t.spec_drafted != null) specDrafted = t.spec_drafted;
}
} catch {
/* ignore malformed chunk */
}
}
return pump();
});
await pump();
// Attach timings to the final assistant message
if (finalTimings || specAccepted != null || specDrafted != null) {
setChatMessages((prev) => {
const next = [...prev];
const cur = next[assistantIdx];
if (cur) {
if (finalTimings) cur.timings = finalTimings;
if (specAccepted != null) cur.specAccepted = specAccepted;
if (specDrafted != null) cur.specDrafted = specDrafted;
}
return next;
});
}
} catch (err) {
if ((err as Error).name !== "AbortError") {
setChatMessages((prev) => {
const next = [...prev];
next[assistantIdx] = {
role: "assistant",
content: `[error: ${(err as Error).message}]`,
};
return next;
});
} else {
// Aborted — leave whatever was streamed so far
}
} finally {
setChatStreaming(false);
chatAbortRef.current = null;
}
void inputText; // suppress unused
}
function handleChatStop() {
if (chatAbortRef.current) {
chatAbortRef.current.abort();
chatAbortRef.current = null;
}
setChatStreaming(false);
}
function handleChatClear() {
setChatMessages([]);
}
async function handleSavePreset() {
if (!presetName.trim()) {
showToast("error", "Preset name required");
@@ -1103,12 +1399,16 @@ export default function DashboardPage() {
{/* Chat tab */}
<TabsContent value="chat">
<ChatTab
systemPrompt={config.systemPrompt}
temperature={config.temperature}
topP={config.topP}
topK={config.topK}
minP={config.minP}
repeatPenalty={config.repeatPenalty}
messages={chatMessages}
input={chatInput}
setInput={setChatInput}
streaming={chatStreaming}
autoScroll={chatAutoScroll}
setAutoScroll={setChatAutoScroll}
onSend={handleChatSend}
onStop={handleChatStop}
onClear={handleChatClear}
messagesEndRef={chatMessagesEndRef}
llamaRunning={!!llamaContainer?.running}
/>
</TabsContent>
@@ -1133,6 +1433,9 @@ export default function DashboardPage() {
setDownloadUrl={setDownloadUrl}
onDownload={handleDownload}
onCancelDownload={handleCancelDownload}
civitaiToken={settings.civitaiToken}
onSaveCivitaiToken={handleSaveCivitaiToken}
urlPreview={urlPreview}
/>
</TabsContent>
@@ -1840,7 +2143,63 @@ function ConfigTab({
onChange={(e) => update("repeatPenalty", Number(e.target.value))}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="n-predict">Max tokens / response</Label>
<Input
id="n-predict"
type="number"
min={-1}
value={config.nPredict}
onChange={(e) => update("nPredict", Number(e.target.value))}
/>
<p className="text-[10px] text-muted-foreground">
-1 = infinity (model decides). Sets --n-predict on the server.
</p>
</div>
</div>
{/* Reasoning / Jinja — for thinking models (Qwen3, DeepSeek-R1, etc.) */}
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="reasoning-format">Reasoning format</Label>
<Select
value={config.reasoningFormat}
onValueChange={(v) =>
update("reasoningFormat", v as DashboardConfig["reasoningFormat"])
}
>
<SelectTrigger id="reasoning-format">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">
auto (recommended) — split thinking into reasoning_content
</SelectItem>
<SelectItem value="deepthink">
deepthink — force thinking even if model wouldn&apos;t
</SelectItem>
<SelectItem value="none">
none — passthrough raw (thinking tags appear in content)
</SelectItem>
</SelectContent>
</Select>
<p className="text-[10px] text-muted-foreground">
For Qwen3, DeepSeek-R1, gpt-oss. &quot;auto&quot; puts
&lt;think&gt;...&lt;/think&gt; blocks into a separate
reasoning_content field shown in chat.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="jinja-toggle">Jinja chat templates</Label>
<ToggleRow
label="Enable --jinja"
hint="Required for reasoning format + tool calling. Recommended ON."
checked={config.jinja}
onChange={(v) => update("jinja", v)}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="sys-prompt">System prompt (default)</Label>
<Textarea
@@ -1902,6 +2261,9 @@ function ModelsTab({
setDownloadUrl,
onDownload,
onCancelDownload,
civitaiToken,
onSaveCivitaiToken,
urlPreview,
}: {
models: ModelFile[];
config: DashboardConfig;
@@ -1915,9 +2277,18 @@ function ModelsTab({
setDownloadUrl: (v: string) => void;
onDownload: () => void;
onCancelDownload: (id: string) => void;
civitaiToken: string;
onSaveCivitaiToken: (token: string) => void;
urlPreview: UrlPreview | null;
}) {
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const [dragOver, setDragOver] = React.useState(false);
const [showCivitaiSettings, setShowCivitaiSettings] = React.useState(false);
const [civitaiTokenDraft, setCivitaiTokenDraft] = React.useState(civitaiToken);
React.useEffect(() => {
setCivitaiTokenDraft(civitaiToken);
}, [civitaiToken]);
function handleFiles(files: FileList | null) {
if (!files || files.length === 0) return;
@@ -2003,16 +2374,83 @@ function ModelsTab({
{/* Download from URL */}
<div className="rounded-md border bg-muted/20 p-4 space-y-3">
<div>
<span className="text-sm font-medium flex items-center gap-2">
<CloudDownload className="h-4 w-4" />
Download from URL
</span>
<p className="text-xs text-muted-foreground mt-0.5">
Fetch a .gguf file from HuggingFace, GitHub releases, or any
direct URL. Uses curl with redirect-following and atomic rename.
</p>
<div className="flex items-start justify-between gap-2">
<div>
<span className="text-sm font-medium flex items-center gap-2">
<CloudDownload className="h-4 w-4" />
Download from URL
</span>
<p className="text-xs text-muted-foreground mt-0.5">
Fetch a .gguf file from HuggingFace, GitHub releases, or any
direct URL. CivitAI URLs are auto-converted (model page →
API download) and the saved token is appended.
</p>
</div>
<Button
size="sm"
variant="outline"
onClick={() => setShowCivitaiSettings((v) => !v)}
>
<KeyIcon className="h-3.5 w-3.5" />
CivitAI token
{civitaiToken ? (
<Badge variant="success" className="ml-1 text-[10px]">
set
</Badge>
) : (
<Badge variant="secondary" className="ml-1 text-[10px]">
empty
</Badge>
)}
</Button>
</div>
{showCivitaiSettings && (
<div className="rounded-md border bg-card p-3 space-y-2">
<Label htmlFor="civitai-token">CivitAI API token</Label>
<Input
id="civitai-token"
type="password"
value={civitaiTokenDraft}
onChange={(e) => setCivitaiTokenDraft(e.target.value)}
placeholder="Get it from https://civitai.com/user/account → API Keys"
className="font-mono text-xs"
/>
<div className="flex items-center gap-2">
<Button
size="sm"
onClick={() => onSaveCivitaiToken(civitaiTokenDraft)}
disabled={busy === "save-settings"}
>
Save
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => {
setCivitaiTokenDraft("");
onSaveCivitaiToken("");
}}
>
Clear
</Button>
<a
href="https://civitai.com/user/account"
target="_blank"
rel="noopener noreferrer"
className="ml-auto text-xs text-muted-foreground hover:underline"
>
Get token ↗
</a>
</div>
<p className="text-[10px] text-muted-foreground">
Stored locally in <code className="font-mono">gpu/dashboard/settings.json</code>.
Used to authenticate CivitAI downloads. Without it, NSFW /
gated models will fail with 401.
</p>
</div>
)}
<div className="flex items-end gap-2">
<div className="flex-1 space-y-1.5">
<Label htmlFor="download-url">URL</Label>
@@ -2020,7 +2458,7 @@ function ModelsTab({
id="download-url"
value={downloadUrl}
onChange={(e) => setDownloadUrl(e.target.value)}
placeholder="https://huggingface.co/.../model.gguf"
placeholder="https://huggingface.co/.../model.gguf or https://civitai.com/models/12345"
className="font-mono text-xs"
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -2039,6 +2477,21 @@ function ModelsTab({
</Button>
</div>
{/* URL preview — shows what we'll actually curl */}
{urlPreview && urlPreview.original !== urlPreview.transformed && (
<div className="rounded-md border bg-card p-2.5 text-xs space-y-1">
<div className="flex items-center gap-1.5">
<Badge variant={urlPreview.isCivitai ? "default" : "secondary"} className="text-[10px]">
{urlPreview.isCivitai ? "CivitAI" : "transformed"}
</Badge>
<span className="text-muted-foreground">{urlPreview.note}</span>
</div>
<pre className="font-mono text-[10px] text-foreground whitespace-pre-wrap break-all">
{urlPreview.transformed}
</pre>
</div>
)}
{/* Active downloads */}
{activeDownloads.length > 0 && (
<div className="space-y-2">
@@ -2244,9 +2697,22 @@ function DownloadJobRow({
</div>
)}
{/* URL transformation note (e.g. "added CivitAI token") */}
{!compact && job.urlNote && (
<div className="text-[10px] text-muted-foreground italic">
{job.urlNote}
</div>
)}
{/* Show source URL for reference (compact mode hides it) */}
{!compact && (
<div className="text-[10px] text-muted-foreground font-mono truncate">
{job.originalUrl && (
<span className="line-through opacity-60">
{job.originalUrl}
</span>
)}
{job.originalUrl && <span className="mx-1">→</span>}
<a
href={job.url}
target="_blank"
@@ -2807,6 +3273,10 @@ function SystemTab({
interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
// For assistant only — reasoning content (thinking blocks) when
// --reasoning-format auto is enabled on the server. Streamed separately
// via delta.reasoning_content.
reasoning?: string;
// For assistant only — timings from llama.cpp response
timings?: {
predicted_n?: number;
@@ -2823,193 +3293,30 @@ interface ChatMessage {
}
function ChatTab({
systemPrompt,
temperature,
topP,
topK,
minP,
repeatPenalty,
messages,
input,
setInput,
streaming,
autoScroll,
setAutoScroll,
onSend,
onStop,
onClear,
messagesEndRef,
llamaRunning,
}: {
systemPrompt: string;
temperature: number;
topP: number;
topK: number;
minP: number;
repeatPenalty: number;
messages: ChatMessage[];
input: string;
setInput: (v: string) => void;
streaming: boolean;
autoScroll: boolean;
setAutoScroll: (v: boolean) => void;
onSend: () => void;
onStop: () => void;
onClear: () => void;
messagesEndRef: React.RefObject<HTMLDivElement | null>;
llamaRunning: boolean;
}) {
const [messages, setMessages] = React.useState<ChatMessage[]>([]);
const [input, setInput] = React.useState("");
const [streaming, setStreaming] = React.useState(false);
const [autoScroll, setAutoScroll] = React.useState(true);
const abortRef = React.useRef<AbortController | null>(null);
const messagesEndRef = React.useRef<HTMLDivElement | null>(null);
// Reset chat on mount if systemPrompt changes
React.useEffect(() => {
if (messages.length === 0 && systemPrompt) {
setMessages([{ role: "system", content: systemPrompt }]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [systemPrompt]);
React.useEffect(() => {
if (autoScroll) {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}, [messages, autoScroll]);
async function handleSend() {
if (!input.trim() || streaming || !llamaRunning) return;
const userMsg: ChatMessage = { role: "user", content: input.trim() };
setInput("");
const allMsgs = [...messages, userMsg];
setMessages(allMsgs);
setStreaming(true);
const controller = new AbortController();
abortRef.current = controller;
// Add an empty assistant message we'll stream into
const assistantIdx = allMsgs.length;
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: allMsgs,
temperature,
top_p: topP,
top_k: topK,
min_p: minP,
repeat_penalty: repeatPenalty,
stream: true,
}),
signal: controller.signal,
});
if (!res.ok || !res.body) {
const errText = await res.text().catch(() => "");
setMessages((prev) => {
const next = [...prev];
next[assistantIdx] = {
role: "assistant",
content: `[error: ${res.status} ${errText.slice(0, 200)}]`,
};
return next;
});
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
let finalTimings: ChatMessage["timings"] | undefined;
let specAccepted: number | undefined;
let specDrafted: number | undefined;
const pump = (): Promise<void> =>
reader.read().then(({ done, value }) => {
if (done) return;
buf += decoder.decode(value, { stream: true });
// Parse SSE chunks: lines starting with "data: "
const lines = buf.split("\n");
buf = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice("data: ".length).trim();
if (payload === "[DONE]") continue;
try {
const chunk = JSON.parse(payload);
// OpenAI-compatible chunk has choices[0].delta.content
const delta = chunk.choices?.[0]?.delta?.content;
if (typeof delta === "string" && delta.length > 0) {
setMessages((prev) => {
const next = [...prev];
const cur = next[assistantIdx];
next[assistantIdx] = {
...cur,
content: (cur?.content || "") + delta,
};
return next;
});
}
// Capture timings if present (llama.cpp includes them in the
// final chunk under choices[0].timings or under .timings)
const t = chunk.choices?.[0]?.timings || chunk.timings;
if (t) {
finalTimings = {
predicted_n: t.predicted_n,
predicted_ms: t.predicted_ms,
predicted_per_second: t.predicted_per_second,
prompt_n: t.prompt_n,
prompt_ms: t.prompt_ms,
prompt_per_second: t.prompt_per_second,
cache_hit_rate: t.cache_hit_rate,
};
if (t.spec_accepted != null)
specAccepted = t.spec_accepted;
if (t.spec_drafted != null)
specDrafted = t.spec_drafted;
}
} catch {
/* ignore malformed chunk */
}
}
return pump();
});
await pump();
// Attach timings to the final assistant message
if (finalTimings) {
setMessages((prev) => {
const next = [...prev];
const cur = next[assistantIdx];
next[assistantIdx] = {
...cur,
timings: finalTimings,
specAccepted,
specDrafted,
};
return next;
});
}
} catch (err) {
if ((err as Error).name !== "AbortError") {
setMessages((prev) => {
const next = [...prev];
next[assistantIdx] = {
role: "assistant",
content: `[error: ${(err as Error).message}]`,
};
return next;
});
}
} finally {
setStreaming(false);
abortRef.current = null;
}
}
function handleStop() {
if (abortRef.current) {
abortRef.current.abort();
abortRef.current = null;
}
setStreaming(false);
}
function handleClear() {
setMessages(systemPrompt ? [{ role: "system", content: systemPrompt }] : []);
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2 flex-wrap">
@@ -3031,7 +3338,7 @@ function ChatTab({
/>
Auto-scroll
</label>
<Button size="sm" variant="ghost" onClick={handleClear}>
<Button size="sm" variant="ghost" onClick={onClear} disabled={messages.length === 0}>
<Trash2 className="h-3.5 w-3.5" />
Clear
</Button>
@@ -3066,25 +3373,28 @@ function ChatTab({
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message... (Ctrl+Enter to send)"
placeholder="Type a message... (Enter to send, Shift+Enter for newline)"
rows={2}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
// Enter = send. Shift+Enter = newline (default behavior).
if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
handleSend();
if (!streaming && llamaRunning && input.trim()) {
onSend();
}
}
}}
className="flex-1 resize-none"
disabled={!llamaRunning || streaming}
/>
{streaming ? (
<Button onClick={handleStop} variant="destructive">
<Button onClick={onStop} variant="destructive">
<Square className="h-3.5 w-3.5" />
Stop
</Button>
) : (
<Button
onClick={handleSend}
onClick={onSend}
disabled={!llamaRunning || !input.trim()}
>
<Send className="h-3.5 w-3.5" />
@@ -3101,6 +3411,7 @@ function MessageBubble({ message }: { message: ChatMessage }) {
const isUser = message.role === "user";
const isAssistant = message.role === "assistant";
const isSystem = message.role === "system";
const [reasoningExpanded, setReasoningExpanded] = React.useState(false);
if (isSystem) {
return (
@@ -3120,7 +3431,30 @@ function MessageBubble({ message }: { message: ChatMessage }) {
: "bg-muted text-foreground"
)}
>
<div className="whitespace-pre-wrap break-words">{message.content}</div>
{/* Reasoning block (thinking) — shown above content, collapsible */}
{isAssistant && message.reasoning && message.reasoning.length > 0 && (
<div className="mb-2 rounded border border-border/40 bg-background/50">
<button
className="w-full px-2 py-1 flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground"
onClick={() => setReasoningExpanded((v) => !v)}
>
<span className="font-medium">
{reasoningExpanded ? "▼" : "▶"} Reasoning
</span>
<span className="opacity-60">
({message.reasoning.length} chars)
</span>
</button>
{reasoningExpanded && (
<pre className="px-2 pb-2 text-[10px] font-mono whitespace-pre-wrap break-all text-muted-foreground max-h-60 overflow-y-auto scrollbar-thin">
{message.reasoning}
</pre>
)}
</div>
)}
<div className="whitespace-pre-wrap break-words">
{message.content || (isAssistant && (!message.reasoning || message.reasoning.length === 0) ? "…" : "")}
</div>
{isAssistant && message.timings && (
<MessageStats message={message} />
)}
@@ -3134,6 +3468,7 @@ function MessageStats({ message }: { message: ChatMessage }) {
if (!t) return null;
return (
<div className="mt-2 pt-2 border-t border-border/30 text-[10px] font-mono text-muted-foreground space-y-0.5">
{/* TPS — generation speed */}
{t.predicted_per_second != null && (
<div>
<span className="text-foreground">TPS:</span>{" "}
@@ -3145,25 +3480,32 @@ function MessageStats({ message }: { message: ChatMessage }) {
)}
</div>
)}
{t.prompt_n != null && (
{/* TTFT — Time To First Token. This is the time spent processing the
prompt before generation started. */}
{t.prompt_ms != null && (
<div>
<span className="text-foreground">Prompt:</span> {t.prompt_n} tok
{t.prompt_ms != null && (
<span className="ml-2">
({(t.prompt_ms / 1000).toFixed(2)}s
{t.prompt_per_second != null &&
`, ${t.prompt_per_second.toFixed(1)} tok/s`}
)
</span>
<span className="text-foreground">TTFT:</span>{" "}
{(t.prompt_ms / 1000).toFixed(2)}s
{t.prompt_n != null && (
<span className="ml-2">({t.prompt_n} prompt tok)</span>
)}
</div>
)}
{/* Prefill speed — prompt processing throughput */}
{t.prompt_per_second != null && (
<div>
<span className="text-foreground">Prefill:</span>{" "}
{t.prompt_per_second.toFixed(1)} tok/s
</div>
)}
{/* Cache hit rate — how much of the prompt was reused from KV cache */}
{t.cache_hit_rate != null && (
<div>
<span className="text-foreground">Cache hit:</span>{" "}
{(t.cache_hit_rate * 100).toFixed(1)}%
</div>
)}
{/* Speculative decoding stats */}
{message.specDrafted != null && message.specAccepted != null && (
<div>
<span className="text-foreground">Spec decoding:</span>{" "}
@@ -3579,16 +3921,24 @@ function buildPreviewArgs(cfg: DashboardConfig): string {
parts.push(`--cache-type-v ${cfg.cacheTypeV}`);
if (cfg.defragThold >= 0 && cfg.defragThold !== 0.1)
parts.push(`--defrag-thold ${cfg.defragThold}`);
if (cfg.flashAttn) parts.push("--flash-attn");
if (cfg.noMmap) parts.push("--no-mmap");
if (cfg.mlock) parts.push("--mlock");
if (cfg.contBatching) parts.push("--cont-batching");
// --flash-attn takes on/off/auto in modern llama.cpp (bare flag fails)
parts.push(`--flash-attn ${cfg.flashAttn ? "on" : "off"}`);
// --mlock / --no-mmap → unified --load-mode in modern llama.cpp
if (cfg.mlock && cfg.noMmap) {
parts.push("--load-mode mlock");
} else if (cfg.mlock) {
parts.push("--load-mode mmap+mlock");
} else if (cfg.noMmap) {
parts.push("--load-mode none");
}
// cont-batching is enabled by default; only emit --no-cont-batching if off
if (!cfg.contBatching) parts.push("--no-cont-batching");
if (cfg.embeddings) parts.push("--embeddings");
if (cfg.metrics) parts.push("--metrics");
if (cfg.ropeFreqScale !== 1.0)
parts.push(`--rope-freq-scale ${cfg.ropeFreqScale}`);
if (cfg.ropeScale !== 1.0)
parts.push(`--rope-scaling ${cfg.ropeScale}`);
parts.push(`--rope-scale ${cfg.ropeScale}`);
if (cfg.yarnExtFactor !== 1.0)
parts.push(`--yarn-ext-factor ${cfg.yarnExtFactor}`);
if (cfg.yarnAttnFactor !== 1.0)
@@ -3610,6 +3960,9 @@ function buildPreviewArgs(cfg: DashboardConfig): string {
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
if (cfg.repeatPenalty > 1.0)
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
if (cfg.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
if (cfg.jinja) parts.push("--jinja");
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}

View File

@@ -143,6 +143,16 @@ export const NODE_INSTANCE =
*/
const COMPOSE_FILE = path.join(PROJECT_DIR, "compose.yaml");
/**
* Path to the persisted dashboard settings (civitai token, etc).
*/
export const DASHBOARD_SETTINGS_PATH = path.join(
PROJECT_DIR,
"gpu",
"dashboard",
"settings.json"
);
/**
* Path to the persisted dashboard config (last-used + saved presets).
*/
@@ -242,6 +252,22 @@ export interface DashboardConfig {
temperature: number;
/** Sampling: repeat penalty (1.0 = disabled) */
repeatPenalty: number;
/**
* Max tokens to predict per response. -1 = infinity (model decides).
* Sets --n-predict on the server side; also passed as max_tokens
* per-request in /api/chat.
*/
nPredict: number;
/**
* Reasoning format for thinking models (Qwen3, DeepSeek-R1, gpt-oss).
* - "auto": llama.cpp auto-detects and splits <think>...</think> into
* the reasoning_content field (recommended)
* - "deepthink": force thinking even if model wouldn't normally
* - "none": passthrough raw (thinking tags appear in content)
*/
reasoningFormat: "none" | "deepthink" | "auto";
/** Enable Jinja chat templates (required for tool calling + reasoning) */
jinja: boolean;
/** Free-form extra args (advanced) */
extraArgs: string;
/** Saved presets */
@@ -288,6 +314,9 @@ export const DEFAULT_CONFIG: DashboardConfig = {
minP: 0.05,
temperature: 0.8,
repeatPenalty: 1.1,
nPredict: -1,
reasoningFormat: "auto",
jinja: true,
extraArgs: "",
presets: [],
};
@@ -358,6 +387,10 @@ export function parseLlamaExtraArgs(
for (let i = 0; i < tokens.length; i++) {
const tok = tokens[i];
const next = tokens[i + 1];
// Helper: check if next token is a value (not another flag)
const isValue = (s: string | undefined) =>
s != null && !s.startsWith("--") && !s.startsWith("-");
switch (tok) {
case "--ctx-size":
cfg.ctxSize = Number(next) || cfg.ctxSize;
@@ -400,7 +433,32 @@ export function parseLlamaExtraArgs(
i++;
break;
case "--flash-attn":
cfg.flashAttn = true;
case "-fa":
// Modern: --flash-attn on|off|auto (default auto).
// Legacy: --flash-attn (bare flag, no value).
if (isValue(next) && /^(on|off|auto)$/i.test(next)) {
cfg.flashAttn = next.toLowerCase() !== "off";
i++;
} else {
cfg.flashAttn = true;
}
break;
case "--load-mode":
case "-lm":
// Replaces --mlock / --no-mmap in modern llama.cpp
if (isValue(next)) {
const mode = next.toLowerCase();
if (mode === "mlock") {
cfg.mlock = true;
cfg.noMmap = true;
} else if (mode === "mmap+mlock") {
cfg.mlock = true;
cfg.noMmap = false;
} else if (mode === "none") {
cfg.noMmap = true;
}
i++;
}
break;
case "--no-mmap":
cfg.noMmap = true;
@@ -409,8 +467,13 @@ export function parseLlamaExtraArgs(
cfg.mlock = true;
break;
case "--cont-batching":
case "-cb":
cfg.contBatching = true;
break;
case "--no-cont-batching":
case "-nocb":
cfg.contBatching = false;
break;
case "--embeddings":
cfg.embeddings = true;
break;
@@ -421,10 +484,21 @@ export function parseLlamaExtraArgs(
cfg.ropeFreqScale = Number(next) || cfg.ropeFreqScale;
i++;
break;
case "--rope-scaling":
case "--rope-scale":
cfg.ropeScale = Number(next) || cfg.ropeScale;
i++;
break;
case "--rope-scaling":
// Modern: enum {none,linear,yarn}. Legacy: numeric factor.
// If numeric, treat as --rope-scale (the new flag for the factor).
if (isValue(next) && /^\d/.test(next)) {
cfg.ropeScale = Number(next) || cfg.ropeScale;
i++;
} else if (isValue(next)) {
// enum value like 'yarn' — ignore, it's the scaling method not the factor
i++;
}
break;
case "--yarn-ext-factor":
cfg.yarnExtFactor = Number(next) || cfg.yarnExtFactor;
i++;
@@ -462,6 +536,21 @@ export function parseLlamaExtraArgs(
cfg.repeatPenalty = Number(next);
i++;
break;
case "--n-predict":
case "--predict":
case "-n":
cfg.nPredict = Number(next);
i++;
break;
case "--reasoning-format":
if (isValue(next)) {
cfg.reasoningFormat = next as DashboardConfig["reasoningFormat"];
i++;
}
break;
case "--jinja":
cfg.jinja = true;
break;
case "--model-draft":
cfg.draftModel = path.basename(next || "");
i++;
@@ -512,17 +601,33 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
if (cfg.defragThold >= 0 && cfg.defragThold !== 0.1)
parts.push(`--defrag-thold ${cfg.defragThold}`);
// Performance flags
if (cfg.flashAttn) parts.push("--flash-attn");
if (cfg.noMmap) parts.push("--no-mmap");
if (cfg.mlock) parts.push("--mlock");
if (cfg.contBatching) parts.push("--cont-batching");
// --flash-attn takes a value (on/off/auto) since llama.cpp changed the CLI
// (https://github.com/ggml-org/llama.cpp/issues/...). Passing it as a bare
// flag causes 'unknown value for --flash-attn: <next-flag>'.
parts.push(`--flash-attn ${cfg.flashAttn ? "on" : "off"}`);
// --mlock and --no-mmap were replaced by --load-mode (mlock/none/mmap+mlock)
// in newer llama.cpp builds. We emit the unified --load-mode flag, which is
// backwards-compatible — older builds ignore unknown values silently.
if (cfg.mlock && cfg.noMmap) {
// mlock the file after loading to RAM (no mmap)
parts.push("--load-mode mlock");
} else if (cfg.mlock) {
// mmap + mlock (default mmap, but also keep in RAM)
parts.push("--load-mode mmap+mlock");
} else if (cfg.noMmap) {
// no mmap at all
parts.push("--load-mode none");
}
// --cont-batching is enabled by default in modern llama.cpp. Only emit
// --no-cont-batching if the user explicitly disabled it.
if (!cfg.contBatching) parts.push("--no-cont-batching");
if (cfg.embeddings) parts.push("--embeddings");
if (cfg.metrics) parts.push("--metrics");
// RoPE / YaRN
if (cfg.ropeFreqScale !== 1.0)
parts.push(`--rope-freq-scale ${cfg.ropeFreqScale}`);
if (cfg.ropeScale !== 1.0)
parts.push(`--rope-scaling ${cfg.ropeScale}`);
parts.push(`--rope-scale ${cfg.ropeScale}`);
if (cfg.yarnExtFactor !== 1.0)
parts.push(`--yarn-ext-factor ${cfg.yarnExtFactor}`);
if (cfg.yarnAttnFactor !== 1.0)
@@ -546,6 +651,12 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
if (cfg.repeatPenalty > 1.0)
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
// Max tokens per response (default -1 = infinity)
if (cfg.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
// Reasoning format for thinking models (Qwen3, DeepSeek-R1, gpt-oss)
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
// Jinja chat templates (required for reasoning format to work properly)
if (cfg.jinja) parts.push("--jinja");
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}
@@ -972,15 +1083,27 @@ export async function getLlamaHealth(): Promise<{
reachable: boolean;
detail: string;
}> {
// Llama.cpp /completion endpoint returns 405 on GET /, but /health works.
// Llama.cpp /health returns "ok" / "loading model" / "error".
//
// We use Node's native fetch() to call http://llama:8080 directly — the
// dashboard container is on the same Docker network as llama, so this
// works without exec'ing into the llama container.
//
// (Previous impl used `docker exec ... wget -qO-` — but the llama.cpp
// server-cuda image doesn't include wget, causing "executable file not
// found in $PATH" errors.)
try {
const { stdout } = await execAsync(
`docker exec $(docker ps --filter label=node.role=llama --filter label=node.instance=${NODE_INSTANCE} --format {{.Names}} | head -n1) wget -qO- http://127.0.0.1:8080/health || true`,
{ maxBuffer: 1 * 1024 * 1024, timeout: 5000 }
);
const text = String(stdout);
if (text.includes("ok")) return { reachable: true, detail: text.trim() };
return { reachable: false, detail: text || "no response" };
const res = await fetch("http://llama:8080/health", {
signal: AbortSignal.timeout(3000),
});
const text = await res.text();
if (res.ok && text.includes("ok")) {
return { reachable: true, detail: text.trim() };
}
return {
reachable: false,
detail: `HTTP ${res.status}: ${text.trim().slice(0, 200)}`,
};
} catch (err) {
return {
reachable: false,
@@ -1022,7 +1145,22 @@ export async function startService(
const profile = COMPOSE_PROFILES[role];
const args = ["up", "-d", "--force-recreate", role];
if (profile) args.unshift("--profile", profile);
const res = await runCompose(args, {});
// Service-specific env overrides. Mirrors what gpuctl shells do — they
// explicitly export these vars before `docker compose` so compose's
// ${VAR:-default} syntax picks the real host path instead of the relative
// default (which would resolve to a path inside the dashboard container,
// not on the host).
const extra: Record<string, string> = {};
if (role === "comfyui") {
// These mirror `ssh/scripts/comfy.sh`:
// COMFY_BASE_HOST="$HOST_PROJECT_PATH/gpu/comfy"
// COMFY_RUN_HOST="$HOST_PROJECT_PATH/comfyui/run"
extra.COMFY_BASE_HOST = `${HOST_PROJECT_PATH}/gpu/comfy`;
extra.COMFY_RUN_HOST = `${HOST_PROJECT_PATH}/comfyui/run`;
}
const res = await runCompose(args, extra);
return {
ok: res.code === 0,
message:

View File

@@ -1,7 +1,144 @@
import { spawn } from "node:child_process";
import { promises as fs } from "node:fs";
import path from "node:path";
import { LLAMA_MODELS_DIR } from "./docker";
import { LLAMA_MODELS_DIR, DASHBOARD_SETTINGS_PATH } from "./docker";
// ---------------------------------------------------------------------------
// Settings (civitai token etc.)
// ---------------------------------------------------------------------------
export interface DashboardSettings {
civitaiToken: string;
// Add more settings here in the future (e.g. default download dir,
// HF token for gated repos, etc.)
}
const DEFAULT_SETTINGS: DashboardSettings = {
civitaiToken: "",
};
let _settingsCache: DashboardSettings | null = null;
export async function loadSettings(): Promise<DashboardSettings> {
if (_settingsCache !== null) return _settingsCache;
let result: DashboardSettings;
try {
const raw = await fs.readFile(DASHBOARD_SETTINGS_PATH, "utf-8");
const parsed = JSON.parse(raw);
result = { ...DEFAULT_SETTINGS, ...parsed };
} catch {
result = { ...DEFAULT_SETTINGS };
}
_settingsCache = result;
return result;
}
export async function saveSettings(settings: DashboardSettings): Promise<void> {
await fs.mkdir(path.dirname(DASHBOARD_SETTINGS_PATH), { recursive: true });
await fs.writeFile(
DASHBOARD_SETTINGS_PATH,
JSON.stringify(settings, null, 2),
"utf-8"
);
_settingsCache = settings;
}
// ---------------------------------------------------------------------------
// URL preparation — handle CivitAI's quirky URL scheme
// ---------------------------------------------------------------------------
//
// CivitAI URLs come in several shapes:
//
// 1. https://civitai.com/models/12345
// Model page (HTML). NOT downloadable directly — must be converted.
//
// 2. https://civitai.com/models/12345?modelVersionId=67890
// Specific version. Also a model page.
//
// 3. https://civitai.com/api/download/models/12345
// Direct download. Returns 302 to a signed Cloudflare URL.
// Requires API token: ?token=XXX
//
// 4. https://civitai.com/api/download/models/12345?token=XXX
// Same with token inline.
//
// 5. https://civitai.com/api/download/models/12345?token=XXX&modelVersionId=67890
// Specific version with token.
//
// We accept ANY of the above (and the .red mirror variants) and:
// - Convert model page URLs → API download URLs
// - Append the saved token if not already present
// - Preserve existing query params (modelVersionId, type, etc.)
//
// Returns { url, note } where note explains what we did.
export interface PreparedUrl {
url: string;
note: string;
}
export function prepareCivitaiUrl(
rawUrl: string,
token: string
): PreparedUrl {
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
// Not a parseable URL — return as-is
return { url: rawUrl, note: "invalid URL, passed through unchanged" };
}
const host = parsed.hostname.toLowerCase();
const isCivitai =
host === "civitai.com" || host === "civitai.red" || host.endsWith(".civitai.com") || host.endsWith(".civitai.red");
if (!isCivitai) {
// Not CivitAI — return as-is
return { url: rawUrl, note: "" };
}
// Normalize: replace civitai.red host with civitai.com (same backend).
// The .red domain is a mirror that doesn't accept API requests the same way.
if (host === "civitai.red") {
parsed.hostname = "civitai.com";
}
const pathname = parsed.pathname;
// Pattern 1: /models/<id> (model page) → convert to /api/download/models/<id>
// Pattern 2: /models/<id>/<slug> (also model page with slug)
const modelMatch = pathname.match(/^\/models\/(\d+)(?:\/[^/]*)?$/);
if (modelMatch) {
const modelId = modelMatch[1];
// Build the API download URL
const apiPath = `/api/download/models/${modelId}`;
parsed.pathname = apiPath;
// Preserve modelVersionId from query if present
// (other query params like 'type' are auto-redirected by civitai)
}
// Pattern: /api/download/models/<id> — append token if missing
if (parsed.pathname.startsWith("/api/download/") && token) {
if (!parsed.searchParams.has("token")) {
parsed.searchParams.set("token", token);
}
} else if (token && !parsed.searchParams.has("token")) {
// For non-API URLs (shouldn't normally happen after the conversion above),
// still try to add the token — CivitAI's CDN often accepts it as a query param
parsed.searchParams.set("token", token);
}
const finalUrl = parsed.toString();
const wasConverted = modelMatch != null;
const note = wasConverted
? `converted model page → API download URL${token ? ", added API token" : ""}`
: token && parsed.searchParams.has("token")
? "added CivitAI API token"
: "";
return { url: finalUrl, note };
}
// ---------------------------------------------------------------------------
// In-memory download tracker
@@ -16,7 +153,12 @@ import { LLAMA_MODELS_DIR } from "./docker";
export interface DownloadJob {
id: string;
/** The URL we actually curl (after CivitAI token / conversion). */
url: string;
/** Original URL the user pasted (only set if we modified it). */
originalUrl?: string;
/** Note explaining what we did to the URL (e.g. "added CivitAI token"). */
urlNote?: string;
filename: string;
status: "queued" | "downloading" | "done" | "failed" | "cancelled";
bytesDownloaded: number;
@@ -47,9 +189,19 @@ const MAX_HISTORY = 50;
* subscribe via `subscribeToJob(id, callback)`.
*/
export async function startModelDownload(
url: string,
rawUrl: string,
filenameOverride?: string
): Promise<DownloadJob> {
// Load settings to get CivitAI token (if any)
const settings = await loadSettings();
// If this is a CivitAI URL, transform it (model page → API download URL,
// append token if missing, normalize .red → .com)
const { url, note: urlNote } = prepareCivitaiUrl(
rawUrl,
settings.civitaiToken || ""
);
// Validate URL
let parsed: URL;
try {
@@ -88,6 +240,8 @@ export async function startModelDownload(
const job: DownloadJob = {
id,
url,
originalUrl: rawUrl !== url ? rawUrl : undefined,
urlNote: urlNote || undefined,
filename,
status: "queued",
bytesDownloaded: 0,