Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(chat): tool-fold follow-ups — live tail stays open, line-keyed members, no empty folded body

reviewfedcb8a41ee3
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index 047f3062e..6b9736c7a 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -184,8 +184,6 @@ export function classifyLocalCommand(content: string): LocalCommandRecord | null
return null
}
-export { COMMAND_OUTPUT_TOOL }
-
// ── System-injected user records ─────────────────────────────────────────────────────────────────
// Claude Code writes several things that are NOT the user's words as `type:"user"` records. Measured
// on 200 real transcripts (2026-09), user records without a tool_result, by `origin.kind`:
diff --git a/src/renderer/lib/chatToolGroups.test.ts b/src/renderer/lib/chatToolGroups.test.ts
index f220e940d..b5f392e8c 100644
--- a/src/renderer/lib/chatToolGroups.test.ts
+++ b/src/renderer/lib/chatToolGroups.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
import type { ChatMessage, ChatPart } from '@shared/types'
import { BACKGROUND_TASK_TOOL } from '@shared/chat-system-records'
import { COMMAND_OUTPUT_TOOL } from '@shared/chat-command'
-import { groupToolCalls, partPosition, toolGroupSummary } from './chatToolGroups'
+import { groupToolCalls, memberKey, partPosition, toolGroupSummary } from './chatToolGroups'
const tool = (name: string, extra: Partial<Extract<ChatPart, { kind: 'tool' }>> = {}): ChatPart => ({
kind: 'tool',
@@ -102,6 +102,19 @@ describe('groupToolCalls', () => {
expect(layout.groupAt.get('1:0')?.key).toBe('i1:0')
})
+
+ it('foldTail:false leaves the run that reaches the end of the thread as chips', () => {
+ const messages = [user('go'), call('Bash'), call('Read'), say('mid'), call('Bash'), call('Edit')]
+ const layout = groupToolCalls(messages, { foldTail: false })
+ expect(runs(messages)).toEqual([['1:0', '2:0'], ['4:0', '5:0']]) // default folds both
+ expect([...layout.groupAt.keys()]).toEqual(['1:0']) // tail run left alone
+ expect(layout.absorbed.has('5:0')).toBe(false)
+ })
+
+ it('memberKey uses the transcript line key, so a prepended page does not re-key a member', () => {
+ expect(memberKey([call('Bash', 120)], { message: 0, part: 0 })).toBe('k120:0')
+ expect(memberKey([call('Bash')], { message: 0, part: 0 })).toBe('i0:0')
+ })
})
describe('toolGroupSummary', () => {
diff --git a/src/renderer/lib/chatToolGroups.ts b/src/renderer/lib/chatToolGroups.ts
index 71274d350..3b2105a18 100644
--- a/src/renderer/lib/chatToolGroups.ts
+++ b/src/renderer/lib/chatToolGroups.ts
@@ -35,6 +35,25 @@ export interface ToolGroupLayout {
export const partPosition = (message: number, part: number): string => `${message}:${part}`
+/**
+ * A React key for one member: the transcript line's byte offset when the message has one (paged
+ * reads), so a prepended older page does not re-key it; else its position (grok, the optimistic
+ * bubble). The group's own key is its first member's.
+ */
+export function memberKey(messages: readonly ChatMessage[], m: ToolGroupMember): string {
+ const key = messages[m.message]?.key
+ return key !== undefined ? `k${key}:${m.part}` : `i${m.message}:${m.part}`
+}
+
+export interface GroupToolCallsOptions {
+ /**
+ * `false` leaves the run that reaches the END of the thread as chips: while the agent is still
+ * working that run is its live turn, and folding it would close each new call as it lands.
+ * Default `true`.
+ */
+ foldTail?: boolean
+}
+
/**
* A tool call the agent made, shown as a chip. Not one:
* - a plan / question card (`body`): that IS the content, never folded away;
@@ -50,20 +69,17 @@ function isFoldableTool(p: ChatPart): boolean {
* The runs of consecutive tool calls, across message boundaries: a transcript writes each call as
* its own line, so the thread holds one message per call. A run ends at anything else in the thread
* — text, a thinking summary, a card, a user message, a system record — exactly where the TUI starts
- * a new line. Runs shorter than `TOOL_GROUP_MIN` stay as chips.
+ * a new line. Runs shorter than `TOOL_GROUP_MIN` stay as chips, and so does the trailing run when
+ * `opts.foldTail` is `false`.
*/
-export function groupToolCalls(messages: readonly ChatMessage[]): ToolGroupLayout {
+export function groupToolCalls(messages: readonly ChatMessage[], opts: GroupToolCallsOptions = {}): ToolGroupLayout {
const groupAt = new Map<string, ToolGroup>()
const absorbed = new Set<string>()
let run: ToolGroupMember[] = []
const flush = (): void => {
if (run.length >= TOOL_GROUP_MIN) {
const first = run[0]
- const key = messages[first.message].key
- groupAt.set(partPosition(first.message, first.part), {
- key: key !== undefined ? `k${key}:${first.part}` : `i${first.message}:${first.part}`,
- members: run
- })
+ groupAt.set(partPosition(first.message, first.part), { key: memberKey(messages, first), members: run })
for (const m of run.slice(1)) absorbed.add(partPosition(m.message, m.part))
}
run = []
@@ -78,7 +94,8 @@ export function groupToolCalls(messages: readonly ChatMessage[]): ToolGroupLayou
else flush()
})
})
- flush()
+ // Whatever run is still open here reaches the end of the thread.
+ if (opts.foldTail !== false) flush()
return { groupAt, absorbed }
}
diff --git a/src/renderer/nodes/ChatPanel.thread.test.tsx b/src/renderer/nodes/ChatPanel.thread.test.tsx
index 1cb5fe518..508606b23 100644
--- a/src/renderer/nodes/ChatPanel.thread.test.tsx
+++ b/src/renderer/nodes/ChatPanel.thread.test.tsx
@@ -131,4 +131,30 @@ describe('⌘M thread look', () => {
expect(host.querySelector('.term-chat__actions time')).toBeNull()
expect(host.querySelector('button[aria-label="Copy message"]')).toBeNull()
})
+
+ it('a turn-ending message whose every part is folded keeps its action row but no empty body', async () => {
+ await mount([
+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0, at: now - 3 * MIN },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Bash', arg: 'a' }], key: 10, at: now - 2 * MIN },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Bash', arg: 'b' }], key: 20, at: now - MIN }
+ ])
+ const last = [...host.querySelectorAll('.term-chat__msg--assistant')].at(-1)!
+ expect(last.classList.contains('term-chat__msg--folded')).toBe(true)
+ expect(last.querySelector('.term-chat__actions time')?.textContent).toBe('1 min ago')
+ expect(last.querySelector('.term-chat__tool')).toBeNull()
+ // ONLY the action row: its calls are drawn in the block above it.
+ expect(last.childElementCount).toBe(1)
+ })
+
+ it('while the agent is working, the trailing run of tool calls is not folded', async () => {
+ // The afterEach drops NODE's entry, which restores the beforeEach's `done` for the next test.
+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'working' } as (typeof s.byId)[string] } }))
+ await mount([
+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Bash', arg: 'a' }], key: 10 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Read', arg: 'b' }], key: 20 }
+ ])
+ expect(host.querySelector('.term-chat__tool-group')).toBeNull()
+ expect(host.querySelectorAll('.term-chat__tool')).toHaveLength(2)
+ })
})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index e1dec6cc3..e81bed9ae 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -968,8 +968,11 @@ export function ChatPanel({
// the turn's last message. `now` is ONE clock for every row's relative time, ticked once a minute
// (a per-row timer would be a timer per turn for a label that changes once a minute).
const turnEnds = useMemo(() => assistantTurnEnds(messages), [messages])
- // Runs of consecutive tool calls, folded into one closed block each (lib/chatToolGroups.ts).
- const toolGroups = useMemo(() => groupToolCalls(messages), [messages])
+ // Runs of consecutive tool calls, folded into one closed block each (lib/chatToolGroups.ts) —
+ // except, while the agent works, the run at the end of the thread: that is the live turn, and its
+ // calls stay open chips until something else ends the run.
+ const foldTail = refusal !== 'working'
+ const toolGroups = useMemo(() => groupToolCalls(messages, { foldTail }), [messages, foldTail])
// The last key IS the latest turn end: `assistantTurnEnds` inserts in thread order.
const latestTurnEnd = useMemo(() => {
let last = -1
@@ -1107,17 +1110,31 @@ export function ChatPanel({
)}
{messages.map((m, i) => {
// A message whose every part is drawn inside an earlier message's tool block has nothing of
- // its own to draw, unless it ends a turn (its action row) or is queued.
+ // its own to draw, unless it ends a turn: then it draws that turn's action row and nothing
+ // else. (Only assistant parts fold, so a queued message — the user's — never does.)
const folded = m.parts.length > 0 && m.parts.every((_, j) => toolGroups.absorbed.has(partPosition(i, j)))
- if (folded && !turnEnds.has(i) && !queuedRef.current.has(m)) return null
+ const turnEnd = turnEnds.get(i)
+ if (folded && !turnEnd) return null
+ // Keyed by the source line's byte offset: a prepended page does not re-key (and so does
+ // not re-render) a single existing bubble. Unkeyed ones (grok, the optimistic sent
+ // bubble) fall back to their position.
+ const key = m.key !== undefined ? `k${m.key}` : `i${i}`
+ const actions = turnEnd && (
+ <ChatTurnActions copyText={turnEnd.copyText} at={turnEnd.at} now={now} latest={i === latestTurnEnd} />
+ )
+ if (folded) {
+ return (
+ <div key={key} className={`term-chat__msg term-chat__msg--${m.role} term-chat__msg--folded`}>
+ {actions}
+ </div>
+ )
+ }
+ const queued = queuedRef.current.has(m)
return (
- // Keyed by the source line's byte offset: a prepended page does not re-key (and so does
- // not re-render) a single existing bubble. Unkeyed ones (grok, the optimistic sent
- // bubble) fall back to their position.
<div
- key={m.key !== undefined ? `k${m.key}` : `i${i}`}
+ key={key}
className={`term-chat__msg term-chat__msg--${m.role}${m.role === 'user' ? ' term-chat__bubble' : ''}${
- queuedRef.current.has(m) ? ' term-chat__msg--queued' : ''
+ queued ? ' term-chat__msg--queued' : ''
}`}
>
{m.parts.map((p, j) => {
@@ -1127,15 +1144,8 @@ export function ChatPanel({
if (toolGroups.absorbed.has(at)) return null
return renderPart(p, i, j)
})}
- {queuedRef.current.has(m) && <div className="term-chat__queued-label">Queued</div>}
- {turnEnds.has(i) && (
- <ChatTurnActions
- copyText={turnEnds.get(i)!.copyText}
- at={turnEnds.get(i)!.at}
- now={now}
- latest={i === latestTurnEnd}
- />
- )}
+ {queued && <div className="term-chat__queued-label">Queued</div>}
+ {actions}
</div>
)
})}
diff --git a/src/renderer/nodes/ChatToolGroup.tsx b/src/renderer/nodes/ChatToolGroup.tsx
index 17954b899..9e364e1e0 100644
--- a/src/renderer/nodes/ChatToolGroup.tsx
+++ b/src/renderer/nodes/ChatToolGroup.tsx
@@ -1,5 +1,5 @@
import type { ChatMessage, ChatPart } from '@shared/types'
-import { partPosition, toolGroupSummary, type ToolGroup } from '../lib/chatToolGroups'
+import { memberKey, toolGroupSummary, type ToolGroup } from '../lib/chatToolGroups'
export interface ChatToolGroupProps {
messages: readonly ChatMessage[]
@@ -24,9 +24,11 @@ export function ChatToolGroup({ messages, group, renderPart }: ChatToolGroupProp
<span className="term-chat__tool-group-names">{names}</span>
</summary>
<div className="term-chat__tool-group-body">
- {group.members.map(({ message, part }) => {
- const p = messages[message]?.parts[part]
- return p ? renderPart(p, message, part, partPosition(message, part)) : null
+ {group.members.map((member) => {
+ const p = messages[member.message]?.parts[member.part]
+ // Keyed by the source line, like the thread's bubbles: a prepended page shifts every
+ // position, and a position key would remount each chip and close whatever was open.
+ return p ? renderPart(p, member.message, member.part, memberKey(messages, member)) : null
})}
</div>
</details>
diff --git a/src/renderer/styles.chat-view.test.ts b/src/renderer/styles.chat-view.test.ts
index 96fdb65a8..1f4f44114 100644
--- a/src/renderer/styles.chat-view.test.ts
+++ b/src/renderer/styles.chat-view.test.ts
@@ -76,6 +76,10 @@ describe('⌘M thread: claude.ai look', () => {
expect(ruleBody('.term-chat__actions')).toMatch(/opacity:\s*0;/)
expect(CSS).toMatch(/\.term-chat__msg:hover \.term-chat__actions,\s*\n?\s*\.term-chat__actions:focus-within,\s*\n?\s*\.term-chat__actions--latest\s*{[^}]*opacity:\s*1;/)
})
+
+ it('a folded message collapses to its action row', () => {
+ expect(ruleBody('.term-chat__msg--folded')).toMatch(/padding:\s*0;/)
+ })
})
describe('the shared .term-chat__input (plan "Revise…", question "Other") keeps a visible field', () => {
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 4a4af0704..b814c4f3f 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3506,6 +3506,12 @@ body,
.term-chat__msg--assistant + .term-chat__msg--assistant {
margin-top: -8px;
}
+/* Every part of this message is drawn in a tool block above it (ChatPanel): it is only its turn's
+ action row, with no body of its own to pad. */
+.term-chat__msg--folded {
+ padding: 0;
+ min-height: 0;
+}
.term-chat__actions {
display: flex;
align-items: center;
diff --git a/src/shared/chat-fixtures/README.md b/src/shared/chat-fixtures/README.md
index 6251a8d3d..7c1a89508 100644
--- a/src/shared/chat-fixtures/README.md
+++ b/src/shared/chat-fixtures/README.md
@@ -72,7 +72,7 @@ the production paging, not a second implementation of it.
| fixture | pins |
|---|---|
| `plain-turns` | User/assistant text, markdown (headings, lists, a blockquote, code fences), string and array user content, two text blocks in one message, and non-ASCII text. Metadata-only records (`file-history-snapshot`, `system`) yield no message. |
-| `tools-cross-page` | A `tool_use` that lands in the second (older) page while its `tool_result` lands in the tail. The tail carries it in `unmatchedResults`, and the older page carries the tool part with its `id` so the port can attach it. One tool call is matched inside the tail. It also shows the `summarizeResult` rules: three lines joined, capped at 500. |
+| `tools-cross-page` | A `tool_use` that lands in the second (older) page while its `tool_result` lands in the tail. The tail carries it in `unmatchedResults`, and the older page carries the tool part with its `id` so the port can attach it. One tool call is matched inside the tail. It also shows the `summarizeResult` rules: three lines joined, capped at 500. The desktop renderer folds a run of two or more consecutive agent tool calls into one block, and the parser output is unchanged, so a port that renders a thread should fold the same runs. |
| `plan-mode` | An `ExitPlanMode` tool call with `input:{plan}`. The tool part carries the full plan as `body` and the approval text as `result`. |
| `ask-question` | `AskUserQuestion` with a single-select and a multi-select question: the rendered `body`, the parsed `questions` (the same reader the answer controls match on) and each result. |
| `utf8-edge` | Multi-byte characters on the window boundaries. The tail window (EOF − 262144) opens **inside** a 4-byte emoji of one line, which must be dropped as the partial line and never decoded torn. The second page (524288) starts **exactly** on the first byte of a multi-byte line, which is kept only because of the lookbehind `\n`. The straddled line reappears whole in that page. The test asserts both placements. |