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): persist tool cards past turn-done, true Stop semantics, clean fatal teardown

enes4b4ded79e022
diff --git a/src/main/chat-driver.ts b/src/main/chat-driver.ts
index d5168aa35..2223fd34d 100644
--- a/src/main/chat-driver.ts
+++ b/src/main/chat-driver.ts
@@ -21,6 +21,10 @@ interface ChatSession {
pending: Map<string, PendingPermission>
allowedForSession: Set<string>
interrupt?: () => Promise<void>
+ // Set by interrupt() before it fires the SDK interrupt, so the resulting turn-done is treated
+ // as a user Stop: it must NOT auto-flush the queue and its done status carries interrupted:true
+ // (so Canvas skips the completion notification). Cleared when that turn-done is handled.
+ interruptedByUser: boolean
disposed: boolean
}
@@ -43,10 +47,15 @@ export class ChatDriver {
this.getWindow()?.webContents.send(IPC.chatEvent(nodeId), event)
}
- private status(s: ChatSession, state: 'working' | 'blocked' | 'done', newTurn = false): void {
+ private status(
+ s: ChatSession,
+ state: 'working' | 'blocked' | 'done',
+ newTurn = false,
+ interrupted = false
+ ): void {
const ev: NormalizedAgentEvent = {
nodeId: s.nodeId, agentId: 'claude', kind: 'state', state, newTurn,
- sessionId: s.sessionId
+ sessionId: s.sessionId, ...(interrupted ? { interrupted: true } : {})
}
this.sendToMain(IPC.agentStatus, ev)
}
@@ -66,11 +75,15 @@ export class ChatDriver {
const s: ChatSession = {
nodeId, cwd: opts.cwd, sessionId: resume, working: false,
input: createPushIterable<unknown>(), queue: new ChatInputQueue(),
- pending: new Map(), allowedForSession: new Set(), disposed: false
+ pending: new Map(), allowedForSession: new Set(),
+ interruptedByUser: false, disposed: false
}
this.sessions.set(nodeId, s)
void this.run(s, resume, opts.fork === true).catch((err) => {
this.emit(nodeId, { kind: 'error', message: String(err?.message ?? err), fatal: true })
+ // Tear down like dispose(): resolve/clear any pending permission cards and end input, so a
+ // fatal crash doesn't leave a stale permission prompt or "working" badge before Reconnect.
+ this.teardown(s)
this.sessions.delete(nodeId)
})
return { ok: true }
@@ -115,8 +128,12 @@ export class ChatDriver {
this.emit(s.nodeId, event)
if (event.kind === 'turn-done') {
s.working = false
- this.status(s, 'done')
- this.flushQueue(s)
+ // A user Stop (interrupt) ends the turn too — but the queue must stay put (items are
+ // individually deletable) and Canvas must skip the "finished" notification.
+ const interrupted = s.interruptedByUser
+ s.interruptedByUser = false
+ this.status(s, 'done', false, interrupted)
+ if (!interrupted) this.flushQueue(s)
}
}
}
@@ -153,7 +170,11 @@ export class ChatDriver {
interrupt(nodeId: string): void {
const s = this.sessions.get(nodeId)
- void s?.interrupt?.().catch(() => {})
+ if (!s) return
+ // Flag the turn as user-stopped BEFORE firing the SDK interrupt, so the turn-done it
+ // triggers is handled as a Stop (no auto-flush, interrupted status).
+ s.interruptedByUser = true
+ void s.interrupt?.().catch(() => {})
}
permissionReply(nodeId: string, requestId: string, decision: ChatPermissionDecision): void {
@@ -167,12 +188,23 @@ export class ChatDriver {
this.emit(nodeId, { kind: 'queue', items: s.queue.items() })
}
+ // Shared teardown for both dispose() and the fatal catch path: deny + clear every pending
+ // permission (resolving the awaiting canUseTool promise AND clearing its renderer card via
+ // permission-done), then end the input stream so the SDK query settles.
+ private teardown(s: ChatSession): void {
+ for (const [requestId, p] of s.pending) {
+ p.resolve({ behavior: 'deny' })
+ this.emit(s.nodeId, { kind: 'permission-done', requestId })
+ }
+ s.pending.clear()
+ s.input.end()
+ }
+
dispose(nodeId: string): void {
const s = this.sessions.get(nodeId)
if (!s) return
s.disposed = true
- for (const p of s.pending.values()) p.resolve({ behavior: 'deny' })
- s.input.end()
+ this.teardown(s)
void s.interrupt?.().catch(() => {})
this.sessions.delete(nodeId)
}
diff --git a/src/renderer/nodes/ChatNode.tsx b/src/renderer/nodes/ChatNode.tsx
index 90a8a32e3..717e94053 100644
--- a/src/renderer/nodes/ChatNode.tsx
+++ b/src/renderer/nodes/ChatNode.tsx
@@ -8,14 +8,15 @@ import {
useState,
type ClipboardEvent,
type DragEvent,
- type KeyboardEvent
+ type KeyboardEvent,
+ type Key
} from 'react'
import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'
import { MarkdownText } from './ChatPanel'
import { useChatSessions } from '../state/chatSessions'
import { useAgentStatus } from '../state/agentStatus'
import { createDiffNode, type CanvasNode } from '../state/workspace'
-import type { ChatImageAttachment } from '@shared/types'
+import type { ChatImageAttachment, ChatToolSummary } from '@shared/types'
const MAX_IMAGES = 5
const MAX_IMAGE_BYTES = 2 * 1024 * 1024 // 2 MB per image
@@ -197,6 +198,40 @@ export default function ChatNode({ id, data, selected }: NodeProps<CanvasNode>)
const working = !!chat?.working || status?.state === 'working'
const cwd = data.cwd as string | undefined
+ // Shared tool-card renderer for both live (toolOrder) and committed (folded into history at
+ // turn-done) tools, so both get the same summary label + diff-preview click treatment.
+ const renderTool = (
+ t: { name: string; arg: string; result?: string; summary?: ChatToolSummary },
+ key: Key,
+ open: boolean
+ ) => {
+ const diffPath = t.summary?.filePath
+ const canDiff = !!diffPath && !!cwd && diffPath.startsWith(cwd)
+ return (
+ <details key={key} className="term-chat__tool" open={open}>
+ <summary>
+ <span className="term-chat__tool-name">{t.name}</span>
+ <span
+ className={`term-chat__tool-arg${canDiff ? ' term-chat__tool-arg--link' : ''}`}
+ title={canDiff ? 'Open diff' : undefined}
+ onClick={
+ canDiff
+ ? (e) => {
+ e.preventDefault() // don't toggle the <details>
+ e.stopPropagation()
+ openDiff(diffPath)
+ }
+ : undefined
+ }
+ >
+ {t.summary ? `${t.summary.filePath} +${t.summary.added} −${t.summary.removed}` : t.arg}
+ </span>
+ </summary>
+ {t.result && <pre className="term-chat__tool-result">{t.result}</pre>}
+ </details>
+ )
+ }
+
return (
<div className={`chat-node${selected ? ' selected' : ''}`} style={{ borderTopColor: data.color }}>
<NodeResizer isVisible={selected} minWidth={360} minHeight={280} />
@@ -215,10 +250,7 @@ export default function ChatNode({ id, data, selected }: NodeProps<CanvasNode>)
) : p.kind === 'thinking' ? (
<details key={j} className="chat-node__thinking"><summary>Thinking</summary><MarkdownText text={p.text} /></details>
) : (
- <details key={j} className="term-chat__tool">
- <summary><span className="term-chat__tool-name">{p.name}</span><span className="term-chat__tool-arg">{p.arg}</span></summary>
- {p.result && <pre className="term-chat__tool-result">{p.result}</pre>}
- </details>
+ renderTool(p, j, false)
)
)}
</div>
@@ -227,34 +259,7 @@ export default function ChatNode({ id, data, selected }: NodeProps<CanvasNode>)
{chat?.streamThinking && (
<details className="chat-node__thinking"><summary>Thinking…</summary><MarkdownText text={chat.streamThinking} /></details>
)}
- {chat?.toolOrder.map((tid) => {
- const t = chat.tools[tid]
- const diffPath = t.summary?.filePath
- const canDiff = !!diffPath && !!cwd && diffPath.startsWith(cwd)
- return (
- <details key={tid} className="term-chat__tool" open={!t.result}>
- <summary>
- <span className="term-chat__tool-name">{t.name}</span>
- <span
- className={`term-chat__tool-arg${canDiff ? ' term-chat__tool-arg--link' : ''}`}
- title={canDiff ? 'Open diff' : undefined}
- onClick={
- canDiff
- ? (e) => {
- e.preventDefault() // don't toggle the <details>
- e.stopPropagation()
- openDiff(diffPath)
- }
- : undefined
- }
- >
- {t.summary ? `${t.summary.filePath} +${t.summary.added} −${t.summary.removed}` : t.arg}
- </span>
- </summary>
- {t.result && <pre className="term-chat__tool-result">{t.result}</pre>}
- </details>
- )
- })}
+ {chat?.toolOrder.map((tid) => renderTool(chat.tools[tid], tid, !chat.tools[tid].result))}
{chat?.streamText && <div className="term-chat__msg term-chat__msg--assistant"><MarkdownText text={chat.streamText} /></div>}
{/* Non-fatal errors: a dismissible inline line. Fatal errors get the reconnect bar
in place of the compose box (below). */}
diff --git a/src/renderer/state/chatSessions.ts b/src/renderer/state/chatSessions.ts
index bec644e4f..5cac44707 100644
--- a/src/renderer/state/chatSessions.ts
+++ b/src/renderer/state/chatSessions.ts
@@ -36,7 +36,10 @@ export const useChatSessions = create<ChatSessionsStore>((set) => ({
set((st) => {
const s = st.byId[nodeId]
if (!s) return {}
- return { byId: { ...st.byId, [nodeId]: { ...s, error: undefined } } }
+ // Clearing the error (Dismiss / Reconnect) must also drop a stale "working" badge and any
+ // orphaned permission card left behind by a fatal crash mid-turn — otherwise they survive
+ // the reconnect with no live driver behind them.
+ return { byId: { ...st.byId, [nodeId]: { ...s, error: undefined, working: false, permission: undefined } } }
}),
drop: (nodeId) =>
set((st) => {
diff --git a/src/renderer/state/chatSessionsCore.test.ts b/src/renderer/state/chatSessionsCore.test.ts
index 889866de2..24a8df76c 100644
--- a/src/renderer/state/chatSessionsCore.test.ts
+++ b/src/renderer/state/chatSessionsCore.test.ts
@@ -28,7 +28,7 @@ describe('applyChatEvent', () => {
})
it('turn-done accumulates cost, clears working + per-turn tool order', () => {
- let s = { ...s0, working: true, toolOrder: ['t1'] }
+ let s = { ...s0, working: true }
s = applyChatEvent(s, { kind: 'turn-done', costUsd: 0.1 })
s = applyChatEvent(s, { kind: 'turn-done', costUsd: 0.05 })
expect(s.costUsd).toBeCloseTo(0.15)
@@ -36,6 +36,32 @@ describe('applyChatEvent', () => {
expect(s.toolOrder).toEqual([])
})
+ it('turn-done folds the turn tools into a committed assistant message, then clears toolOrder', () => {
+ let s = applyChatEvent(s0, { kind: 'tool', toolUseId: 't1', name: 'Bash', arg: 'ls', summary: undefined })
+ s = applyChatEvent(s, { kind: 'tool', toolUseId: 't2', name: 'Write', arg: '/f.ts', summary: { filePath: '/f.ts', added: 3, removed: 0 } })
+ s = applyChatEvent(s, { kind: 'tool-result', toolUseId: 't1', result: 'out' })
+ s = applyChatEvent(s, { kind: 'turn-done', costUsd: 0.02 })
+ expect(s.toolOrder).toEqual([])
+ // A single synthetic assistant message carries both tools in order, preserving result + summary.
+ expect(s.messages).toEqual([
+ {
+ role: 'assistant',
+ parts: [
+ { kind: 'tool', name: 'Bash', arg: 'ls', result: 'out', summary: undefined },
+ { kind: 'tool', name: 'Write', arg: '/f.ts', result: undefined, summary: { filePath: '/f.ts', added: 3, removed: 0 } }
+ ]
+ }
+ ])
+ })
+
+ it('turn-done with no tools appends no message', () => {
+ let s = applyChatEvent(s0, { kind: 'message', msg: { role: 'assistant', parts: [{ kind: 'text', text: 'hi' }] } })
+ const before = s.messages
+ s = applyChatEvent(s, { kind: 'turn-done', costUsd: 0.01 })
+ expect(s.messages).toBe(before)
+ expect(s.toolOrder).toEqual([])
+ })
+
it('permission set + cleared', () => {
let s = applyChatEvent(s0, { kind: 'permission', requestId: 'r1', toolName: 'Bash', input: {} })
expect(s.permission?.requestId).toBe('r1')
diff --git a/src/renderer/state/chatSessionsCore.ts b/src/renderer/state/chatSessionsCore.ts
index 92a931d20..7329a5a89 100644
--- a/src/renderer/state/chatSessionsCore.ts
+++ b/src/renderer/state/chatSessionsCore.ts
@@ -49,11 +49,30 @@ export function applyChatEvent(s: ChatNodeState, e: ChatEvent): ChatNodeState {
return { ...s, permission: { requestId: e.requestId, toolName: e.toolName, input: e.input } }
case 'permission-done':
return s.permission?.requestId === e.requestId ? { ...s, permission: undefined } : s
- case 'turn-done':
+ case 'turn-done': {
+ // Tool calls stream as live cards (toolOrder) but the completed 'message' event carries
+ // only text/thinking. Before clearing toolOrder at turn end, fold this turn's tools into
+ // committed history as a synthetic assistant message so the cards (incl. diff-preview
+ // links) survive the turn instead of vanishing until a transcript reload.
+ const committed: ChatMessage[] =
+ s.toolOrder.length > 0
+ ? [
+ {
+ role: 'assistant',
+ parts: s.toolOrder.map((id) => {
+ const t = s.tools[id]
+ return { kind: 'tool', name: t.name, arg: t.arg, result: t.result, summary: t.summary }
+ })
+ }
+ ]
+ : []
return {
- ...s, working: false, toolOrder: [], streamText: '', streamThinking: '',
+ ...s,
+ messages: committed.length ? [...s.messages, ...committed] : s.messages,
+ working: false, toolOrder: [], streamText: '', streamThinking: '',
costUsd: s.costUsd + (e.costUsd ?? 0)
}
+ }
case 'queue':
return { ...s, queue: e.items }
case 'error':
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 77bbbda45..5aaf2c1f7 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -666,11 +666,13 @@ export interface TranscriptLine {
text: string
}
-/** One ordered piece of a chat message: prose, or a tool call with an optional result. */
+/** One ordered piece of a chat message: prose, or a tool call with an optional result.
+ * `summary` (present only on live-turn tools folded into history) carries the diff-preview
+ * metadata so committed tool cards keep the same summary/diff-click treatment as live ones. */
export type ChatPart =
| { kind: 'text'; text: string }
| { kind: 'thinking'; text: string }
- | { kind: 'tool'; name: string; arg: string; result?: string }
+ | { kind: 'tool'; name: string; arg: string; result?: string; summary?: ChatToolSummary }
/** A structured chat message reconstructed from a Claude session transcript. */
export interface ChatMessage {