Compare commits

...

8 Commits

Author SHA1 Message Date
Z User
3275af09e9 fix: Perf tab field mapping + TTS service (openedai-speech) + v0.7.0
## 1. Perf tab — fixed based on actual /props + /slots JSON

User provided raw JSON showing the real field names:
- default_generation_settings.params.temperature (NOT .temperature)
- modalities.vision (NOT has_multimodal)
- default_generation_settings.n_ctx (NOT n_context)
- slots: n_prompt_tokens / n_prompt_tokens_processed / n_prompt_tokens_cache
- slots: next_token[0].n_decoded / n_remain
- slots: NO timings field (only available in chat completions)
- slots: speculative boolean (not spec object)

**Fix:**
- SlotInfo interface extended with all new fields
- OverviewView: extracts gen from dgs.params (nested), checks modalities.vision,
  uses dgs.n_ctx for total ctx, shows build_info, shows speculative status
- SlotsView: uses n_prompt_tokens_processed (newer) ?? n_past (legacy)
  for ctx display, shows n_prompt_tokens + n_prompt_tokens_cache,
  shows next_token decoded/remaining when no timings,
  shows speculative badge
- Sampling values now use .toFixed(2) for readability
- Raw JSON dump section preserved (useful for future field changes)

## 2. TTS service (openedai-speech)

Added OpenAI-compatible TTS service using openedai-speech:
- compose.yaml: new 'tts' service with profile 'tts'
  - image: ghcr.io/matatonic/openedai-speech:latest
  - gpus: all (GPU acceleration for faster synthesis)
  - volumes: gpu/tts/voices + gpu/tts/cache
  - port: 8000 (internal)
  - labels: node.role=tts
- tailscale serve: port 8100 → tts:8000
- sleep_mode: tts added to removal list
- wake_mode: tts added to startup list with --profile tts
- gpuctl usage: tts added to services list
- dashboard: tts added to ServiceRole type, COMPOSE_PROFILES, VALID_ROLES

TTS API is OpenAI-compatible:
  POST http://gpu-node:8100/v1/audio/speech
  { model: 'tts-1', voice: 'alloy', input: 'Hello world' }
  → audio/mpeg response

## 3. Version bump to 0.7.0

## After merge

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

Check footer — v0.7.0.

For TTS:
```sh
curl -X POST http://gpu-node-win:8100/v1/audio/speech \
  -H 'Content-Type: application/json' \
  -d '{"model":"tts-1","voice":"alloy","input":"Hello world"}' \
  --output test.mp3
```
2026-10-29 20:41:35 +00:00
b6533ac558 Merge pull request 'fix: model select uses relativePath + mmproj select + Perf NaN fix + v0.6.0' (#16) from fix/perf-and-models-select into master
Reviewed-on: https://gitea.mikan/mikan/GPU-Node/pulls/16
2026-10-29 19:57:54 +00:00
Z User
48a6166a57 fix: model select uses relativePath + mmproj select in ConfigTab + Perf NaN fix + version 0.6.0
## Problems fixed

### 1. Model select didn't use subdirectories
ConfigTab's model Select used m.name (just 'model.gguf') instead of
m.relativePath ('Qwen3-VL/model.gguf'). When the user selected a model
from a subdir, the config stored just the filename — llama.cpp would
look for /models/model.gguf instead of /models/Qwen3-VL/model.gguf.

**Fix:** Select uses m.relativePath everywhere (model + draft + mmproj).
Also filters by kind: only base models in model Select, only mtp/draft
in draft Select, only mmproj in mmproj Select. Shows subdir/ prefix
in the dropdown.

### 2. mmproj select missing from ConfigTab
User asked: 'mmproj нужна настройка еще на самой странице конфигов'

**Fix:** Added a new 'Multimodal projector (mmproj)' section in
ConfigTab with a Select dropdown. Lists files with kind='mmproj' (or
all files as fallback if no mmproj files detected). Shows the
resulting --mmproj /models/<path> line when set.

### 3. Perf tab shows NaN and '?' everywhere
- 'Ctx usage: NaN / 50176' — slots[].n_past was undefined → NaN in reduce
- 'Default sampling: temp: ? ...' — /props didn't return
  default_generation_settings (or named differently)
- 'Total ctx: —' — /props didn't return n_context
- 'slot #0 ctx: /50176' — n_past was undefined

**Fix:**
- NaN-safe: all slot field access uses typeof checks or ?? '?'
- Try multiple key names: default_generation_settings || generation_settings,
  total_slots || n_slots, n_context || n_ctx_total, has_multimodal ||
  mmproj_path || is_multimodal
- Added '▶ Raw /props + /slots JSON' collapsible section at the bottom
  of Overview — shows the raw JSON from both endpoints so the user (and
  I) can see what llama.cpp actually returns. This is critical for
  debugging — llama.cpp changes field names across versions.

### 4. Version bump to 0.6.0
Updated DASHBOARD_VERSION to '0.6.0' so the user can verify the update
took effect (footer shows v0.6.0, /api/debug returns version: '0.6.0').

## After merge

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

Check footer — should show v0.6.0. If it shows v0.5.0, the container
didn't rebuild (try docker compose build dashboard && docker compose
up -d --force-recreate dashboard).

For Perf tab debugging: open the '▶ Raw /props + /slots JSON' section
and share the output — that'll show exactly what llama.cpp returns.
2026-10-28 20:18:51 +00:00
35730871bf Merge pull request 'fix: version display in UI + simplify subdir to just <repo> (includes all from PR #14)' (#15) from fix/versioning-and-subdir into master
Reviewed-on: #15
2026-10-28 19:38:28 +00:00
6593f78ded Merge pull request 'feat: mmproj support, model subdirs, auto-categorize, perf overview, comfy total size, wake dashboard fix' (#14) from feat/multi-fixes into master
Reviewed-on: #14
2026-10-28 19:37:10 +00:00
Z User
b96d773065 fix: version display in UI + simplify subdir to just <repo>
## What

1. **Version display** — user reported 'ни одно изменение с дашбордом не увидел'.
   Added DASHBOARD_VERSION constant (0.5.0) shown in the footer as 'v0.5.0'.
   Also returned in /api/debug so user can verify the update took effect via
   `curl http://gpu-node:8090/api/debug | jq .version`.

2. **Simplify subdir** — user said '<user>___<repo> не нужно, просто <repo>'.
   Changed download subdir from 'user___repo' to just 'repo'. So
   huggingface.co/user/Qwen3-VL/resolve/main/model.gguf → subdir='Qwen3-VL'
   (was 'user___Qwen3-VL').

3. **Includes all changes from PR #14** (mmproj, subdirs, auto-categorize,
   perf overview, comfy total size, wake dashboard fix) — this branch
   merges feat/multi-fixes + adds versioning + simplifies subdir.

## After merge

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

Check the footer — should show 'v0.5.0'. If it doesn't, the update didn't
take effect.
2026-10-28 19:34:07 +00:00
Z User
71f90aa569 feat: mmproj support, model subdirs, auto-categorize, perf overview, comfy total size, wake dashboard fix
## Summary

8 fixes in one PR — all from user feedback:

1. **Perf tab shows nothing** — added /api/props endpoint, Overview view
   with avg TPS / ctx usage / multimodal / sampling defaults
2. **Comfy models list — no total size** — added total size to header
3. **gpuctl wake doesn't start dashboard** — added belt-and-suspenders
   check + explicit docker compose up -d dashboard fallback
4. **mmproj support (multimodal)** — new mmprojPath config field,
   --mmproj arg, Set mmproj button in Models tab
5. **Subdirectory support in llama_models** — listModels() recurses one
   level deep, ModelFile has relativePath/subdir/kind fields
6. **Auto-categorize models** — detectModelKind() tags files as
   base/mmproj/mtp/draft by filename, shown as colored badges
7. **Comfy download progress** — reduced queue refresh from 5s to 2s
8. **Auto-create repo subdir on download** — HF/GitHub URLs
   automatically create user___repo/ subdirectory

## Details

### Perf tab (1)
- New /api/props endpoint proxies llama.cpp /props
- New Overview view shows: avg TPS, total slots, ctx usage, multimodal,
  predicted/prompt token counts, model name, total ctx, sampling defaults
- Slots view now shows 'No slots' instead of 'No active slots' (idle
  slots are still listed by /slots)
- Default view changed from slots to overview
- Added 'Click Live to start polling' placeholder when not active
- Error display if fetch fails

### Comfy total size (2)
- ComfyTab header now shows total size: 'N file(s) · X.XX GB total'

### gpuctl wake dashboard fix (3)
- wake_mode() now checks if dashboard container is running after the
  --profile wake up -d call, and if not, runs a plain
  'docker compose up -d dashboard' as fallback

### mmproj support (4)
- DashboardConfig.mmprojPath (relative path like 'Qwen3-VL/mmproj-F16.gguf')
- DEFAULT_CONFIG.mmprojPath = ''
- buildLlamaExtraArgs: --mmproj /models/<path> when set
- parseLlamaExtraArgs: parses --mmproj, strips /models/ prefix
- mergeConfig: includes mmprojPath
- ModelsTab: 'Set mmproj' button for files with kind='mmproj'
- Active mmproj shown with badge in model list

### Subdirectory support (5)
- ModelFile: added relativePath, subdir, kind fields
- listModels() now walks top-level entries; if a subdirectory is found,
  lists .gguf files inside it (one level deep — HF repos are flat)
- Sort: by subdir (groups files in same repo together), then by size desc
- deleteModel() accepts relative paths like 'Qwen3-VL/model.gguf'
- Path traversal protection: resolved path must stay under
  LLAMA_MODELS_DIR

### Auto-categorize models (6)
- detectModelKind(filename) checks lowercase filename:
  - 'mmproj' in name → 'mmproj'
  - 'mtp' in name → 'mtp'
  - 'draft' in name → 'draft'
  - otherwise → 'base'
- Models tab shows colored Kind badge per file
- Action buttons are context-aware:
  - base: 'Use' (sets config.model)
  - mmproj: 'Set mmproj' (sets config.mmprojPath)
  - mtp/draft: 'Set draft' (sets config.draftModel)

### Comfy download progress (7)
- Queue refresh interval reduced from 5000ms to 2000ms for more
  responsive progress display

### Auto-create repo subdir on download (8)
- startModelDownload() now detects HF and GitHub URLs and extracts
  user/repo to create a subdirectory:
  - huggingface.co/<user>/<repo>/resolve/<branch>/<file>
    → subdir = '<user>___<repo>'
  - github.com/<user>/<repo>/releases/download/<tag>/<file>
    → subdir = '<user>___<repo>'
  - Other URLs: no subdir (flat layout)
- The subdirectory is created on the fly before starting curl
- File is saved as <LLAMA_MODELS_DIR>/<subdir>/<filename>
- Job.filename shows the full relative path (e.g. 'user___repo/model.gguf')

## Verification

- npm run build — OK, 27 routes (1 new /api/props)
- bash dashboard/validate-build.sh — all 8 COPY sources ✓

## After deploy

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

Test:
- Download a HF model → it lands in user___repo/ subdir
- Models tab shows files grouped by subdir with kind badges
- Click 'Set mmproj' on an mmproj file → --mmproj added to launch args
- Start Llama → check Perf tab → Overview shows TPS / ctx / multimodal
- gpuctl sleep → gpuctl wake → dashboard should come back up
2026-10-28 19:10:58 +00:00
187fefc30b Merge pull request 'feat(comfy): CivitAI URL transformation + token support for comfy models' (#13) from feat/civitai-for-comfy into master
Reviewed-on: #13
2026-10-24 02:40:10 +00:00
12 changed files with 862 additions and 181 deletions

View File

@@ -163,6 +163,25 @@ services:
- "node.role=comfyui"
- "node.instance=${TAILSCALE_HOSTNAME:-gpu-node}"
tts:
profiles:
- tts
image: ghcr.io/matatonic/openedai-speech:latest
container_name: ${TAILSCALE_HOSTNAME:-gpu-node}-tts
gpus: all
volumes:
- ${HOST_PROJECT_PATH:-./}/gpu/tts/voices:/app/voices
- ${HOST_PROJECT_PATH:-./}/gpu/tts/cache:/app/cache
environment:
PORT: 8000
HALF_PRECISION: "false"
networks:
- gpu-node
restart: "no"
labels:
- "node.role=tts"
- "node.instance=${TAILSCALE_HOSTNAME:-gpu-node}"
dashboard:
image: gpu-node-dashboard
container_name: ${TAILSCALE_HOSTNAME:-gpu-node}-dashboard

View File

@@ -26,6 +26,7 @@ function mergeConfig(
nGpuLayers: patch.nGpuLayers ?? base.nGpuLayers,
threads: patch.threads ?? base.threads,
draftModel: patch.draftModel ?? base.draftModel,
mmprojPath: patch.mmprojPath ?? base.mmprojPath,
specType: patch.specType ?? base.specType,
specDraftNMax: patch.specDraftNMax ?? base.specDraftNMax,
batchSize: patch.batchSize ?? base.batchSize,

View File

@@ -120,6 +120,7 @@ export async function GET() {
ok: envError === null,
error: envError,
},
version: "0.7.0",
timestamp: new Date().toISOString(),
});
}

View File

@@ -0,0 +1,50 @@
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* GET /api/props
*
* Proxies llama.cpp's /props endpoint. Returns:
* - default_generation_settings: { n_predict, temperature, top_k, top_p,
* min_p, repeat_penalty, ... } — the sampling defaults the server
* started with
* - total_slots: number of parallel slots
* - model_path: path to the loaded model
* - chat_template: chat template string (if --jinja)
* - n_context: total context size (ctx_size * parallel)
* - n_vocab, n_embd, n_params: model metadata
* - has_multimodal: bool (mmproj loaded)
* - timings: cumulative across all slots since server start
*
* Unlike /slots (per-slot state), /props gives server-wide info that's
* useful even when no chat is running.
*/
export async function GET() {
try {
const res = await fetch("http://llama:8080/props", {
cache: "no-store",
signal: AbortSignal.timeout(5000),
});
if (!res.ok) {
return NextResponse.json(
{
ok: false,
error: `llama returned ${res.status}`,
},
{ status: res.status }
);
}
const data = await res.json();
return NextResponse.json({ ok: true, props: data });
} catch (err) {
return NextResponse.json(
{
ok: false,
error: (err as Error).message,
},
{ status: 503 }
);
}
}

View File

@@ -21,6 +21,7 @@ const VALID_ROLES: ServiceRole[] = [
"ssh-companion",
"gpu-test",
"dashboard",
"tts",
];
function parseRole(role: string): ServiceRole | null {

View File

@@ -53,13 +53,19 @@ import {
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn, formatBytes, timeAgo } from "@/lib/utils";
import { DASHBOARD_VERSION } from "@/lib/version";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type ModelKind = "base" | "mmproj" | "mtp" | "draft";
interface ModelFile {
name: string;
relativePath: string;
subdir: string;
kind: ModelKind;
sizeBytes: number;
sizeHuman: string;
modifiedAt: string;
@@ -91,6 +97,8 @@ interface DashboardConfig {
nGpuLayers: number;
threads: number;
draftModel: string;
/** Optional mmproj file (multimodal vision projector) */
mmprojPath: string;
specType: "none" | "draft-mtp" | "draft-llama";
specDraftNMax: number;
batchSize: number;
@@ -179,6 +187,7 @@ const DEFAULT_CONFIG: DashboardConfig = {
nGpuLayers: -1,
threads: -1,
draftModel: "",
mmprojPath: "",
specType: "none",
specDraftNMax: 4,
batchSize: 512,
@@ -438,7 +447,7 @@ export default function DashboardPage() {
refreshModels();
refreshComfyTypes();
refreshComfyModels();
const id = setInterval(refreshComfyQueue, 5000);
const id = setInterval(refreshComfyQueue, 2000);
return () => clearInterval(id);
}, [
refreshConfig,
@@ -1480,6 +1489,8 @@ export default function DashboardPage() {
busy={busy}
uploadProgress={uploadProgress}
onSelectModel={(m) => update("model", m)}
onUseMmproj={(m) => update("mmprojPath", m)}
onUseDraft={(m) => update("draftModel", m)}
onUpload={handleUpload}
onDelete={handleDeleteModel}
downloadJobs={downloadJobs}
@@ -1550,8 +1561,11 @@ export default function DashboardPage() {
<footer className="border-t border-border bg-card/30 mt-auto">
<div className="mx-auto max-w-7xl px-4 sm:px-6 py-3 flex items-center justify-between text-xs text-muted-foreground">
<div>
GPU-Node Dashboard ·{" "}
<div className="flex items-center gap-2">
<span className="font-mono font-medium text-foreground">
v{DASHBOARD_VERSION}
</span>
<span>·</span>
<a
href="https://github.com/ggml-org/llama.cpp"
target="_blank"
@@ -1790,8 +1804,13 @@ function ConfigTab({
No .gguf files found
</SelectItem>
) : (
models.map((m) => (
<SelectItem key={m.name} value={m.name}>
models.filter((m) => m.kind === "base").map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<span className="font-mono">{m.name}</span>
<span className="ml-2 text-muted-foreground text-xs">{m.sizeHuman}</span>
</SelectItem>
@@ -1899,11 +1918,18 @@ function ConfigTab({
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">— None —</SelectItem>
{models.map((m) => (
<SelectItem key={m.name} value={m.name}>
<span className="font-mono">{m.name}</span>
</SelectItem>
))}
{models
.filter((m) => m.kind === "mtp" || m.kind === "draft")
.map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<span className="font-mono">{m.name}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
@@ -1922,6 +1948,67 @@ function ConfigTab({
</div>
</div>
{/* Multimodal (mmproj) — vision projector for VL models */}
<div className="rounded-md border p-4 space-y-3 bg-muted/20">
<div>
<span className="text-sm font-medium flex items-center gap-2">
<Zap className="h-4 w-4 text-warning" />
Multimodal projector (mmproj)
</span>
<p className="text-xs text-muted-foreground mt-0.5">
Vision projector for VL models (Qwen3-VL, Llama 3.2 Vision, etc.).
Select the mmproj .gguf file that matches your base model.
Leave empty for text-only models.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="mmproj-select">mmproj file</Label>
<Select
value={config.mmprojPath || "__none__"}
onValueChange={(v) => update("mmprojPath", v === "__none__" ? "" : v)}
>
<SelectTrigger id="mmproj-select">
<SelectValue placeholder="None (text-only)" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">— None (text-only) —</SelectItem>
{models
.filter((m) => m.kind === "mmproj")
.map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<span className="font-mono">{m.name}</span>
<span className="ml-2 text-muted-foreground text-xs">{m.sizeHuman}</span>
</SelectItem>
))}
{/* Also show base models as fallback (some mmproj files
don't have 'mmproj' in the name) */}
{models.filter((m) => m.kind === "mmproj").length === 0 && (
models.map((m) => (
<SelectItem key={m.relativePath} value={m.relativePath}>
{m.subdir && (
<span className="text-muted-foreground text-xs">
{m.subdir}/
</span>
)}
<span className="font-mono">{m.name}</span>
</SelectItem>
))
)}
</SelectContent>
</Select>
{config.mmprojPath && (
<div className="text-[10px] text-muted-foreground font-mono">
--mmproj /models/{config.mmprojPath}
</div>
)}
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="overflow">Context overflow</Label>
@@ -2311,6 +2398,8 @@ function ModelsTab({
busy,
uploadProgress,
onSelectModel,
onUseMmproj,
onUseDraft,
onUpload,
onDelete,
downloadJobs,
@@ -2327,6 +2416,8 @@ function ModelsTab({
busy: string | null;
uploadProgress: { name: string; percent: number } | null;
onSelectModel: (m: string) => void;
onUseMmproj: (m: string) => void;
onUseDraft: (m: string) => void;
onUpload: (file: File) => void;
onDelete: (name: string) => void;
downloadJobs: DownloadJob[];
@@ -2591,59 +2682,102 @@ function ModelsTab({
<thead className="sticky top-0 bg-card">
<tr className="text-left text-xs text-muted-foreground border-b">
<th className="py-2 px-2 font-medium">Name</th>
<th className="py-2 px-2 font-medium w-20">Kind</th>
<th className="py-2 px-2 font-medium w-32 text-right">Size</th>
<th className="py-2 px-2 font-medium w-32 text-right">Modified</th>
<th className="py-2 px-2 font-medium w-32 text-right">Actions</th>
<th className="py-2 px-2 font-medium w-44 text-right">Actions</th>
</tr>
</thead>
<tbody>
{models.map((m) => (
<tr
key={m.name}
className="border-b border-border/40 hover:bg-muted/30"
>
<td className="py-2 px-2">
<div className="flex items-center gap-2">
<FileText className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
<span className="font-mono text-xs truncate">{m.name}</span>
{config.model === m.name && (
<Badge variant="success" className="text-[10px]">
active
</Badge>
)}
</div>
</td>
<td className="py-2 px-2 text-right font-mono text-xs">
{m.sizeHuman}
</td>
<td className="py-2 px-2 text-right text-xs text-muted-foreground">
{timeAgo(m.modifiedAt)}
</td>
<td className="py-2 px-2 text-right">
<div className="flex items-center justify-end gap-1">
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={config.model === m.name || busy !== null}
onClick={() => onSelectModel(m.name)}
>
Use
<ChevronRight className="h-3 w-3" />
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 hover:text-destructive"
disabled={busy !== null}
onClick={() => onDelete(m.name)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
))}
{models.map((m) => {
const isActiveBase = config.model === m.relativePath;
const isActiveMmproj = config.mmprojPath === m.relativePath;
const isActiveDraft = config.draftModel === m.name;
const isActive = isActiveBase || isActiveMmproj || isActiveDraft;
const kindBadge = {
base: <Badge variant="outline" className="text-[10px]">base</Badge>,
mmproj: <Badge variant="default" className="text-[10px]">mmproj</Badge>,
mtp: <Badge variant="secondary" className="text-[10px]">mtp</Badge>,
draft: <Badge variant="secondary" className="text-[10px]">draft</Badge>,
}[m.kind];
return (
<tr
key={m.relativePath}
className="border-b border-border/40 hover:bg-muted/30"
>
<td className="py-2 px-2">
<div className="flex items-center gap-2">
<FileText className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
{m.subdir && (
<span className="font-mono text-[10px] text-muted-foreground">
{m.subdir}/
</span>
)}
<span className="font-mono text-xs truncate">{m.name}</span>
{isActive && (
<Badge variant="success" className="text-[10px]">
{isActiveBase ? "active" : isActiveMmproj ? "mmproj" : "draft"}
</Badge>
)}
</div>
</td>
<td className="py-2 px-2">{kindBadge}</td>
<td className="py-2 px-2 text-right font-mono text-xs">
{m.sizeHuman}
</td>
<td className="py-2 px-2 text-right text-xs text-muted-foreground">
{timeAgo(m.modifiedAt)}
</td>
<td className="py-2 px-2 text-right">
<div className="flex items-center justify-end gap-1 flex-wrap">
{m.kind === "base" && (
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={isActiveBase || busy !== null}
onClick={() => onSelectModel(m.relativePath)}
>
Use
<ChevronRight className="h-3 w-3" />
</Button>
)}
{m.kind === "mmproj" && (
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={isActiveMmproj || busy !== null}
onClick={() => onUseMmproj(m.relativePath)}
>
{isActiveMmproj ? "✓ mmproj" : "Set mmproj"}
</Button>
)}
{(m.kind === "mtp" || m.kind === "draft") && (
<Button
size="sm"
variant="ghost"
className="h-7"
disabled={isActiveDraft || busy !== null}
onClick={() => onUseDraft(m.name)}
>
{isActiveDraft ? "✓ draft" : "Set draft"}
</Button>
)}
<Button
size="sm"
variant="ghost"
className="h-7 hover:text-destructive"
disabled={busy !== null}
onClick={() => onDelete(m.relativePath)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
@@ -3063,6 +3197,8 @@ function ComfyTab({
<code className="font-mono text-xs">/project/gpu/comfy/models</code>
{" · "}
{models.length} file(s)
{" · "}
{formatBytes(models.reduce((s, m) => s + (m.sizeBytes || 0), 0))} total
</CardDescription>
</div>
<div className="flex items-center gap-2">
@@ -3689,9 +3825,25 @@ interface SlotInfo {
id: number;
is_processing: boolean;
n_ctx: number;
n_past: number;
n_eval: number;
prompt: number[];
// Newer llama.cpp field names
n_prompt_tokens?: number;
n_prompt_tokens_processed?: number;
n_prompt_tokens_cache?: number;
speculative?: boolean;
// Legacy field names (older versions)
n_past?: number;
n_eval?: number;
prompt?: number[];
// Next token info (newer versions)
next_token?: Array<{
has_next_token?: boolean;
has_new_line?: boolean;
n_remain?: number;
n_decoded?: number;
}>;
// Per-slot params (newer versions include these)
params?: Record<string, unknown>;
// Timings — only present after generation in some versions
timings?: {
prompt_n: number;
prompt_ms: number;
@@ -3703,7 +3855,6 @@ interface SlotInfo {
predicted_per_second: number;
cache_hit_rate?: number;
};
// Speculative decoding stats (if --spec-* was passed at startup)
spec?: {
accepted: number;
drafted: number;
@@ -3713,9 +3864,11 @@ interface SlotInfo {
function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
const [slots, setSlots] = React.useState<SlotInfo[]>([]);
const [props, setProps] = React.useState<Record<string, unknown> | null>(null);
const [metricsRaw, setMetricsRaw] = React.useState<string>("");
const [active, setActive] = React.useState(false);
const [view, setView] = React.useState<"slots" | "metrics">("slots");
const [view, setView] = React.useState<"overview" | "slots" | "metrics">("overview");
const [errors, setErrors] = React.useState<string>("");
React.useEffect(() => {
if (!active || !llamaRunning) return;
@@ -3723,8 +3876,23 @@ function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
async function poll() {
if (cancelled) return;
setErrors("");
try {
if (view === "slots") {
if (view === "overview") {
// Fetch props + slots in parallel for the overview
const [propsRes, slotsRes] = await Promise.all([
fetch("/api/props", { cache: "no-store" }).catch(() => null),
fetch("/api/slots", { cache: "no-store" }).catch(() => null),
]);
if (propsRes && propsRes.ok) {
const pd = await propsRes.json();
if (!cancelled && pd.ok) setProps(pd.props);
}
if (slotsRes && slotsRes.ok) {
const sd = await slotsRes.json();
if (!cancelled) setSlots(sd.slots || []);
}
} else if (view === "slots") {
const res = await fetch("/api/slots", { cache: "no-store" });
if (res.ok) {
const data = await res.json();
@@ -3735,10 +3903,13 @@ function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
if (res.ok) {
const text = await res.text();
if (!cancelled) setMetricsRaw(text);
} else {
const text = await res.text().catch(() => "");
if (!cancelled) setMetricsRaw(`[${res.status}] ${text.slice(0, 300)}`);
}
}
} catch {
/* ignore — will retry */
} catch (err) {
if (!cancelled) setErrors((err as Error).message);
}
}
@@ -3763,11 +3934,12 @@ function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Select value={view} onValueChange={(v) => setView(v as "slots" | "metrics")}>
<SelectTrigger className="w-32">
<Select value={view} onValueChange={(v) => setView(v as "overview" | "slots" | "metrics")}>
<SelectTrigger className="w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="overview">Overview</SelectItem>
<SelectItem value="slots">Slots</SelectItem>
<SelectItem value="metrics">Prometheus</SelectItem>
</SelectContent>
@@ -3801,117 +3973,399 @@ function PerfTab({ llamaRunning }: { llamaRunning: boolean }) {
Start it to see live performance metrics.
</p>
</div>
) : !active ? (
<div className="text-center py-12 text-muted-foreground">
<Play className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Click Live to start polling</p>
<p className="text-xs mt-1">Polls every 1.5s while active</p>
</div>
) : errors ? (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm">
<span className="font-mono text-xs text-destructive">{errors}</span>
</div>
) : view === "slots" ? (
<SlotsView slots={slots} />
) : (
) : view === "metrics" ? (
<pre className="text-xs font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-3 max-h-[32rem] overflow-y-auto scrollbar-thin">
{metricsRaw || "[no metrics — was llama started with --metrics?]"}
</pre>
) : (
<OverviewView props={props} slots={slots} />
)}
</CardContent>
</Card>
);
}
function OverviewView({
props,
slots,
}: {
props: Record<string, unknown> | null;
slots: SlotInfo[];
}) {
if (!props) {
return (
<p className="text-sm text-muted-foreground text-center py-8">
Loading…
</p>
);
}
// Extract params from nested structure
// Newer llama.cpp: default_generation_settings.params.temperature
// Older: default_generation_settings.temperature
const dgs = (props.default_generation_settings ||
props.generation_settings) as Record<string, unknown> | undefined;
const gen = (dgs?.params || dgs) as
| {
n_predict?: number;
max_tokens?: number;
temperature?: number;
top_k?: number;
top_p?: number;
min_p?: number;
repeat_penalty?: number;
}
| undefined;
// Cumulative timings across all slots
const totalPredictedN = slots.reduce(
(s, x) =>
s +
(x.timings?.predicted_n || x.next_token?.[0]?.n_decoded || 0),
0
);
const totalPromptN = slots.reduce(
(s, x) =>
s +
(x.timings?.prompt_n ||
x.n_prompt_tokens_processed ||
x.n_past ||
0),
0
);
// Average TPS — from timings (if available)
const activeSlots = slots.filter((s) => s.timings?.predicted_per_second);
const avgTps =
activeSlots.length > 0
? activeSlots.reduce(
(s, x) => s + (x.timings?.predicted_per_second || 0),
0
) / activeSlots.length
: null;
// Multimodal — newer: modalities.vision, older: has_multimodal
const modalities = props.modalities as
| { vision?: boolean; audio?: boolean; video?: boolean }
| undefined;
const hasMultimodal = Boolean(
modalities?.vision ||
modalities?.audio ||
props.has_multimodal ||
props.is_multimodal
);
const totalSlots =
(props.total_slots as number) ||
(props.n_slots as number) ||
slots.length;
// Ctx usage — try newer field names first
const ctxUsed = slots.reduce(
(s, x) =>
s +
(x.n_prompt_tokens_processed ?? x.n_past ?? 0),
0
);
const ctxTotal = slots.reduce(
(s, x) => s + (x.n_ctx ?? 0),
0
);
// Total ctx from props: newer: default_generation_settings.n_ctx
const totalCtx =
(dgs?.n_ctx as number) ||
(props.n_context as number) ||
(props.n_ctx_total as number) ||
ctxTotal ||
null;
// Speculative decoding
const specSlots = slots.filter((s) => s.speculative);
const hasSpec = specSlots.length > 0;
// Build info
const buildInfo = props.build_info as string | undefined;
const [showRaw, setShowRaw] = React.useState(false);
return (
<div className="space-y-4">
{/* Key metrics */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<MetricCell
label="Avg TPS"
value={avgTps != null ? `${avgTps.toFixed(1)}` : "—"}
hint="tok/s generated"
/>
<MetricCell
label="Total slots"
value={`${totalSlots}`}
hint={`${activeSlots.length} with timings`}
/>
<MetricCell
label="Ctx usage"
value={
ctxTotal > 0
? `${ctxUsed} / ${ctxTotal}`
: ctxUsed > 0
? `${ctxUsed}`
: "—"
}
hint="prompt tokens processed / ctx"
/>
<MetricCell
label="Multimodal"
value={hasMultimodal ? "yes" : "no"}
hint={hasMultimodal ? "vision/audio loaded" : "text-only"}
/>
</div>
{/* Cumulative stats */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
<MetricCell
label="Generated"
value={totalPredictedN > 0 ? `${totalPredictedN}` : "—"}
hint="tokens decoded"
/>
<MetricCell
label="Prompt"
value={totalPromptN > 0 ? `${totalPromptN}` : "—"}
hint="tokens processed"
/>
<MetricCell
label="Model"
value={
typeof props.model_path === "string"
? (props.model_path as string).split("/").pop() || "?"
: "?"
}
hint={typeof props.model_path === "string" ? props.model_path : ""}
/>
<MetricCell
label="Speculative"
value={hasSpec ? "yes" : "no"}
hint={hasSpec ? `${specSlots.length} slots` : "disabled"}
/>
</div>
{/* Active slots breakdown */}
{slots.length > 0 && (
<div>
<div className="text-xs text-muted-foreground mb-2 font-medium uppercase tracking-wide">
Slots ({totalCtx != null ? `${totalCtx} ctx` : ""}{buildInfo ? ` · ${buildInfo}` : ""})
</div>
<SlotsView slots={slots} />
</div>
)}
{/* Generation defaults */}
{gen && (
<div>
<div className="text-xs text-muted-foreground mb-2 font-medium uppercase tracking-wide">
Default sampling
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2 text-xs font-mono">
<span>
<span className="text-muted-foreground">temp:</span> {gen.temperature?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">top_k:</span> {gen.top_k ?? "?"}
</span>
<span>
<span className="text-muted-foreground">top_p:</span> {gen.top_p?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">min_p:</span> {gen.min_p?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">rep:</span> {gen.repeat_penalty?.toFixed(2) ?? "?"}
</span>
<span>
<span className="text-muted-foreground">n_pred:</span> {gen.n_predict ?? gen.max_tokens ?? "?"}
</span>
</div>
</div>
)}
{/* Raw JSON dump — for debugging when fields are missing */}
<div>
<button
className="text-xs text-muted-foreground hover:text-foreground underline-offset-2 hover:underline"
onClick={() => setShowRaw((v) => !v)}
>
{showRaw ? "▼" : "▶"} Raw /props + /slots JSON
</button>
{showRaw && (
<div className="mt-2 space-y-2">
<div>
<div className="text-[10px] text-muted-foreground mb-1">/props:</div>
<pre className="text-[10px] font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-2 max-h-40 overflow-y-auto scrollbar-thin">
{JSON.stringify(props, null, 2)}
</pre>
</div>
<div>
<div className="text-[10px] text-muted-foreground mb-1">/slots:</div>
<pre className="text-[10px] font-mono whitespace-pre-wrap bg-zinc-950 dark:bg-black text-zinc-300 rounded-md border p-2 max-h-40 overflow-y-auto scrollbar-thin">
{JSON.stringify(slots, null, 2)}
</pre>
</div>
</div>
)}
</div>
</div>
);
}
function SlotsView({ slots }: { slots: SlotInfo[] }) {
if (slots.length === 0) {
return (
<p className="text-sm text-muted-foreground text-center py-8">
No active slots. Start a chat to see metrics.
No slots. (Llama might be loading the model still.)
</p>
);
}
return (
<div className="space-y-3">
{slots.map((s) => (
<div key={s.id} className="rounded-md border p-3 bg-card space-y-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Badge variant={s.is_processing ? "default" : "secondary"}>
{s.is_processing ? "processing" : "idle"}
</Badge>
<span className="text-xs text-muted-foreground font-mono">
slot #{s.id}
</span>
</div>
<div className="text-xs text-muted-foreground font-mono">
ctx: {s.n_past}/{s.n_ctx}
{slots.map((s) => {
// Use n_prompt_tokens_processed (newer) or n_past (legacy)
const promptTokens =
s.n_prompt_tokens_processed ?? s.n_past ?? null;
const totalPromptTokens =
s.n_prompt_tokens ?? null;
const cacheTokens = s.n_prompt_tokens_cache ?? null;
const decodedTokens = s.next_token?.[0]?.n_decoded ?? null;
const remainTokens = s.next_token?.[0]?.n_remain ?? null;
const hasTimings = !!s.timings;
return (
<div key={s.id} className="rounded-md border p-3 bg-card space-y-3">
<div className="flex items-center justify-between gap-2 flex-wrap">
<div className="flex items-center gap-2">
<Badge variant={s.is_processing ? "default" : "secondary"}>
{s.is_processing ? "processing" : "idle"}
</Badge>
<span className="text-xs text-muted-foreground font-mono">
slot #{s.id}
</span>
{s.speculative && (
<Badge variant="outline" className="text-[10px]">
spec
</Badge>
)}
</div>
<div className="text-xs text-muted-foreground font-mono">
ctx: {promptTokens ?? "?"}/{s.n_ctx ?? "?"}
{totalPromptTokens != null && ` (${totalPromptTokens} prompt)`}
{cacheTokens != null && ` · ${cacheTokens} cached`}
</div>
</div>
{hasTimings ? (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
<MetricCell
label="TPS"
value={
s.timings!.predicted_per_second != null
? `${s.timings!.predicted_per_second.toFixed(1)} tok/s`
: "—"
}
hint={
s.timings!.predicted_n != null
? `${s.timings!.predicted_n} tok / ${(s.timings!.predicted_ms! / 1000).toFixed(2)}s`
: undefined
}
/>
<MetricCell
label="TTFT"
value={
s.timings!.prompt_ms != null
? `${(s.timings!.prompt_ms / 1000).toFixed(2)}s`
: "—"
}
hint={
s.timings!.prompt_n != null
? `${s.timings!.prompt_n} prompt tok`
: undefined
}
/>
<MetricCell
label="Prompt TPS"
value={
s.timings!.prompt_per_second != null
? `${s.timings!.prompt_per_second.toFixed(1)} tok/s`
: "—"
}
/>
<MetricCell
label="Cache hit"
value={
s.timings!.cache_hit_rate != null
? `${(s.timings!.cache_hit_rate * 100).toFixed(1)}%`
: "—"
}
/>
</div>
) : (
<div className="space-y-1">
<p className="text-xs text-muted-foreground italic">
No per-token timings (idle or no generation yet).
</p>
{decodedTokens != null && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
<MetricCell
label="Decoded"
value={`${decodedTokens}`}
hint="tokens generated"
/>
<MetricCell
label="Remaining"
value={remainTokens != null ? `${remainTokens}` : "—"}
hint="tokens left"
/>
<MetricCell
label="Cache"
value={cacheTokens != null ? `${cacheTokens}` : "—"}
hint="cached prompt tokens"
/>
</div>
)}
</div>
)}
{s.spec && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs pt-2 border-t">
<MetricCell
label="Spec drafted"
value={`${s.spec.drafted}`}
/>
<MetricCell
label="Spec accepted"
value={`${s.spec.accepted}`}
/>
<MetricCell
label="Accept rate"
value={
s.spec.drafted > 0
? `${((s.spec.accepted / s.spec.drafted) * 100).toFixed(0)}%`
: "—"
}
/>
</div>
)}
</div>
{s.timings ? (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
<MetricCell
label="TPS"
value={
s.timings.predicted_per_second != null
? `${s.timings.predicted_per_second.toFixed(1)} tok/s`
: "—"
}
hint={
s.timings.predicted_n != null
? `${s.timings.predicted_n} tok / ${(s.timings.predicted_ms / 1000).toFixed(2)}s`
: undefined
}
/>
<MetricCell
label="TTFT"
value={
s.timings.prompt_ms != null
? `${(s.timings.prompt_ms / 1000).toFixed(2)}s`
: "—"
}
hint={
s.timings.prompt_n != null
? `${s.timings.prompt_n} prompt tok`
: undefined
}
/>
<MetricCell
label="Prompt TPS"
value={
s.timings.prompt_per_second != null
? `${s.timings.prompt_per_second.toFixed(1)} tok/s`
: "—"
}
/>
<MetricCell
label="Cache hit"
value={
s.timings.cache_hit_rate != null
? `${(s.timings.cache_hit_rate * 100).toFixed(1)}%`
: "—"
}
/>
</div>
) : (
<p className="text-xs text-muted-foreground italic">
No timings yet — slot hasn&apos;t processed any tokens.
</p>
)}
{s.spec && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs pt-2 border-t">
<MetricCell
label="Spec drafted"
value={`${s.spec.drafted}`}
/>
<MetricCell
label="Spec accepted"
value={`${s.spec.accepted}`}
/>
<MetricCell
label="Accept rate"
value={
s.spec.drafted > 0
? `${((s.spec.accepted / s.spec.drafted) * 100).toFixed(0)}%`
: "—"
}
/>
</div>
)}
</div>
))}
);
})}
</div>
);
}
@@ -4123,6 +4577,7 @@ function buildPreviewArgs(cfg: DashboardConfig): string {
if (cfg.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
if (cfg.jinja) parts.push("--jinja");
if (cfg.mmprojPath) parts.push(`--mmproj /models/${cfg.mmprojPath}`);
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}

View File

@@ -180,8 +180,18 @@ export interface ContainerInfo {
statusText: string;
}
export type ModelKind = "base" | "mmproj" | "mtp" | "draft";
export interface ModelFile {
/** Display name (just the filename, e.g. "Qwen3-VL-Q8_0.gguf") */
name: string;
/** Full path relative to LLAMA_MODELS_DIR (e.g. "Qwen3-VL/Qwen3-VL-Q8_0.gguf"
* if the file is in a subdirectory, or just "model.gguf" if at the root) */
relativePath: string;
/** Subdirectory name (e.g. "Qwen3-VL") or empty string if at root */
subdir: string;
/** Auto-detected category: base model / mmproj / mtp / draft */
kind: ModelKind;
sizeBytes: number;
sizeHuman: string;
modifiedAt: string;
@@ -200,6 +210,8 @@ export interface DashboardConfig {
threads: number;
/** Optional draft model file */
draftModel: string;
/** Optional mmproj file (multimodal vision projector, e.g. mmproj-F16.gguf) */
mmprojPath: string;
/** Speculative decoding type */
specType: "none" | "draft-mtp" | "draft-llama";
/** Max draft tokens */
@@ -288,6 +300,7 @@ export const DEFAULT_CONFIG: DashboardConfig = {
nGpuLayers: -1,
threads: -1,
draftModel: "",
mmprojPath: "",
specType: "none",
specDraftNMax: 4,
batchSize: 512,
@@ -551,6 +564,16 @@ export function parseLlamaExtraArgs(
case "--jinja":
cfg.jinja = true;
break;
case "--mmproj":
// Multimodal vision projector path
// Strip /models/ prefix if present (we store just the relative path)
if (isValue(next)) {
let p = next;
if (p.startsWith("/models/")) p = p.slice("/models/".length);
cfg.mmprojPath = p;
i++;
}
break;
case "--model-draft":
cfg.draftModel = path.basename(next || "");
i++;
@@ -657,6 +680,11 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
// Jinja chat templates (required for reasoning format to work properly)
if (cfg.jinja) parts.push("--jinja");
// Multimodal vision projector (mmproj) — for vision-language models
// like Qwen3-VL, Llama 3.2 Vision, etc.
if (cfg.mmprojPath) {
parts.push(`--mmproj /models/${cfg.mmprojPath}`);
}
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}
@@ -706,24 +734,78 @@ export async function writeEnvLlamaConfig(
// Models
// ---------------------------------------------------------------------------
/**
* Auto-detect model kind based on filename.
* - 'mmproj' — multimodal vision projector (filename contains 'mmproj')
* - 'mtp' — speculative decoding draft model (filename contains 'mtp')
* - 'draft' — draft model for speculative decoding (filename contains 'draft')
* - 'base' — regular model
*/
export function detectModelKind(filename: string): ModelKind {
const lower = filename.toLowerCase();
if (lower.includes("mmproj")) return "mmproj";
if (lower.includes("mtp")) return "mtp";
if (lower.includes("draft")) return "draft";
return "base";
}
export async function listModels(): Promise<ModelFile[]> {
try {
const entries = await fs.readdir(LLAMA_MODELS_DIR, { withFileTypes: true });
const models: ModelFile[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
// Walk the top-level entries. If a subdirectory is found, recurse one
// level deep (we don't go deeper — HuggingFace-style repos are flat).
const topEntries = await fs.readdir(LLAMA_MODELS_DIR, { withFileTypes: true });
for (const entry of topEntries) {
if (entry.name.startsWith(".")) continue;
if (!entry.name.toLowerCase().endsWith(".gguf")) continue;
const full = path.join(LLAMA_MODELS_DIR, entry.name);
const stat = await fs.stat(full);
models.push({
name: entry.name,
sizeBytes: stat.size,
sizeHuman: humanSize(stat.size),
modifiedAt: stat.mtime.toISOString(),
});
if (entry.isFile()) {
if (!entry.name.toLowerCase().endsWith(".gguf")) continue;
const full = path.join(LLAMA_MODELS_DIR, entry.name);
const stat = await fs.stat(full);
models.push({
name: entry.name,
relativePath: entry.name,
subdir: "",
kind: detectModelKind(entry.name),
sizeBytes: stat.size,
sizeHuman: humanSize(stat.size),
modifiedAt: stat.mtime.toISOString(),
});
} else if (entry.isDirectory()) {
// Subdirectory — list .gguf files inside
const subdir = entry.name;
const subdirPath = path.join(LLAMA_MODELS_DIR, subdir);
let subEntries: import("node:fs").Dirent[];
try {
subEntries = await fs.readdir(subdirPath, { withFileTypes: true });
} catch {
continue; // permission error etc — skip
}
for (const subEntry of subEntries) {
const subName = String(subEntry.name);
if (!subEntry.isFile()) continue;
if (subName.startsWith(".")) continue;
if (!subName.toLowerCase().endsWith(".gguf")) continue;
const full = path.join(subdirPath, subName);
const stat = await fs.stat(full);
models.push({
name: subName,
relativePath: `${subdir}/${subName}`,
subdir,
kind: detectModelKind(subName),
sizeBytes: stat.size,
sizeHuman: humanSize(stat.size),
modifiedAt: stat.mtime.toISOString(),
});
}
}
}
models.sort((a, b) => b.sizeBytes - a.sizeBytes);
// Sort: by subdir (group files in same repo together), then by size desc
models.sort((a, b) => {
if (a.subdir !== b.subdir) {
return a.subdir.localeCompare(b.subdir);
}
return b.sizeBytes - a.sizeBytes;
});
return models;
} catch {
return [];
@@ -1125,6 +1207,7 @@ export type ServiceRole =
| "ssh-companion"
| "gpu-test"
| "dashboard"
| "tts"
| "tailscale";
const COMPOSE_PROFILES: Partial<Record<ServiceRole, string>> = {
@@ -1137,6 +1220,7 @@ const COMPOSE_PROFILES: Partial<Record<ServiceRole, string>> = {
"ssh-companion": "wake",
"model-worker": "wake",
webdav: "wake",
tts: "tts",
};
export async function startService(
@@ -1682,13 +1766,24 @@ export async function saveUploadedModel(
}
export async function deleteModel(
filename: string
relativePath: string
): Promise<{ ok: boolean; error?: string }> {
const safe = path.basename(filename).replace(/[^\w.\-]/g, "_");
// relativePath can be "model.gguf" or "Qwen3-VL/Qwen3-VL-Q8_0.gguf"
// Sanitize each path segment to prevent path traversal
const segments = relativePath.split("/").map((s) =>
s.replace(/[^\w.\-]/g, "_")
);
const safe = segments.join("/");
if (!safe.toLowerCase().endsWith(".gguf")) {
return { ok: false, error: "Only .gguf files are allowed" };
}
const full = path.join(LLAMA_MODELS_DIR, safe);
// Ensure the resulting path is still under LLAMA_MODELS_DIR
const resolvedFull = path.resolve(full);
const resolvedBase = path.resolve(LLAMA_MODELS_DIR);
if (!resolvedFull.startsWith(resolvedBase + path.sep) && resolvedFull !== resolvedBase) {
return { ok: false, error: "Path traversal detected" };
}
try {
await fs.unlink(full);
return { ok: true };

View File

@@ -213,15 +213,35 @@ export async function startModelDownload(
throw new Error(`only http(s) URLs are supported, got: ${parsed.protocol}`);
}
// Determine filename
// Determine filename and optional subdirectory
let filename: string;
let subdir: string = "";
if (filenameOverride) {
filename = filenameOverride;
} else {
// Use last URL path segment, strip query string
const pathname = parsed.pathname;
const last = pathname.split("/").filter(Boolean).pop() || "model.gguf";
const segments = pathname.split("/").filter(Boolean);
const last = segments.pop() || "model.gguf";
filename = last;
// For HuggingFace URLs: /<user>/<repo>/resolve/main/<file>
// → subdir = "<repo>" (just the repo name, not user___repo)
// For GitHub releases: /<user>/<repo>/releases/download/<tag>/<file>
// → subdir = "<repo>"
const host = parsed.hostname.toLowerCase();
if (host === "huggingface.co" || host === "hf.co") {
// HF URL: /user/repo/resolve/branch/file
if (segments.length >= 2) {
const repo = segments[1];
subdir = repo.replace(/[^\w.\-]/g, "_");
}
} else if (host === "github.com" && segments.includes("releases")) {
// GitHub: /user/repo/releases/download/tag/file
if (segments.length >= 2) {
const repo = segments[1];
subdir = repo.replace(/[^\w.\-]/g, "_");
}
}
}
// Sanitize: only allow .gguf extension, no path traversal
@@ -231,9 +251,15 @@ export async function startModelDownload(
// Many HuggingFace URLs use ?download=true; ignore query.
filename = `${filename}.gguf`;
}
if (subdir) {
subdir = subdir.replace(/[^\w.\-]/g, "_");
}
// Check we don't overwrite an existing file (race-safe via atomic rename)
const dest = path.join(LLAMA_MODELS_DIR, filename);
// If subdir is set, create it and download there
const destDir = subdir
? path.join(LLAMA_MODELS_DIR, subdir)
: LLAMA_MODELS_DIR;
const dest = path.join(destDir, filename);
const tmpDest = `${dest}.part`;
const id = `dl-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
@@ -242,7 +268,7 @@ export async function startModelDownload(
url,
originalUrl: rawUrl !== url ? rawUrl : undefined,
urlNote: urlNote || undefined,
filename,
filename: subdir ? `${subdir}/${filename}` : filename,
status: "queued",
bytesDownloaded: 0,
bytesTotal: null,

View File

@@ -0,0 +1,15 @@
/**
* Dashboard version — bump this on every PR merge.
*
* Displayed in the footer and available via /api/debug so the user can
* verify the update actually took effect.
*/
export const DASHBOARD_VERSION = "0.7.0";
/**
* Build timestamp — set at build time by Next.js.
* Falls back to "dev" when running in dev mode.
*/
export const BUILD_ID =
process.env.NEXT_PUBLIC_BUILD_ID ||
(process.env.NODE_ENV === "production" ? "prod" : "dev");

View File

@@ -34,7 +34,7 @@ Usage:
gpuctl restart <service>
gpuctl logs <service>
Services: llama, comfy, model-worker, webdav, dashboard,
Services: llama, comfy, model-worker, webdav, dashboard, tts,
ssh-main, ssh-companion, gpu-test
EOF
}

View File

@@ -115,7 +115,7 @@ sleep_mode() {
echo "Entering sleep mode for instance: $NODE_INSTANCE"
echo "Keeping: tailscale + $KEEP_SSH_ROLE"
for ROLE in llama comfyui gpu-test model-worker webdav dashboard; do
for ROLE in llama comfyui gpu-test model-worker webdav dashboard tts; do
CTR=$(get_service_container "$ROLE" 2>/dev/null) || true
[ -n "$CTR" ] && docker rm -f "$CTR" 2>/dev/null || true
done
@@ -151,17 +151,32 @@ wake_mode() {
echo "Entering wake mode for instance: $NODE_INSTANCE"
echo "Current SSH role: $SSH_ROLE"
echo "Host project: $HOST_PROJECT_PATH"
echo "Starting: $TARGET_SSH_SERVICE + model-worker + webdav + dashboard"
echo "Starting: $TARGET_SSH_SERVICE + model-worker + webdav + dashboard + tts"
HOST_PROJECT_PATH="$HOST_PROJECT_PATH" \
docker compose \
-f "$COMPOSE_FILE" \
--profile wake \
--profile tts \
up -d \
"$TARGET_SSH_SERVICE" \
model-worker \
webdav \
dashboard
dashboard \
tts
# Belt-and-suspenders: ensure dashboard is up even if the --profile wake
# flag above didn't include it (compose v2 with --profile + explicit names
# should work, but older versions may skip services without a matching
# profile).
DASHBOARD_CTR=$(get_service_container "dashboard" 2>/dev/null) || DASHBOARD_CTR=""
if [ -z "$DASHBOARD_CTR" ] || ! container_is_running "$DASHBOARD_CTR"; then
echo "Dashboard not running after wake — starting it explicitly..."
HOST_PROJECT_PATH="$HOST_PROJECT_PATH" \
docker compose \
-f "$COMPOSE_FILE" \
up -d dashboard
fi
echo
echo "Containers:"

View File

@@ -17,6 +17,9 @@
},
"8090": {
"TCPForward": "dashboard:3000"
},
"8100": {
"TCPForward": "tts:8000"
}
}
}