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): structured transcript reader + chat:read-transcript IPC

enesfc0f878f122b
diff --git a/src/main/index.ts b/src/main/index.ts
index 13377efbb..7648dd193 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -15,6 +15,7 @@ import { createSubagentTail } from './subagent-tail'
import { createContextTail } from './context-tail'
import {
readTranscriptLines,
+ readChatMessages,
resolveTranscriptPath,
transcriptPathForCwd,
SESSION_ID_RE
@@ -205,19 +206,36 @@ app.whenReady().then(async () => {
// which need the raw transcript_path the NormalizedAgentEvent intentionally drops.
const subagentTail = createSubagentTail(win)
const contextTail = createContextTail(win)
+ // Resolve a session's transcript path: prefer the exact session path when a (valid)
+ // sessionId is known; otherwise fall back to the node's cwd, which is durable and doesn't
+ // need a live hook event.
+ const resolveTranscript = async (
+ sessionId: string | undefined,
+ cwd: string | undefined
+ ): Promise<string | undefined> => {
+ let p: string | undefined
+ if (sessionId && SESSION_ID_RE.test(sessionId)) {
+ p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId))
+ }
+ if (!p && cwd) p = await transcriptPathForCwd(cwd)
+ return p
+ }
+
ipcMain.handle(
IPC.claudeReadTranscript,
async (_e, sessionId: string | undefined, cwd: string | undefined) => {
- // Prefer the exact session path when a (valid) sessionId is known; otherwise fall
- // back to the node's cwd, which is durable and doesn't need a live hook event.
- let p: string | undefined
- if (sessionId && SESSION_ID_RE.test(sessionId)) {
- p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId))
- }
- if (!p && cwd) p = await transcriptPathForCwd(cwd)
+ const p = await resolveTranscript(sessionId, cwd)
return p ? readTranscriptLines(p) : []
}
)
+
+ ipcMain.handle(
+ IPC.chatReadTranscript,
+ async (_e, sessionId: string | undefined, cwd: string | undefined) => {
+ const p = await resolveTranscript(sessionId, cwd)
+ return p ? readChatMessages(p) : []
+ }
+ )
// Populate the context meter without a live hook event: the renderer calls this on mount
// (the continuing session may be idle after a restart). Track under the sessionId (the key
// the meter looks up); cwd is only a path fallback. contextTail.track reads immediately and
diff --git a/src/main/transcript-reader.ts b/src/main/transcript-reader.ts
index 1210f5845..f0d979b00 100644
--- a/src/main/transcript-reader.ts
+++ b/src/main/transcript-reader.ts
@@ -4,7 +4,7 @@
import fs from 'fs'
import os from 'os'
import path from 'path'
-import type { TranscriptLine } from '../shared/types'
+import type { TranscriptLine, ChatMessage, ChatPart } from '../shared/types'
// Only read the last ~5 MB of a transcript so a very large session can't block the main
// process. The older head is dropped silently (search is most useful on recent context).
@@ -64,8 +64,9 @@ function linesFrom(raw: string): TranscriptLine[] {
return out
}
-export async function readTranscriptLines(filePath: string): Promise<TranscriptLine[]> {
- let buf: string
+// Read the last ~READ_CAP_BYTES of the file as UTF-8 (dropping the partial leading line on a
+// capped read), or the whole file when it's small. Returns undefined if it can't be read.
+async function readCappedTail(filePath: string): Promise<string | undefined> {
try {
const stat = await fs.promises.stat(filePath)
if (stat.size > READ_CAP_BYTES) {
@@ -77,18 +78,22 @@ export async function readTranscriptLines(filePath: string): Promise<TranscriptL
length: READ_CAP_BYTES,
buffer: Buffer.alloc(READ_CAP_BYTES)
})
- buf = buffer.toString('utf8')
+ const s = buffer.toString('utf8')
+ const nl = s.indexOf('\n') // drop the first (partial) line
+ return nl >= 0 ? s.slice(nl + 1) : s
} finally {
await fd.close()
}
- const nl = buf.indexOf('\n') // drop the first (partial) line
- if (nl >= 0) buf = buf.slice(nl + 1)
- } else {
- buf = await fs.promises.readFile(filePath, 'utf8')
}
+ return await fs.promises.readFile(filePath, 'utf8')
} catch {
- return []
+ return undefined
}
+}
+
+export async function readTranscriptLines(filePath: string): Promise<TranscriptLine[]> {
+ const buf = await readCappedTail(filePath)
+ if (buf === undefined) return []
const lines: TranscriptLine[] = []
for (const raw of buf.split('\n')) {
if (raw.trim()) lines.push(...linesFrom(raw))
@@ -96,6 +101,71 @@ export async function readTranscriptLines(filePath: string): Promise<TranscriptL
return lines
}
+// Reconstruct structured chat messages from raw transcript JSONL lines. An assistant line's
+// text + tool_use blocks become one message's ordered parts; a later user-line tool_result is
+// correlated back onto its tool part by tool_use_id. User lines that carry only tool_results
+// (no prose) are NOT rendered as bubbles — they're tool output, attached to the tool instead.
+export function parseChatMessages(rawLines: string[]): ChatMessage[] {
+ const messages: ChatMessage[] = []
+ const toolById = new Map<string, Extract<ChatPart, { kind: 'tool' }>>()
+ for (const raw of rawLines) {
+ if (!raw.trim()) continue
+ let o: { type?: string; message?: { content?: unknown } }
+ try {
+ o = JSON.parse(raw)
+ } catch {
+ continue
+ }
+ const content = o.message?.content
+ if (o.type === 'assistant' && Array.isArray(content)) {
+ const parts: ChatPart[] = []
+ for (const c of content as Array<{
+ type?: string
+ text?: string
+ name?: string
+ id?: string
+ input?: unknown
+ }>) {
+ if (c.type === 'text' && c.text) parts.push({ kind: 'text', text: c.text })
+ else if (c.type === 'tool_use') {
+ const part: Extract<ChatPart, { kind: 'tool' }> = {
+ kind: 'tool',
+ name: c.name ?? 'tool',
+ arg: toolArg(c.input)
+ }
+ parts.push(part)
+ if (c.id) toolById.set(c.id, part)
+ }
+ }
+ if (parts.length) messages.push({ role: 'assistant', parts })
+ } else if (o.type === 'user' && Array.isArray(content)) {
+ const parts: ChatPart[] = []
+ for (const c of content as Array<{
+ type?: string
+ text?: string
+ tool_use_id?: string
+ content?: unknown
+ }>) {
+ if (c.type === 'text' && c.text) parts.push({ kind: 'text', text: c.text })
+ else if (c.type === 'tool_result') {
+ const tool = c.tool_use_id ? toolById.get(c.tool_use_id) : undefined
+ if (tool) tool.result = summarizeResult(c.content)
+ }
+ }
+ if (parts.length) messages.push({ role: 'user', parts })
+ } else if (o.type === 'user' && typeof content === 'string' && content.trim()) {
+ messages.push({ role: 'user', parts: [{ kind: 'text', text: content }] })
+ }
+ }
+ return messages
+}
+
+export async function readChatMessages(filePath: string): Promise<ChatMessage[]> {
+ const buf = await readCappedTail(filePath)
+ if (buf === undefined) return []
+ return parseChatMessages(buf.split('\n'))
+}
+
// Claude session ids are UUID-like (hex + dashes). Reject anything else before it
// touches the filesystem — this alone prevents path traversal (no '/' or '.' possible).
export const SESSION_ID_RE = /^[0-9a-fA-F-]{8,64}$/
diff --git a/src/preload/index.ts b/src/preload/index.ts
index c994084df..1c016892d 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -176,6 +176,10 @@ const api: NodeTerminalApi = {
readTranscript: (sessionId, cwd) =>
ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd)
},
+ chat: {
+ readTranscript: (sessionId, cwd) =>
+ ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd)
+ },
remoteHost: {
start: () => ipcRenderer.invoke(IPC.remoteHostStart),
stop: () => ipcRenderer.invoke(IPC.remoteHostStop),
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 4a887be74..4a3bcf2cc 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -51,6 +51,8 @@ export const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cron
export const BRANCH_CAPABLE = ['claude'] as const
export const CONTEXT_LINK_CAPABLE = ['claude'] as const
export const USAGE_CAPABLE = ['claude'] as const
+// Agents whose structured transcript we can render as a chat panel (Cmd+M chat mode).
+export const CHAT_CAPABLE = ['claude'] as const
// Agents whose native transcript we can read + render for cross-agent transfer.
export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini'] as const
@@ -63,6 +65,7 @@ export const canRecur = (id: AgentId): boolean => includes(RECURRING_CAPABLE, id
export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)
export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAPABLE, id)
export const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)
+export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)
export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURCE_CAPABLE, id)
// Returns the builtin config for an id, or undefined for custom/unknown agents.
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 4097ef6ab..0606391cc 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -11,6 +11,7 @@ export const IPC = {
ptyCapture: 'pty:capture',
ptySendText: 'pty:send-text',
claudeReadTranscript: 'claude:read-transcript',
+ chatReadTranscript: 'chat:read-transcript',
appToggleMarkdown: 'app:toggle-markdown',
appCloseNode: 'app:close-node',
appCloseWindow: 'app:close-window',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index aa4da64b8..3d372d3f3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -490,6 +490,29 @@ export interface TranscriptLine {
text: string
}
+/** One ordered piece of a chat message: prose, or a tool call with an optional result. */
+export type ChatPart =
+ | { kind: 'text'; text: string }
+ | { kind: 'tool'; name: string; arg: string; result?: string }
+
+/** A structured chat message reconstructed from a Claude session transcript. */
+export interface ChatMessage {
+ role: 'user' | 'assistant'
+ parts: ChatPart[]
+}
+
+export interface ChatApi {
+ /**
+ * Reads a Claude session transcript as structured chat messages ([] if unavailable).
+ * Resolves the transcript like `ClaudeApi.readTranscript` (sessionId → cwd), then
+ * reconstructs ordered bubbles + tool calls.
+ */
+ readTranscript(
+ sessionId: string | undefined,
+ cwd: string | undefined
+ ): Promise<ChatMessage[]>
+}
+
export interface ClaudeApi {
/**
* Reads a Claude session's full transcript as flat searchable lines ([] if unavailable).
@@ -626,6 +649,7 @@ export interface NodeTerminalApi {
usage: UsageApi
context: ContextApi
claude: ClaudeApi
+ chat: ChatApi
remoteHost: RemoteHostApi
remoteClient: RemoteClientApi
handoff: HandoffApi