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(ssh-p2b): extract pure transcript parsers + remote-file reader

enes1afdac659436
diff --git a/src/main/context-tail.test.ts b/src/main/context-tail.test.ts
new file mode 100644
index 000000000..98fd44068
--- /dev/null
+++ b/src/main/context-tail.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest'
+import { parseLatestUsage } from './context-tail'
+
+describe('parseLatestUsage', () => {
+ it('returns the LAST assistant usage in the text (sum of input + cache tokens)', () => {
+ const text = [
+ JSON.stringify({ type: 'assistant', message: { model: 'claude-x', usage: { input_tokens: 10, cache_read_input_tokens: 5 } } }),
+ JSON.stringify({ type: 'user', message: {} }),
+ JSON.stringify({ type: 'assistant', message: { model: 'claude-y', usage: { input_tokens: 100, cache_creation_input_tokens: 20 } } })
+ ].join('\n')
+ expect(parseLatestUsage(text)).toEqual({ used: 120, model: 'claude-y' })
+ })
+ it('ignores non-assistant lines, zero-usage, and garbled JSON; null when none', () => {
+ expect(parseLatestUsage('not json\n{"type":"assistant","message":{"usage":{"input_tokens":0}}}')).toBeNull()
+ expect(parseLatestUsage('')).toBeNull()
+ })
+})
diff --git a/src/main/context-tail.ts b/src/main/context-tail.ts
index d274fb3cb..09619ca6a 100644
--- a/src/main/context-tail.ts
+++ b/src/main/context-tail.ts
@@ -15,6 +15,32 @@ const POLL_MS = 1000
// line is dropped naturally by the JSON.parse guard.
const INITIAL_READ_CAP = 1024 * 1024 // 1 MB
+/** Scan transcript text for the LATEST assistant message's token usage + model. Pure. */
+export function parseLatestUsage(text: string): { used: number; model: string | null } | null {
+ let found = false
+ let usedTokens = 0
+ let model: string | null = null
+ for (const line of text.split('\n')) {
+ const s = line.trim()
+ if (!s) continue
+ let o: { type?: string; message?: { model?: string; usage?: Record<string, number> } }
+ try {
+ o = JSON.parse(s)
+ } catch {
+ continue
+ }
+ if (o.type !== 'assistant' || !o.message?.usage) continue
+ const u = o.message.usage
+ const used =
+ (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
+ if (used <= 0) continue
+ found = true
+ usedTokens = used
+ model = o.message.model ?? model // carry the prior model forward when this line omits it
+ }
+ return found ? { used: usedTokens, model } : null
+}
+
interface Tracked {
path: string
offset: number
@@ -77,24 +103,10 @@ export function createContextTail(win: BrowserWindow): ContextTail {
} catch {
return
}
- for (const line of chunk.split('\n')) {
- const s = line.trim()
- if (!s) continue
- let o: { type?: string; message?: { model?: string; usage?: Record<string, number> } }
- try {
- o = JSON.parse(s)
- } catch {
- continue // partial/garbled line
- }
- if (o.type !== 'assistant' || !o.message?.usage) continue
- const u = o.message.usage
- const used =
- (u.input_tokens ?? 0) +
- (u.cache_read_input_tokens ?? 0) +
- (u.cache_creation_input_tokens ?? 0)
- if (used <= 0) continue
- t.used = used
- t.model = o.message.model ?? t.model
+ const latest = parseLatestUsage(chunk)
+ if (latest) {
+ t.used = latest.used
+ t.model = latest.model ?? t.model
}
}
}
diff --git a/src/main/remote-ssh/remote-file.test.ts b/src/main/remote-ssh/remote-file.test.ts
new file mode 100644
index 000000000..43f015da1
--- /dev/null
+++ b/src/main/remote-ssh/remote-file.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from 'vitest'
+import { tailFromOffsetArgs, tailLastBytesArgs, RemoteFile } from './remote-file'
+
+const conn = { host: 'h', user: 'u' }
+const ref = { conn, controlPath: '/s.sock', path: '/home/u/.claude/projects/p/x.jsonl' }
+
+describe('remote-file builders', () => {
+ it('tailFromOffsetArgs reads bytes after the offset (1-indexed +N)', () => {
+ expect(tailFromOffsetArgs(conn, '/s.sock', '/a b.jsonl', 10).join(' '))
+ .toContain(`tail -c +11 '/a b.jsonl'`)
+ })
+ it('tailLastBytesArgs reads the last N bytes', () => {
+ expect(tailLastBytesArgs(conn, '/s.sock', '/a.jsonl', 4096).join(' ')).toContain(`tail -c 4096 '/a.jsonl'`)
+ })
+})
+
+describe('RemoteFile', () => {
+ it('readFrom advances offset by the byte length of the returned text', async () => {
+ const run = vi.fn(async () => ({ code: 0, stdout: 'hello\n' }))
+ const rf = new RemoteFile(run)
+ expect(await rf.readFrom(ref, 100)).toEqual({ text: 'hello\n', newOffset: 100 + Buffer.byteLength('hello\n') })
+ })
+ it('readFrom fails open: non-zero code → empty, offset unchanged', async () => {
+ const rf = new RemoteFile(async () => ({ code: 1, stdout: '' }))
+ expect(await rf.readFrom(ref, 100)).toEqual({ text: '', newOffset: 100 })
+ })
+ it('readTail returns stdout (empty on failure)', async () => {
+ expect(await new RemoteFile(async () => ({ code: 0, stdout: 'X' })).readTail(ref, 10)).toBe('X')
+ expect(await new RemoteFile(async () => ({ code: 1, stdout: '' })).readTail(ref, 10)).toBe('')
+ })
+})
diff --git a/src/main/remote-ssh/remote-file.ts b/src/main/remote-ssh/remote-file.ts
new file mode 100644
index 000000000..0fc93d143
--- /dev/null
+++ b/src/main/remote-ssh/remote-file.ts
@@ -0,0 +1,42 @@
+// Reads remote files over the project's existing ControlMaster (`ssh <childArgs> 'tail …'`).
+// Pure builders + an injected-runner class so the read logic is electron-free and unit-testable;
+// the actual ssh spawn is injected by the caller (Tasks 2/3 wire it to the project's runner).
+import { childArgs } from './control-master'
+import { posixQuote, type SshConnection } from '../../shared/ssh'
+
+export interface RemoteFileRef {
+ conn: SshConnection
+ controlPath: string
+ path: string
+}
+
+export function tailFromOffsetArgs(conn: SshConnection, controlPath: string, path: string, offset: number): string[] {
+ return childArgs(conn, controlPath, `tail -c +${offset + 1} ${posixQuote(path)}`)
+}
+export function tailLastBytesArgs(conn: SshConnection, controlPath: string, path: string, bytes: number): string[] {
+ return childArgs(conn, controlPath, `tail -c ${bytes} ${posixQuote(path)}`)
+}
+
+/** Reads a remote file over the project's ControlMaster. Fail-open: errors → empty. */
+export class RemoteFile {
+ constructor(private run: (args: string[]) => Promise<{ code: number; stdout: string }>) {}
+
+ async readFrom(ref: RemoteFileRef, offset: number): Promise<{ text: string; newOffset: number }> {
+ try {
+ const { code, stdout } = await this.run(tailFromOffsetArgs(ref.conn, ref.controlPath, ref.path, offset))
+ if (code !== 0) return { text: '', newOffset: offset }
+ return { text: stdout, newOffset: offset + Buffer.byteLength(stdout) }
+ } catch {
+ return { text: '', newOffset: offset }
+ }
+ }
+
+ async readTail(ref: RemoteFileRef, bytes: number): Promise<string> {
+ try {
+ const { code, stdout } = await this.run(tailLastBytesArgs(ref.conn, ref.controlPath, ref.path, bytes))
+ return code === 0 ? stdout : ''
+ } catch {
+ return ''
+ }
+ }
+}
diff --git a/src/main/subagent-tail.test.ts b/src/main/subagent-tail.test.ts
new file mode 100644
index 000000000..c9bfd95ec
--- /dev/null
+++ b/src/main/subagent-tail.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { formatSubagentChunk } from './subagent-tail'
+
+describe('formatSubagentChunk', () => {
+ it('formats assistant prose + tool_use across lines, dropping blanks/garbled', () => {
+ const text = [
+ JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'hi' }] } }),
+ '',
+ 'garbled',
+ JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Bash', input: { command: 'ls' } }] } })
+ ].join('\n')
+ // formatLine emits assistant text verbatim ('hi') and tool_use as `$ <name> <arg>` ('$ Bash ls');
+ // the chunk joins surviving lines with '\n' (mirrors the tail's read loop exactly).
+ expect(formatSubagentChunk(text)).toBe('hi\n$ Bash ls')
+ })
+})
diff --git a/src/main/subagent-tail.ts b/src/main/subagent-tail.ts
index a9db492e5..7472ae0a3 100644
--- a/src/main/subagent-tail.ts
+++ b/src/main/subagent-tail.ts
@@ -58,7 +58,7 @@ function summarizeResult(content: unknown): string {
// Render one transcript line as a clean activity log: assistant prose verbatim,
// tool calls as `$ Tool arg`, tool results as a one-line summary. Skips metadata.
-function formatLine(line: string): string {
+export function formatLine(line: string): string {
let o: { type?: string; message?: { content?: unknown } }
try {
o = JSON.parse(line)
@@ -92,6 +92,18 @@ function formatLine(line: string): string {
return ''
}
+// Format a chunk of newly-read transcript bytes into the activity-log text streamed to the
+// renderer: drop blank lines, format each surviving line, drop empties, join with '\n'.
+// Mirrors the tail read loop exactly so local + remote streamed output stay byte-identical.
+export function formatSubagentChunk(text: string): string {
+ return text
+ .split('\n')
+ .filter(Boolean)
+ .map(formatLine)
+ .filter(Boolean)
+ .join('\n')
+}
+
export interface SubagentTail {
track(toolUseId: string, transcriptPath: string | undefined): void
finish(toolUseId: string): void
@@ -135,13 +147,7 @@ export function createSubagentTail(win: BrowserWindow): SubagentTail {
fs.readSync(fd, buf, 0, buf.length, e.offset)
fs.closeSync(fd)
e.offset = size
- const out = buf
- .toString('utf-8')
- .split('\n')
- .filter(Boolean)
- .map(formatLine)
- .filter(Boolean)
- .join('\n')
+ const out = formatSubagentChunk(buf.toString('utf-8'))
if (out) send(toolUseId, out + '\n')
} catch {
// file may not exist yet / transient read error
diff --git a/src/main/transcript-reader.test.ts b/src/main/transcript-reader.test.ts
new file mode 100644
index 000000000..26aa861b3
--- /dev/null
+++ b/src/main/transcript-reader.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+import { parseTranscriptLines } from './transcript-reader'
+import type { TranscriptLine } from '../shared/types'
+
+describe('parseTranscriptLines', () => {
+ it('maps each JSONL line to TranscriptLine[] (role/text), mirroring the reader', () => {
+ const text = [
+ JSON.stringify({
+ type: 'assistant',
+ message: {
+ content: [
+ { type: 'text', text: 'hello' },
+ { type: 'tool_use', name: 'Read', input: { file_path: '/a/b/workspace.ts' } }
+ ]
+ }
+ }),
+ JSON.stringify({
+ type: 'user',
+ message: {
+ content: [
+ { type: 'text', text: 'do it' },
+ { type: 'tool_result', content: 'line one\nline two\nline three\nline four' }
+ ]
+ }
+ }),
+ JSON.stringify({ type: 'user', message: { content: 'plain user' } }),
+ '',
+ 'garbled'
+ ].join('\n')
+ const expected: TranscriptLine[] = [
+ { role: 'assistant', text: 'hello' },
+ { role: 'tool', text: '$ Read /a/b/workspace.ts' },
+ { role: 'user', text: 'do it' },
+ { role: 'tool', text: 'line one line two line three' },
+ { role: 'user', text: 'plain user' }
+ ]
+ expect(parseTranscriptLines(text)).toEqual(expected)
+ })
+})
diff --git a/src/main/transcript-reader.ts b/src/main/transcript-reader.ts
index 4d08f83ce..dac7e8223 100644
--- a/src/main/transcript-reader.ts
+++ b/src/main/transcript-reader.ts
@@ -91,16 +91,22 @@ async function readCappedTail(filePath: string): Promise<string | undefined> {
}
}
-export async function readTranscriptLines(filePath: string): Promise<TranscriptLine[]> {
- const buf = await readCappedTail(filePath)
- if (buf === undefined) return []
+// Parse transcript text into flat searchable lines. Pure — splits on newlines and maps each
+// non-blank line via linesFrom. Reused by the remote reader (which fetches the text over SSH).
+export function parseTranscriptLines(text: string): TranscriptLine[] {
const lines: TranscriptLine[] = []
- for (const raw of buf.split('\n')) {
+ for (const raw of text.split('\n')) {
if (raw.trim()) lines.push(...linesFrom(raw))
}
return lines
}
+export async function readTranscriptLines(filePath: string): Promise<TranscriptLine[]> {
+ const buf = await readCappedTail(filePath)
+ if (buf === undefined) return []
+ return parseTranscriptLines(buf)
+}
+
// 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