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): a prompt queued mid-turn no longer folds the live tool run

review5bde2e166507
diff --git a/src/renderer/lib/chatToolGroups.test.ts b/src/renderer/lib/chatToolGroups.test.ts
index 35c0f7e19..cc9153b32 100644
--- a/src/renderer/lib/chatToolGroups.test.ts
+++ b/src/renderer/lib/chatToolGroups.test.ts
@@ -149,6 +149,41 @@ describe('groupToolCalls', () => {
expect([...layout.absorbed]).toEqual(['2:0', '5:0'])
})
+ it('foldTail:false measures the tail before the queued prompts at the end of the thread', () => {
+ // A prompt sent into the CLI's queue mid-turn is drawn at the END of the thread until the
+ // transcript has it. It is not the turn's output: the live run before it is still the tail.
+ const queued = [user('next, please'), user('and this')]
+ const messages = [user('go'), call('Bash'), call('Read'), say('mid'), call('Bash'), call('Edit'), ...queued]
+ const isQueued = (m: ChatMessage): boolean => queued.includes(m)
+
+ const layout = groupToolCalls(messages, { foldTail: false, isQueued })
+
+ expect([...layout.groupAt.keys()]).toEqual(['1:0']) // the run before the queued bubbles stays chips
+ expect(layout.absorbed.has('5:0')).toBe(false)
+ // Without the predicate the user bubble ends the run, and each new call would land folded.
+ expect([...groupToolCalls(messages, { foldTail: false }).groupAt.keys()]).toEqual(['1:0', '4:0'])
+ })
+
+ it('a queued prompt does not keep an earlier run open once the thread has moved past it', () => {
+ // Only TRAILING queued bubbles are skipped: a run that a non-queued message ends folds as before.
+ const queued = user('queued')
+ const messages = [user('go'), call('Bash'), call('Read'), say('done'), queued]
+
+ const layout = groupToolCalls(messages, { foldTail: false, isQueued: (m) => m === queued })
+
+ expect([...layout.groupAt.keys()]).toEqual(['1:0'])
+ expect(layout.absorbed.has('2:0')).toBe(true)
+ })
+
+ it('a turn that is not live folds the run before the queued prompts too (foldTail default)', () => {
+ const queued = user('queued')
+ const messages = [user('go'), call('Bash'), call('Read'), queued]
+
+ const layout = groupToolCalls(messages, { isQueued: (m) => m === queued })
+
+ expect([...layout.groupAt.keys()]).toEqual(['1:0'])
+ })
+
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')
diff --git a/src/renderer/lib/chatToolGroups.ts b/src/renderer/lib/chatToolGroups.ts
index 95f02f684..f44bc3960 100644
--- a/src/renderer/lib/chatToolGroups.ts
+++ b/src/renderer/lib/chatToolGroups.ts
@@ -53,6 +53,12 @@ export interface GroupToolCallsOptions {
* Default `true`.
*/
foldTail?: boolean
+ /**
+ * The optimistic bubbles of prompts sent into the CLI's queue mid-turn (ChatPanel's "Queued"). They
+ * sit at the END of the thread until the transcript has them, so the run they follow is still the
+ * live tail: `foldTail` measures the end against the last message that is NOT queued. Absent = none.
+ */
+ isQueued?: (m: ChatMessage) => boolean
}
/**
@@ -76,12 +82,15 @@ function isFoldableTool(p: ChatPart, message: number, latestTodo: number): boole
* 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, and so does the trailing run when
- * `opts.foldTail` is `false`.
+ * `opts.foldTail` is `false` (trailing = before any queued prompts at the very end, `opts.isQueued`).
*/
export function groupToolCalls(messages: readonly ChatMessage[], opts: GroupToolCallsOptions = {}): ToolGroupLayout {
const groupAt = new Map<string, ToolGroup>()
const absorbed = new Set<string>()
const latestTodo = latestTodoIndex(messages)
+ // The thread's end for `foldTail`: queued prompts after the last real message are not part of it.
+ let end = messages.length
+ if (opts.isQueued) while (end > 0 && opts.isQueued(messages[end - 1])) end--
let run: ToolGroupMember[] = []
const flush = (): void => {
if (run.length >= TOOL_GROUP_MIN) {
@@ -91,7 +100,7 @@ export function groupToolCalls(messages: readonly ChatMessage[], opts: GroupTool
}
run = []
}
- messages.forEach((m, i) => {
+ messages.slice(0, end).forEach((m, i) => {
if (m.role !== 'assistant' || isSystemRecordMessage(m)) {
flush()
return
@@ -101,7 +110,8 @@ export function groupToolCalls(messages: readonly ChatMessage[], opts: GroupTool
else flush()
})
})
- // Whatever run is still open here reaches the end of the thread.
+ // Whatever run is still open here reaches the end of the thread (the queued prompts after `end`
+ // hold no tool call to fold — they are the user's).
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 424346c10..a52c063c5 100644
--- a/src/renderer/nodes/ChatPanel.thread.test.tsx
+++ b/src/renderer/nodes/ChatPanel.thread.test.tsx
@@ -25,7 +25,7 @@ const { session, reads } = vi.hoisted(() => {
return { messages: reads.messages, found: true, olderCursor: null, unmatchedResults: [] }
}
},
- pty: { sendText: vi.fn(async () => true as const) }
+ pty: { sendText: vi.fn(async () => true as const), sendChatPrompt: vi.fn(async () => true as const) }
}
}
return { session, reads }
@@ -187,6 +187,27 @@ describe('⌘M thread look', () => {
expect(host.querySelectorAll('.term-chat__tool')).toHaveLength(2)
})
+ it('a prompt queued mid-turn does not fold the live run it lands after', async () => {
+ // The "Queued" bubble is drawn at the END of the thread; the run before it is still the live tail.
+ 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 }
+ ])
+ const ta = host.querySelector('textarea')!
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(ta, 'and then this')
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ expect(host.querySelector('.term-chat__msg--queued')?.textContent).toContain('and then this')
+ expect(host.querySelector('.term-chat__tool-group')).toBeNull()
+ expect(host.querySelectorAll('.term-chat__tool')).toHaveLength(2)
+ })
+
it('shows the clock time under a user bubble and a day divider at each day start', async () => {
// `thread` is stamped off the wall clock, so for ten minutes after midnight its first stamps fall
// on yesterday; re-anchored at today's noon its stamps are all today whenever this runs.
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 7262f8198..3a2f768b1 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -981,8 +981,13 @@ export function ChatPanel({
// except, while the turn is live, the run at the end of the thread: its calls stay open chips until
// something else ends the run. Live = working, or waiting on a prompt (`dialog`: a permission
// request or question lands MID-turn, and folding on it would close the run on every prompt).
+ // A prompt queued meanwhile is drawn at the very end, but is not the turn's output: the tail is
+ // measured before it (`isQueued`; the set gains a send before the thread does, so it is current).
const liveTurn = refusal === 'working' || refusal === 'dialog'
- const toolGroups = useMemo(() => groupToolCalls(messages, { foldTail: !liveTurn }), [messages, liveTurn])
+ const toolGroups = useMemo(
+ () => groupToolCalls(messages, { foldTail: !liveTurn, isQueued: (m) => queuedRef.current.has(m) }),
+ [messages, liveTurn]
+ )
// The last key IS the latest turn end: `assistantTurnEnds` inserts in thread order.
const latestTurnEnd = useMemo(() => {
let last = -1
diff --git a/src/shared/chat-fixtures/README.md b/src/shared/chat-fixtures/README.md
index 9b3689624..d2b62934d 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. The desktop renderer folds a run of two or more consecutive agent tool calls into one block, except the run at the END of the thread while the agent is working or waiting on a prompt (the live turn), and the parser output is unchanged, so a port that renders a thread should fold the same runs. |
+| `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, except the run at the END of the thread while the agent is working or waiting on a prompt (the live turn; the end is measured before any optimistic "Queued" prompt bubbles drawn after it), 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. |