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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(chat): pure SDK-message → ChatEvent reducer
enesfd9af21e9889
diff --git a/src/main/chat-events.test.ts b/src/main/chat-events.test.tsnew file mode 100644index 000000000..71fef1fe3--- /dev/null+++ b/src/main/chat-events.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest'+import { sdkMessageToEvents, summarizeToolInput } from './chat-events'++describe('sdkMessageToEvents', () => {+ it('maps init system message to session event', () => {+ const ev = sdkMessageToEvents({+ type: 'system', subtype: 'init', session_id: 'abc', slash_commands: ['/compact']+ })+ expect(ev).toEqual([{ kind: 'session', sessionId: 'abc', slashCommands: ['/compact'] }])+ })++ it('maps text and thinking deltas', () => {+ expect(sdkMessageToEvents({+ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'he' } }+ })).toEqual([{ kind: 'delta', block: 'text', text: 'he' }])+ expect(sdkMessageToEvents({+ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'thinking_delta', thinking: 'hm' } }+ })).toEqual([{ kind: 'delta', block: 'thinking', text: 'hm' }])+ })++ it('maps a completed assistant message to message + tool events', () => {+ const ev = sdkMessageToEvents({+ type: 'assistant',+ message: {+ role: 'assistant',+ content: [+ { type: 'text', text: 'done' },+ { type: 'tool_use', id: 't1', name: 'Edit', input: { file_path: '/a/b.ts', old_string: 'x\ny', new_string: 'z' } }+ ]+ }+ })+ expect(ev[0]).toEqual({ kind: 'message', msg: { role: 'assistant', parts: [{ kind: 'text', text: 'done' }] } })+ expect(ev[1]).toMatchObject({ kind: 'tool', toolUseId: 't1', name: 'Edit', summary: { filePath: '/a/b.ts' } })+ })++ it('maps tool results from user messages', () => {+ const ev = sdkMessageToEvents({+ type: 'user',+ message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] }+ })+ expect(ev).toEqual([{ kind: 'tool-result', toolUseId: 't1', result: 'ok' }])+ })++ it('maps result to turn-done with cost and usage', () => {+ const ev = sdkMessageToEvents({+ type: 'result', subtype: 'success', total_cost_usd: 0.12,+ usage: { input_tokens: 10, output_tokens: 20 }+ })+ expect(ev).toEqual([{ kind: 'turn-done', costUsd: 0.12, usage: { inputTokens: 10, outputTokens: 20 } }])+ })++ it('maps error result subtypes to turn-done + error', () => {+ const ev = sdkMessageToEvents({ type: 'result', subtype: 'error_max_turns', total_cost_usd: 0.01 })+ expect(ev[0].kind).toBe('turn-done')+ expect(ev[1]).toMatchObject({ kind: 'error', fatal: false })+ })++ it('ignores unknown messages', () => {+ expect(sdkMessageToEvents({ type: 'whatever' })).toEqual([])+ })+})++describe('summarizeToolInput', () => {+ it('summarizes Edit with line counts from old/new strings', () => {+ const s = summarizeToolInput('Edit', { file_path: '/x.ts', old_string: 'a\nb', new_string: 'c' })+ expect(s.summary).toEqual({ filePath: '/x.ts', added: 1, removed: 2 })+ expect(s.arg).toBe('/x.ts')+ })+ it('summarizes Write as all-added', () => {+ const s = summarizeToolInput('Write', { file_path: '/x.ts', content: 'a\nb\nc' })+ expect(s.summary).toEqual({ filePath: '/x.ts', added: 3, removed: 0 })+ })+ it('falls back to a compact arg for other tools', () => {+ const s = summarizeToolInput('Bash', { command: 'ls -la' })+ expect(s.arg).toBe('ls -la')+ expect(s.summary).toBeUndefined()+ })+})diff --git a/src/main/chat-events.ts b/src/main/chat-events.tsnew file mode 100644index 000000000..ad9d91de0--- /dev/null+++ b/src/main/chat-events.ts@@ -0,0 +1,92 @@+// Pure reducer: one SDK message (structurally typed — no SDK import, so tests use plain+// JSON fixtures) → zero or more ChatEvents for the renderer. Owned by chat-driver.ts.+import type { ChatEvent, ChatMessage, ChatPart, ChatToolSummary } from '../shared/types'++/** The subset of SDK message shapes we consume, typed structurally. */+export interface SdkMessageLike {+ type?: string+ subtype?: string+ session_id?: string+ slash_commands?: string[]+ total_cost_usd?: number+ usage?: { input_tokens?: number; output_tokens?: number }+ event?: { type?: string; delta?: { type?: string; text?: string; thinking?: string } }+ message?: { role?: string; content?: unknown }+}++const lines = (s: unknown): number => (typeof s === 'string' && s.length ? s.split('\n').length : 0)++/** Compact one-line arg + optional file/line summary for a tool_use block. */+export function summarizeToolInput(+ name: string,+ input: Record<string, unknown>+): { arg: string; summary?: ChatToolSummary } {+ const filePath = typeof input.file_path === 'string' ? input.file_path : undefined+ if ((name === 'Edit' || name === 'MultiEdit') && filePath) {+ return { arg: filePath, summary: { filePath, added: lines(input.new_string), removed: lines(input.old_string) } }+ }+ if (name === 'Write' && filePath) {+ return { arg: filePath, summary: { filePath, added: lines(input.content), removed: 0 } }+ }+ const first = input.command ?? input.file_path ?? input.pattern ?? input.url ?? input.prompt+ const arg = typeof first === 'string' ? first : JSON.stringify(input ?? {})+ return { arg: arg.length > 200 ? arg.slice(0, 200) + '…' : arg }+}++const toolResultText = (content: unknown): string => {+ if (typeof content === 'string') return content+ if (Array.isArray(content))+ return content+ .map((b) => (b && typeof b === 'object' && 'text' in b ? String((b as { text: unknown }).text) : ''))+ .join('\n')+ return ''+}++export function sdkMessageToEvents(msg: SdkMessageLike): ChatEvent[] {+ if (msg.type === 'system' && msg.subtype === 'init' && msg.session_id) {+ return [{ kind: 'session', sessionId: msg.session_id, slashCommands: msg.slash_commands ?? [] }]+ }+ if (msg.type === 'stream_event') {+ const d = msg.event?.delta+ if (msg.event?.type === 'content_block_delta' && d) {+ if (d.type === 'text_delta' && d.text) return [{ kind: 'delta', block: 'text', text: d.text }]+ if (d.type === 'thinking_delta' && d.thinking) return [{ kind: 'delta', block: 'thinking', text: d.thinking }]+ }+ return []+ }+ if (msg.type === 'assistant' && Array.isArray((msg.message as { content?: unknown })?.content)) {+ const out: ChatEvent[] = []+ const parts: ChatPart[] = []+ for (const block of (msg.message as { content: Array<Record<string, unknown>> }).content) {+ if (block.type === 'text' && typeof block.text === 'string') parts.push({ kind: 'text', text: block.text })+ else if (block.type === 'thinking' && typeof block.thinking === 'string')+ parts.push({ kind: 'thinking', text: block.thinking })+ else if (block.type === 'tool_use' && typeof block.id === 'string' && typeof block.name === 'string') {+ const { arg, summary } = summarizeToolInput(block.name, (block.input as Record<string, unknown>) ?? {})+ out.push({ kind: 'tool', toolUseId: block.id, name: block.name, arg, summary })+ }+ }+ const msgEvent: ChatEvent[] = parts.length+ ? [{ kind: 'message', msg: { role: 'assistant', parts } satisfies ChatMessage }]+ : []+ return [...msgEvent, ...out]+ }+ if (msg.type === 'user' && Array.isArray((msg.message as { content?: unknown })?.content)) {+ const out: ChatEvent[] = []+ for (const block of (msg.message as { content: Array<Record<string, unknown>> }).content) {+ if (block.type === 'tool_result' && typeof block.tool_use_id === 'string')+ out.push({ kind: 'tool-result', toolUseId: block.tool_use_id, result: toolResultText(block.content) })+ }+ return out+ }+ if (msg.type === 'result') {+ const usage = msg.usage+ ? { inputTokens: msg.usage.input_tokens ?? 0, outputTokens: msg.usage.output_tokens ?? 0 }+ : undefined+ const done: ChatEvent = { kind: 'turn-done', costUsd: msg.total_cost_usd, usage }+ if (msg.subtype && msg.subtype !== 'success')+ return [done, { kind: 'error', message: `Turn ended: ${msg.subtype}`, fatal: false }]+ return [done]+ }+ return []+}