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.

feat(chat): main-process ChatDriver + chat:* IPC wiring

enes2c51b715fd21
diff --git a/src/main/chat-driver.ts b/src/main/chat-driver.ts
new file mode 100644
index 000000000..d5168aa35
--- /dev/null
+++ b/src/main/chat-driver.ts
@@ -0,0 +1,183 @@
+// One long-lived Claude Agent SDK query per chat node (streaming input mode). The renderer
+// talks to this over the narrow chat:* IPC surface; SDK messages are reduced by
+// chat-events.ts and pushed on chat:event:<nodeId>. Continuity is resume-based: the
+// process dies with the app; the node's persisted chatSessionId resumes the transcript.
+import { IPC } from '../shared/ipc'
+import type { ChatEvent, ChatImageAttachment, ChatPermissionDecision } from '../shared/types'
+import type { NormalizedAgentEvent } from '../shared/agents/normalize'
+import { sdkMessageToEvents } from './chat-events'
+import { ChatInputQueue, createPushIterable } from './chat-queue'
+import { resolveTranscriptPath } from './transcript-reader'
+
+interface PendingPermission { resolve: (d: ChatPermissionDecision) => void }
+
+interface ChatSession {
+ nodeId: string
+ cwd?: string
+ sessionId?: string
+ working: boolean
+ input: ReturnType<typeof createPushIterable<unknown>>
+ queue: ChatInputQueue
+ pending: Map<string, PendingPermission>
+ allowedForSession: Set<string>
+ interrupt?: () => Promise<void>
+ disposed: boolean
+}
+
+type SendToMain = (channel: string, payload: unknown) => void
+
+// Minimal structural view of the send target. The codebase resolves the live window at send
+// time via getMainWindow() (returns MainWindowLike, never a raw BrowserWindow — capturing one
+// leaves a dead webContents after a macOS close→dock-reopen), so we accept anything that can
+// send on its webContents rather than the full BrowserWindow type.
+type WindowLike = { webContents: { send(channel: string, ...args: unknown[]): void } }
+
+export class ChatDriver {
+ private sessions = new Map<string, ChatSession>()
+ constructor(
+ private getWindow: () => WindowLike | null,
+ private sendToMain: SendToMain
+ ) {}
+
+ private emit(nodeId: string, event: ChatEvent): void {
+ this.getWindow()?.webContents.send(IPC.chatEvent(nodeId), event)
+ }
+
+ private status(s: ChatSession, state: 'working' | 'blocked' | 'done', newTurn = false): void {
+ const ev: NormalizedAgentEvent = {
+ nodeId: s.nodeId, agentId: 'claude', kind: 'state', state, newTurn,
+ sessionId: s.sessionId
+ }
+ this.sendToMain(IPC.agentStatus, ev)
+ }
+
+ async ensure(
+ nodeId: string,
+ opts: { cwd?: string; sessionId?: string; fork?: boolean }
+ ): Promise<{ ok: boolean; error?: string }> {
+ if (this.sessions.has(nodeId)) return { ok: true }
+ // Resume validation: a sessionId whose transcript is gone would silently start a
+ // fresh session with mismatched history — surface it instead.
+ let resume = opts.sessionId
+ if (resume && !(await resolveTranscriptPath(resume))) {
+ this.emit(nodeId, { kind: 'error', message: 'Previous session transcript not found — starting fresh.' })
+ resume = undefined
+ }
+ 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
+ }
+ 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 })
+ this.sessions.delete(nodeId)
+ })
+ return { ok: true }
+ }
+
+ private async run(s: ChatSession, resume: string | undefined, fork: boolean): Promise<void> {
+ // Task-1 spike result: the SDK runs under Electron main with no env/executable
+ // overrides (ELECTRON_RUN_AS_NODE inheritance is harmless), so no special spawn handling.
+ const { query } = await import('@anthropic-ai/claude-agent-sdk')
+ const q = query({
+ prompt: s.input.iterable as AsyncIterable<never>,
+ options: {
+ cwd: s.cwd,
+ ...(resume ? { resume } : {}),
+ ...(fork ? { forkSession: true } : {}),
+ includePartialMessages: true,
+ permissionMode: 'default',
+ canUseTool: async (toolName: string, input: Record<string, unknown>, { toolUseID }: { toolUseID: string }) => {
+ if (s.allowedForSession.has(toolName)) return { behavior: 'allow' as const, updatedInput: input }
+ const requestId = toolUseID
+ this.emit(s.nodeId, { kind: 'permission', requestId, toolName, input })
+ this.status(s, 'blocked')
+ const decision = await new Promise<ChatPermissionDecision>((resolve) => {
+ s.pending.set(requestId, { resolve })
+ })
+ s.pending.delete(requestId)
+ this.emit(s.nodeId, { kind: 'permission-done', requestId })
+ this.status(s, 'working')
+ if (decision.behavior === 'allow') {
+ if (decision.alwaysSession) s.allowedForSession.add(toolName)
+ return { behavior: 'allow' as const, updatedInput: input }
+ }
+ return { behavior: 'deny' as const, message: 'User denied in nodeterm chat.' }
+ }
+ }
+ })
+ s.interrupt = () => q.interrupt()
+ for await (const msg of q) {
+ if (s.disposed) break
+ for (const event of sdkMessageToEvents(msg as never)) {
+ if (event.kind === 'session') s.sessionId = event.sessionId
+ this.emit(s.nodeId, event)
+ if (event.kind === 'turn-done') {
+ s.working = false
+ this.status(s, 'done')
+ this.flushQueue(s)
+ }
+ }
+ }
+ }
+
+ private pushUser(s: ChatSession, text: string, images?: ChatImageAttachment[]): void {
+ const content: unknown = images?.length
+ ? [
+ ...images.map((i) => ({ type: 'image', source: { type: 'base64', media_type: i.mediaType, data: i.data } })),
+ { type: 'text', text }
+ ]
+ : text
+ s.input.push({ type: 'user', message: { role: 'user', content } })
+ s.working = true
+ this.status(s, 'working', true)
+ }
+
+ private flushQueue(s: ChatSession): void {
+ const next = s.queue.takeNext()
+ this.emit(s.nodeId, { kind: 'queue', items: s.queue.items() })
+ if (next) this.pushUser(s, next.text)
+ }
+
+ send(nodeId: string, text: string, images?: ChatImageAttachment[]): void {
+ const s = this.sessions.get(nodeId)
+ if (!s) return
+ if (s.working) {
+ s.queue.add(text) // images only send immediately in v1; queued items are text
+ this.emit(nodeId, { kind: 'queue', items: s.queue.items() })
+ return
+ }
+ this.pushUser(s, text, images)
+ }
+
+ interrupt(nodeId: string): void {
+ const s = this.sessions.get(nodeId)
+ void s?.interrupt?.().catch(() => {})
+ }
+
+ permissionReply(nodeId: string, requestId: string, decision: ChatPermissionDecision): void {
+ this.sessions.get(nodeId)?.pending.get(requestId)?.resolve(decision)
+ }
+
+ removeQueued(nodeId: string, queueId: string): void {
+ const s = this.sessions.get(nodeId)
+ if (!s) return
+ s.queue.remove(queueId)
+ this.emit(nodeId, { kind: 'queue', items: s.queue.items() })
+ }
+
+ 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()
+ void s.interrupt?.().catch(() => {})
+ this.sessions.delete(nodeId)
+ }
+
+ disposeAll(): void {
+ for (const id of [...this.sessions.keys()]) this.dispose(id)
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 598ef54dd..215be3c3a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -35,6 +35,7 @@ import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'
import { childArgs } from './remote-ssh/control-master'
import { posixQuote } from '../shared/ssh'
import { buildHandoff } from './handoff'
+import { ChatDriver } from './chat-driver'
import { initContextLink, setNodeTranscript } from './context-link'
import { initCanvasControl } from './canvas-control'
import { initTranscriptIndex, searchTranscripts } from './transcript-index'
@@ -77,6 +78,9 @@ const sshStore = new SshStore()
const ptyManager = new PtyManager()
const workspaceStore = new WorkspaceStore()
const gitService = new GitService()
+// One driver for all chat nodes. Resolves the live window at send time (getMainWindow) so
+// pushes survive a macOS close→dock-reopen; disposed on quit next to ptyManager.killAll().
+const chatDriver = new ChatDriver(getMainWindow, sendToMain)
// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters.
let sshProjectManager: ReturnType<typeof initSshProject> | undefined
@@ -528,6 +532,15 @@ app.whenReady().then(async () => {
(_e, sessionId: string, agentId: string, sourceNodeId: string, cwd: string | undefined) =>
buildHandoff({ sessionId, agentId, sourceNodeId, cwd })
)
+ // Chat nodes: one long-lived Claude Agent SDK query per node, bridged over chat:* IPC.
+ ipcMain.handle(IPC.chatEnsure, (_e, nodeId: string, opts) => chatDriver.ensure(nodeId, opts))
+ ipcMain.on(IPC.chatSend, (_e, nodeId: string, text: string, images) => chatDriver.send(nodeId, text, images))
+ ipcMain.on(IPC.chatInterrupt, (_e, nodeId: string) => chatDriver.interrupt(nodeId))
+ ipcMain.on(IPC.chatPermissionReply, (_e, nodeId: string, requestId: string, decision) =>
+ chatDriver.permissionReply(nodeId, requestId, decision))
+ ipcMain.on(IPC.chatRemoveQueued, (_e, nodeId: string, queueId: string) => chatDriver.removeQueued(nodeId, queueId))
+ ipcMain.on(IPC.chatDispose, (_e, nodeId: string) => chatDriver.dispose(nodeId))
+
installManagedAgentHooks()
hookServer.setListener((e) => sendToMain(IPC.agentStatus, e))
// Security: hook POSTs now arrive over the remote reverse tunnel too (SSH Phase 2a), so a
@@ -769,6 +782,7 @@ let quitFlushed = false
app.on('before-quit', (e) => {
quitting = true // from here on, window close-events must NOT be turned into hide
sshProjectManager?.disconnectAll()
+ chatDriver.disposeAll() // tear down every chat node's SDK query (resume-based, so this is safe)
if (quitFlushed) return
quitFlushed = true
e.preventDefault()