Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/fix-claude-response-viewer-per-message.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
---
"aicodeman": patch
---

fix(web): render one Claude response-viewer message per model message

The Claude reader concatenated every assistant row between two human prompts into one
card, fusing up to 74 distinct model messages into a single card, and it never read the
attachment rows that hold a prompt typed while the agent was working. Measured over 57
real transcripts on 2026-09-01, the viewer now shows 1,806 messages instead of 356 and
353 user cards instead of 178, recovering the user's own words from 162 absorbed
prompts, with the assistant text sequence unchanged row for row and the response without
`?context=full` byte-identical on all 57 files. A same-speaker run inside one turn
renders as continuation segments under one badge, and the header reports turns as well
as messages instead of claiming a 1,566-row session was "6 messages".
2 changes: 1 addition & 1 deletion docs/architecture-invariants.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -340,7 +340,7 @@ Anatomy: `.set-shell` → `.set-shell-head` (title + `.set-head-actions`) + `.se

⚠️ **`Session.lastSubmitAt` is persisted state, not a runtime counter.** `start()` reassigns `_claudeSessionId = resumeSessionId || id` on every launch — including the re-attach path for a mux session that survived the restart — so a recovered pane always points the viewer at its *launch* conversation, even when the CLI moved on via `/clear` hours earlier. The submit anchor is the only thing that can correct that without user input, so it round-trips through `SessionState.lastSubmitAt` and is restored in `restoreMuxSessions()`. Drop it from `toState()` and recovered panes silently show the pre-`/clear` transcript until the user types again. Restoring a *stale* anchor is safe: the resolver's staleness guard rejects any candidate transcript older than the one the pane is currently on, which is exactly the shape of a respawn into a fresh conversation.

⚠️ **Claude transcripts are grouped at real human-turn boundaries, not per JSONL row.** A Claude transcript is an append-only event log, so one logical exchange spans many rows: tool-result rows, meta/image/skill rows, compact summaries, task/team notifications, sidechains, replayed assistant snapshots, and multi-block assistant output. Rendering a card per row was the bug: it produced duplicate and truncated cards that looked like the viewer had lost the response. The grouping walks to the next genuine user turn and dedups replayed assistant snapshots while preserving the tool/task/skill/compact/team metadata filtering. Related: a recovered `restored-<uuid8>` tmux placeholder carries a **stale cwd**, so transcript lookup by working directory finds nothing; it rebinds to the matching top-level Claude transcript UUID instead when that match is unambiguous. Tests: `test/routes/session-routes-claude-last-response.test.ts`. Purely client-side (no `renderIndexHtml` step): the template ships with `btn-response-viewer-header--hidden` and `applyHeaderVisibilitySettings()` (settings-ui.js) toggles it after settings load. Hiding must go through that marker class — the base rule is `display:inline-flex !important`, so an inline style can't override it. `showResponseViewer` is in the `displayKeys` per-device set (settings-ui.js), so it does NOT sync across devices.
⚠️ **The Claude viewer emits one message per model message and groups them with `turn`; it never concatenates them.** A Claude transcript is an append-only event log, so one logical exchange spans many rows: tool-result rows, meta/image/skill rows, compact summaries, task/team notifications, sidechains, replayed assistant snapshots. Rendering a card per *row* was the original bug (#169) — but the fix overshot to one card per *human turn*, which fused up to 74 distinct model messages into a single card and reported it as one message. One assistant row IS one whole model message: measured across a real `~/.claude/projects` (CLI 2.1.220-2.1.251) no assistant row carries more than one content block and no `message.id` carries more than one text block, so there was never anything to reassemble, and no adjacent pair of assistant rows continues a table, a list, or an open code fence. Each row is therefore its own message carrying `{kind, label, role, text, timestamp, turn}`; the frontend renders a same-role run inside one `turn` as badge-less continuation segments (`.rv-msg-cont`), which is what keeps a p90 of 11 messages per turn from reading as card spam. ⚠️ **A prompt typed while Claude is working is recorded ONLY as an `attachment/queued_command` row** — the CLI never re-emits it as a `user` row — so reading only `user` rows lost 162 of 353 user cards on that corpus AND lost the turn boundary each one carries, which is what let an assistant run fuse in the first place. Take it only when `attachment.origin.kind === 'human'` and `commandMode === 'prompt'`; the CLI's own queue entries (`commandMode: 'task-notification'`) carry no `origin` key at all. The shape is not a documented CLI contract, so every field check must fail closed. ⚠️ **`data.text` (no `?context=full`) is frozen on the last assistant row and must never be derived from `messages.at(-1)`** — agent pollers hash it (`skills/codeman/preamble.sh`), and the last message can be the user's own queued prompt. Replayed assistant snapshots are still deduped, and the tool/task/skill/compact/team metadata filtering is unchanged. Related: a recovered `restored-<uuid8>` tmux placeholder carries a **stale cwd**, so transcript lookup by working directory finds nothing; it rebinds to the matching top-level Claude transcript UUID instead when that match is unambiguous. Tests: `test/routes/session-routes-claude-last-response.test.ts`, `test/response-viewer-turn-segments.test.ts`. Purely client-side (no `renderIndexHtml` step): the template ships with `btn-response-viewer-header--hidden` and `applyHeaderVisibilitySettings()` (settings-ui.js) toggles it after settings load. Hiding must go through that marker class — the base rule is `display:inline-flex !important`, so an inline style can't override it. `showResponseViewer` is in the `displayKeys` per-device set (settings-ui.js), so it does NOT sync across devices.
**File Viewer button** (header, 1.4.1) is **shown by default on desktop** since `211f3c0` (post-1.8.0): toggle under App Settings → Header & Panels → Header buttons → File Viewer (`showFileViewerButton`, in the per-device `displayKeys` set, fallback default `true`). Purely client-side like the response viewer: the template now ships the button VISIBLE (no `--hidden` class) and `applyHeaderVisibilitySettings()` toggles the `btn-file-viewer--hidden` marker class after settings load; phones still hide it via mobile.css. The button toggles the file-browser panel open/closed without opening the settings modal (`panels-ui.js`). The same commit set the **default desktop header** to WS/CPU/MEM + File Viewer + gear: the token-count chip (`showTokenCount`, no settings-UI toggle) and the lifecycle-log button (`showLifecycleLog`) both default **OFF** now (templates ship them hidden; stored prefs still honored). The plan-usage chip default is unchanged (opt-in, see Plan-usage chip). The **Cron toolbar button** joined the same opt-in pattern in 1.6.0: template ships `btn-cron--hidden`, `applyHeaderVisibilitySettings()` toggles it via the per-device `showCronButton` setting (default OFF, App Settings → Header & Panels → Scheduling); cron jobs themselves are unaffected.

### Session list layout (header strip vs. left sidebar)
Expand Down
1 change: 1 addition & 0 deletions skills/codeman/reference/endpoints.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -283,6 +283,7 @@ than into an existing checkout.
| create a session in an arbitrary directory (no case, **no PTY**, id at `.data.session.id`) | `POST /api/v1/sessions`, then `POST /api/v1/sessions/:id/interactive` or `.../shell` to start it, see [Starting a worker](#starting-a-worker) |
| send input | `POST /api/v1/sessions/:id/input` |
| **read a worker's answer** (claude/codex/deepseek) | `GET /api/v1/sessions/:id/last-response` → `.data.{text,timestamp}`, clean transcript text, no TUI noise. ⚠️ **Poll it**, see [symptom 7](#7-last-response-returns-an-empty-string-right-after-stop) |
| read the whole conversation | `GET /api/v1/sessions/:id/last-response?context=full` → `.data.messages[]`. ⚠️ **Only `{role,text}` is present for every mode.** `kind`/`label` come from claude (`prompt`/`response`), deepseek and the pane parser (which also emit `status`/`tool`) but NOT from codex; `timestamp` from claude and codex but not deepseek/pane; `turn` and `queued:true` (a prompt typed while the agent was working) from claude only. `.data.text` is unchanged by `context=full` — it stays the last assistant message, never `messages[-1]` |
| read terminal (tail is in **BYTES**, raw ANSI) | `GET /api/v1/sessions/:id/terminal?tail=3000` → `.data.terminalBuffer`, for *diagnosis* (unsubmitted prompt?), not for reading answers |
| full tmux scrollback (context bomb; post-mortems only) | `GET /api/v1/sessions/:id/terminal?full=1` |
| background agents, one session | `GET /api/v1/sessions/:id/subagents` |
Expand Down
12 changes: 11 additions & 1 deletion skills/codeman/reference/verbs.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -391,7 +391,17 @@ done
printf '%s\n' "$TXT"
```

`.data` is `{text, timestamp}`. ⚠️ **On a hook-less workspace this reads the PREVIOUS
`.data` is `{text, timestamp}`. Add `?context=full` for the whole conversation in
`.data.messages[]`. ⚠️ **The four readers do not emit the same fields — only `{role, text}`
is guaranteed.** `kind`/`label` come from claude (`prompt`/`response`), deepseek and the pane
parser (the last two also emit `status`/`tool`), but **not** from codex; `timestamp` comes
from claude and codex but not from deepseek or the pane parser. A claude worker additionally
carries `turn` (a run of same-speaker messages inside one `turn` is one utterance split into
segments, not separate exchanges) and `queued: true` on a prompt the user typed while the
agent was still working. Filter on `role`, not on `kind`, unless you know the mode.
`.data.text` does not change under `context=full`: it stays the
last **assistant** message, so never read it as `messages[-1]`, which can be a prompt.
⚠️ **On a hook-less workspace this reads the PREVIOUS
turn.** `last-response` returns whatever the transcript last flushed, so it is only as
correct as your end-of-turn signal: pair it with a `stop` signal or a marker, never
with a bare `idle` ([§5.1](#51-where-to-spawn)). ⚠️ **Poll it, do not read it once.** `text` is written
Expand Down
59 changes: 50 additions & 9 deletions src/web/public/app.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2183,15 +2183,26 @@ class CodemanApp {
}

/** Build one response-viewer message so the brief and full views share markup and CSS. */
_buildResponseViewerMessage(text, role, agentLabel) {
_buildResponseViewerMessage(text, role, agentLabel, meta) {
const div = document.createElement('div');
const isUser = role === 'user';
div.className = 'rv-message ' + (isUser ? 'rv-msg-user' : 'rv-msg-assistant');

const roleBadge = document.createElement('div');
roleBadge.className = 'rv-role ' + (isUser ? 'rv-role-user' : 'rv-role-assistant');
roleBadge.textContent = isUser ? 'You' : agentLabel;
div.appendChild(roleBadge);
// Consecutive messages from one speaker inside one turn are segments of a
// single utterance: one badge, a hairline seam. Claude emits a median of 3
// messages per turn (p90 11, max 51), so a badge per message would be the
// card spam the old concatenation was introduced to avoid. `meta` is
// optional so the brief view's 3-argument call keeps its exact shape.
const continuation = !!(meta && meta.continuation);
if (continuation) div.classList.add('rv-msg-cont');
if (meta && meta.kind) div.dataset.kind = meta.kind;
if (meta && meta.queued) div.dataset.queued = '1';

if (!continuation) {
const roleBadge = document.createElement('div');
roleBadge.className = 'rv-role ' + (isUser ? 'rv-role-user' : 'rv-role-assistant');
roleBadge.textContent = isUser ? 'You' : agentLabel;
div.appendChild(roleBadge);
}

const renderedText = document.createElement('div');
renderedText.className = 'rv-text';
Expand DownExpand Up@@ -2351,19 +2362,49 @@ class CodemanApp {
if (!body) return;

if (messages.length === 0) {
body.textContent = 'No conversation history available';
// Never destroy what the eye button already rendered: the brief view has
// a terminal-buffer fallback (see toggleResponseViewer) that this
// endpoint does not, so an empty full-context result must not wipe a
// real answer the user is reading.
// ⚠️ Idempotent, because More deliberately stays live here: the branch
// returns before the button is hidden so a transcript that appears a
// moment later can still be loaded, and appending would then stack a
// second identical notice on every retry.
// `:scope >` keeps the lookup off model-rendered markdown inside .rv-text.
let notice = body.querySelector(':scope > .rv-notice');
if (!notice) {
notice = document.createElement('div');
notice.className = 'rv-notice';
body.appendChild(notice);
}
const emptyText = 'No full conversation history available for this session';
notice.textContent = window.codemanT?.(emptyText) || emptyText;
return;
}

// Render conversation thread
const agentLabel = this._getResponseViewerAgentLabel();
body.innerHTML = '';
let previous = null;
for (const msg of messages) {
body.appendChild(this._buildResponseViewerMessage(msg.text, msg.role, agentLabel));
// ⚠️ A numeric `turn` is REQUIRED, never same-role adjacency alone.
// Only the Claude reader emits turns; Codex and the external-CLI pane
// parser emit adjacent assistant/response blocks with no turn at all, and
// an older server emits none either — all three must keep rendering one
// badged card per message exactly as they do today.
const continuation =
!!previous && previous.role === msg.role && typeof msg.turn === 'number' && previous.turn === msg.turn;
body.appendChild(this._buildResponseViewerMessage(msg.text, msg.role, agentLabel, { ...msg, continuation }));
previous = msg;
}
this._bindResponseViewerInteractions(body);

if (title) title.textContent = `Conversation (${messages.length} messages)`;
const turns = new Set(messages.filter((msg) => typeof msg.turn === 'number').map((msg) => msg.turn)).size;
if (title) {
title.textContent = turns
? `Conversation (${messages.length} messages, ${turns} turns)`
: `Conversation (${messages.length} messages)`;
}
if (moreBtn) moreBtn.style.display = 'none';
// Scroll to bottom (latest message)
body.scrollTop = body.scrollHeight;
Expand Down
1 change: 1 addition & 0 deletions src/web/public/i18n.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,6 +86,7 @@
'Instance count': '实例数量',
'No response yet': '暂无回复',
'No response yet — send a message in this session first.': '暂无回复,请先在此会话中发送一条消息。',
'No full conversation history available for this session': '此会话没有可显示的完整对话历史',
'Last Response': '最近一次回复',
More: '更多',
'Codeman version': '{name}版本',
Expand Down
37 changes: 37 additions & 0 deletions src/web/public/styles.css
Original file line numberDiff line numberDiff line change
Expand Up@@ -12600,6 +12600,43 @@ kbd {
background: color-mix(in srgb, var(--green) 12%, transparent);
}

/* Consecutive messages from one speaker inside one turn are segments of a
single utterance, not separate cards: no repeated badge, a hairline seam.
The role accent survives because the colour rules above match on BOTH
:has(.rv-role-*) and .rv-msg-* — a badge-less continuation still hits the
class arm. Do not drop either arm. */
.rv-message.rv-msg-cont {
margin-top: -18px;
border-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
padding-top: 0;
}

.rv-message.rv-msg-cont > .rv-text {
border-top: 1px solid var(--border);
padding-top: 12px;
}

.rv-message:has(+ .rv-msg-cont) {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
padding-bottom: 0;
}

/* A prompt the user typed while the agent was working (absorbed mid-turn).
A pseudo-element, not a text node, so the i18n MutationObserver cannot
rewrite it. */
.rv-message[data-queued='1'] .rv-role::after {
content: ' ⏱';
}

.rv-notice {
opacity: 0.7;
font-style: italic;
margin-top: 12px;
}

/* Markdown rendered content inside response viewer.
Prose uses a proportional font for readability; code keeps monospace. */
.rv-text,
Expand Down
Loading