fix(dashboard): chat survives tab switch, Enter to send, reasoning display, /health via fetch, n-predict + reasoning-format params #12

Merged
mikan merged 1 commits from fix/chat-improvements into master 2026-10-24 02:19:07 +00:00
Collaborator

Что починил

1. Chat сбрасывался при смене вкладки

Причина: state (messages, input, streaming) жил внутри ChatTab компонента. Когда юзер переключал вкладку → ChatTab unmount → state терялся.

Fix: поднял весь chat state на top-level компонент:

  • chatMessages, chatInput, chatStreaming, chatAutoScroll
  • chatAbortRef (для Stop button)
  • chatMessagesEndRef (auto-scroll anchor)

ChatTab теперь controlled component — получает state + handlers как props. Переключение вкладок unmount'ит view, но state сохраняется.

2. Enter для отправки, Shift+Enter для переноса

Было: Ctrl+Enter чтобы отправить.
Теперь: Enter (без Shift/Ctrl/Meta/Alt) отправляет. Shift+Enter вставляет newline (default textarea behavior).

3. Reasoning display (thinking models)

Почему не показывало reasoning: llama.cpp --reasoning-format auto split'ит <dim...> блоки в отдельное delta.reasoning_content field. Мы его не ловили.

Fix:

  • Добавил --reasoning-format config field (none/deepthink/auto, default auto).
  • Добавил --jinja toggle (нужен для reasoning format).
  • /api/chat передаёт reasoning_format через.
  • Frontend handleChatSend ловит delta.reasoning_content → message.reasoning.
  • MessageBubble показывает reasoning как collapsible блок над content (▶ Reasoning, клик чтобы развернуть).

4. Prefill speed + TTFT в chat stats

Было: показывал 'Prompt: N tok (Xs, Y tok/s)' одной строкой, легко пропустить.
Теперь: явные отдельные stats:

  • TPS: — generation throughput (predicted_per_second)
  • TTFT: — Time To First Token = prompt_ms / 1000 (с prompt token count в скобках)
  • Prefill: — prompt processing speed (prompt_per_second)
  • Cache hit: — KV cache reuse rate
  • Spec decoding: — accepted/drafted + acceptance rate

5. Лимит ответа (max tokens)

'У него же нет ограничений в объеме ответа кроме Context size?' — есть: --n-predict (default -1 = infinity). Не был exposed.

Fix: добавил nPredict field в DashboardConfig (default -1). Sets --n-predict на server AND max_tokens per-request в /api/chat. UI: input в Default sampling секции ConfigTab.

6. /health 'Unreachable' — wget missing

Было: docker exec ... wget -qO- http://127.0.0.1:8080/health → 'OCI runtime exec failed: exec: "wget": executable file not found in $PATH'. llama.cpp:server-cuda image не включает wget.

Fix: getLlamaHealth() теперь использует Node native fetch() к http://llama:8080/health напрямую — dashboard container на той же Docker сети. (Тот же подход что в /api/chat и /api/slots.)

7. 'зачем нам отдельно выделять лламму?'

/api/llama endpoint (start/stop/restart/remove) функционально идентичен /api/services/llama. Оставил для backward compat с frontend ко��ом, но System tab's per-container action buttons (▶ ↻ ■ 🗑) уже используют generic /api/services route.

Backend

dashboard/src/lib/docker.ts

  • DashboardConfig: добавил nPredict, reasoningFormat, jinja
  • DEFAULT_CONFIG: nPredict=-1, reasoningFormat='auto', jinja=true
  • buildLlamaExtraArgs(): эмитит --n-predict (если >=0), --reasoning-format <value>, --jinja (если true)
  • parseLlamaExtraArgs(): парсит --n-predict/--predict/-n, --reasoning-format, --jinja. Добавил isValue() helper.
  • getLlamaHealth(): переписал на fetch() вместо docker exec wget

dashboard/src/app/api/config/route.ts

  • mergeConfig() включает 3 новых field'а

dashboard/src/app/api/chat/route.ts

  • Убрал unused spawn import и misleading wget comment
  • Принимает reasoning_format в body, передаёт в llama.cpp
  • Sets stream_options: { include_usage: true } чтобы timings приходили в final chunk

Frontend

dashboard/src/app/page.tsx

  • Поднял chat state (chatMessages, chatInput, chatStreaming, chatAutoScroll, chatAbortRef, chatMessagesEndRef) на top-level component
  • ChatTab теперь controlled component (state + handlers как props)
  • Enter key отправляет (Shift+Enter для newline)
  • handleChatSend() ловит delta.reasoning_content → message.reasoning
  • MessageBubble: collapsible Reasoning блок (▶ / ▼)
  • MessageStats: явные TPS / TTFT / Prefill / Cache hit / Spec decoding
  • DashboardConfig interface + DEFAULT_CONFIG + buildPreviewArgs все включают 3 новых field'а
  • ConfigTab 'Default sampling' секция: добавил n-predict input, reasoning-format select, jinja toggle

Verification

  • npm run build — OK, 26 routes
  • bash dashboard/validate-build.sh — все 8 COPY источников ✓, standalone ✓

После мержа

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

Затем:

  1. Открой Config tab → Default sampling → Reasoning format 'auto' (должен быть default), Jinja ON (должен быть default)
  2. Start Llama
  3. Открой Chat tab → отправь сообщение thinking модели (Qwen3, DeepSeek-R1) → увидь reasoning блок над ответом
  4. Переключись на Models tab и обратно → chat сохранён
  5. Нажми Enter → отправка. Shift+Enter → newline
  6. Проверь System tab → Llama /health должно показать OK (больше нет wget error)
## Что починил ### 1. Chat сбрасывался при смене вкладки **Причина:** state (`messages`, `input`, `streaming`) жил внутри `ChatTab` компонента. Когда юзер переключал вкладку → ChatTab unmount → state терялся. **Fix:** поднял весь chat state на top-level компонент: - `chatMessages`, `chatInput`, `chatStreaming`, `chatAutoScroll` - `chatAbortRef` (для Stop button) - `chatMessagesEndRef` (auto-scroll anchor) ChatTab теперь controlled component — получает state + handlers как props. Переключение вкладок unmount'ит view, но state сохраняется. ### 2. Enter для отправки, Shift+Enter для переноса Было: Ctrl+Enter чтобы отправить. Теперь: Enter (без Shift/Ctrl/Meta/Alt) отправляет. Shift+Enter вставляет newline (default textarea behavior). ### 3. Reasoning display (thinking models) **Почему не показывало reasoning:** llama.cpp `--reasoning-format auto` split'ит `<dim...>` блоки в отдельное `delta.reasoning_content` field. Мы его не ловили. **Fix:** - Добавил `--reasoning-format` config field (none/deepthink/auto, default `auto`). - Добавил `--jinja` toggle (нужен для reasoning format). - `/api/chat` передаёт `reasoning_format` через. - Frontend `handleChatSend` ловит `delta.reasoning_content` → `message.reasoning`. - MessageBubble показывает reasoning как collapsible блок над content (▶ Reasoning, клик чтобы развернуть). ### 4. Prefill speed + TTFT в chat stats **Было:** показывал 'Prompt: N tok (Xs, Y tok/s)' одной строкой, легко пропустить. **Теперь:** явные отдельные stats: - `TPS:` — generation throughput (predicted_per_second) - `TTFT:` — Time To First Token = prompt_ms / 1000 (с prompt token count в скобках) - `Prefill:` — prompt processing speed (prompt_per_second) - `Cache hit:` — KV cache reuse rate - `Spec decoding:` — accepted/drafted + acceptance rate ### 5. Лимит ответа (max tokens) 'У него же нет ограничений в объеме ответа кроме Context size?' — есть: `--n-predict` (default -1 = infinity). Не был exposed. **Fix:** добавил `nPredict` field в DashboardConfig (default -1). Sets `--n-predict` на server AND `max_tokens` per-request в /api/chat. UI: input в Default sampling секции ConfigTab. ### 6. /health 'Unreachable' — wget missing **Было:** `docker exec ... wget -qO- http://127.0.0.1:8080/health` → 'OCI runtime exec failed: exec: "wget": executable file not found in $PATH'. llama.cpp:server-cuda image не включает wget. **Fix:** `getLlamaHealth()` теперь использует Node native `fetch()` к `http://llama:8080/health` напрямую — dashboard container на той же Docker сети. (Тот же подход что в /api/chat и /api/slots.) ### 7. 'зачем нам отдельно выделять лламму?' `/api/llama` endpoint (start/stop/restart/remove) функционально идентичен `/api/services/llama`. Оставил для backward compat с frontend ко��ом, но System tab's per-container action buttons (▶ ↻ ■ 🗑) уже используют generic /api/services route. ## Backend ### `dashboard/src/lib/docker.ts` - `DashboardConfig`: добавил `nPredict`, `reasoningFormat`, `jinja` - `DEFAULT_CONFIG`: nPredict=-1, reasoningFormat='auto', jinja=true - `buildLlamaExtraArgs()`: эмитит `--n-predict` (если >=0), `--reasoning-format <value>`, `--jinja` (если true) - `parseLlamaExtraArgs()`: парсит `--n-predict`/`--predict`/`-n`, `--reasoning-format`, `--jinja`. Добавил `isValue()` helper. - `getLlamaHealth()`: переписал на fetch() вместо docker exec wget ### `dashboard/src/app/api/config/route.ts` - `mergeConfig()` включает 3 новых field'а ### `dashboard/src/app/api/chat/route.ts` - Убрал unused `spawn` import и misleading wget comment - Принимает `reasoning_format` в body, передаёт в llama.cpp - Sets `stream_options: { include_usage: true }` чтобы timings приходили в final chunk ## Frontend ### `dashboard/src/app/page.tsx` - Поднял chat state (chatMessages, chatInput, chatStreaming, chatAutoScroll, chatAbortRef, chatMessagesEndRef) на top-level component - ChatTab теперь controlled component (state + handlers как props) - Enter key отправляет (Shift+Enter для newline) - `handleChatSend()` ловит `delta.reasoning_content` → message.reasoning - MessageBubble: collapsible Reasoning блок (▶ / ▼) - MessageStats: явные TPS / TTFT / Prefill / Cache hit / Spec decoding - `DashboardConfig` interface + DEFAULT_CONFIG + buildPreviewArgs все включают 3 новых field'а - ConfigTab 'Default sampling' секция: добавил n-predict input, reasoning-format select, jinja toggle ## Verification - `npm run build` — OK, 26 routes - `bash dashboard/validate-build.sh` — все 8 COPY источников ✓, standalone ✓ ## После мержа ```sh git pull && sh build.sh docker compose up -d --force-recreate dashboard ``` Затем: 1. Открой Config tab → Default sampling → Reasoning format 'auto' (должен быть default), Jinja ON (должен быть default) 2. Start Llama 3. Открой Chat tab → отправь сообщение thinking модели (Qwen3, DeepSeek-R1) → увидь reasoning блок над ответом 4. Переключись на Models tab и обратно → chat сохранён 5. Нажми Enter → отправка. Shift+Enter → newline 6. Проверь System tab → Llama /health должно показать OK (больше нет wget error)
super-z-bot added 1 commit 2026-10-24 02:17:21 +00:00
## 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
mikan merged commit 3d2bec055b into master 2026-10-24 02:19:07 +00:00
Sign in to join this conversation.
No Reviewers
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: mikan/GPU-Node#12