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
fix(agents): don't lose subagent transcript lines torn mid-write
enesc27013872cf1
diff --git a/src/main/remote-subagent-tail.test.ts b/src/main/remote-subagent-tail.test.tsindex 4798eb617..d51eb352e 100644--- a/src/main/remote-subagent-tail.test.ts+++ b/src/main/remote-subagent-tail.test.ts@@ -38,6 +38,27 @@ describe('createRemoteSubagentTail', () => {tail.untrack('tool-1')})+ it('does not drop a line served torn across two reads', async () => {+ const { win, send } = fakeWin()+ const raw = assistant('remote torn line')+ // The remote `tail -c +N` can return a line mid-write; the second read completes it.+ const parts = [raw.slice(0, 15), raw.slice(15) + '\n']+ let i = 0+ const remoteFile = {+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {+ const text = parts[i] ?? ''+ i+++ return { text, newOffset: o + Buffer.byteLength(text) }+ })+ }+ const tail = createRemoteSubagentTail(win, remoteFile as never)+ tail.track('tool-3', ref) // immediate first read gets the partial line+ await new Promise((r) => setTimeout(r, 1100)) // next poll (1s) reads the rest+ const streamed = send.mock.calls.map((c) => (c[1] as { chunk: string }).chunk).join('')+ expect(streamed).toContain('remote torn line')+ tail.untrack('tool-3')+ }, 5000)+it('does not send when the chunk is empty', async () => {const { win, send } = fakeWin()const remoteFile = {diff --git a/src/main/remote-subagent-tail.ts b/src/main/remote-subagent-tail.tsindex 72adf5959..562fc9ab7 100644--- a/src/main/remote-subagent-tail.ts+++ b/src/main/remote-subagent-tail.ts@@ -9,7 +9,7 @@// listener already learned it), so each entry is tracked directly by its RemoteFileRef.import { type BrowserWindow } from 'electron'import { IPC } from '../shared/ipc'-import { formatSubagentChunk } from './subagent-tail'+import { formatSubagentChunk, splitCompleteLines } from './subagent-tail'import type { RemoteFile, RemoteFileRef } from './remote-ssh/remote-file'const POLL_MS = 1000@@ -18,6 +18,8 @@ interface Tracked {ref: RemoteFileRefoffset: numberreading: boolean+ /** Partial trailing line held back until the next read completes it (see subagent-tail.ts). */+ carry: Buffer | null}export interface RemoteSubagentTail {@@ -42,7 +44,10 @@ export function createRemoteSubagentTail(win: BrowserWindow, remoteFile: RemoteFconst { text, newOffset } = await remoteFile.readFrom(e.ref, e.offset)e.offset = newOffsetif (text) {- const out = formatSubagentChunk(text)+ const read = Buffer.from(text)+ const { text: complete, carry } = splitCompleteLines(e.carry?.length ? Buffer.concat([e.carry, read]) : read)+ e.carry = carry+ const out = formatSubagentChunk(complete)if (out) send(toolUseId, out + '\n')}} finally {@@ -61,12 +66,20 @@ export function createRemoteSubagentTail(win: BrowserWindow, remoteFile: RemoteFreturn {track(toolUseId, ref) {if (!ref || tracked.has(toolUseId)) return- tracked.set(toolUseId, { ref, offset: 0, reading: false })+ tracked.set(toolUseId, { ref, offset: 0, reading: false, carry: null })void readOne(toolUseId, tracked.get(toolUseId)!) // immediate first readif (!timer) timer = setInterval(tick, POLL_MS)},untrack(toolUseId) {+ const e = tracked.get(toolUseId)tracked.delete(toolUseId)+ // The transcript is complete on untrack — a held-back carry is a final line missing+ // only its trailing newline; flush instead of dropping it.+ if (e?.carry?.length) {+ const out = formatSubagentChunk(e.carry.toString('utf-8'))+ e.carry = null+ if (out) send(toolUseId, out + '\n')+ }if (!tracked.size && timer) {clearInterval(timer)timer = nulldiff --git a/src/main/subagent-tail.test.ts b/src/main/subagent-tail.test.tsindex c9bfd95ec..b8dfdc8da 100644--- a/src/main/subagent-tail.test.ts+++ b/src/main/subagent-tail.test.ts@@ -1,10 +1,16 @@-import { describe, expect, it } from 'vitest'-import { formatSubagentChunk } from './subagent-tail'+import { describe, expect, it, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { createSubagentTail, formatSubagentChunk, splitCompleteLines } from './subagent-tail'++const assistant = (text: string): string =>+ JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text }] } })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' }] } }),+ assistant('hi'),'','garbled',JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Bash', input: { command: 'ls' } }] } })@@ -14,3 +20,101 @@ describe('formatSubagentChunk', () => {expect(formatSubagentChunk(text)).toBe('hi\n$ Bash ls')})})++describe('splitCompleteLines', () => {+ it('returns everything as carry when there is no newline', () => {+ const { text, carry } = splitCompleteLines(Buffer.from('partial line'))+ expect(text).toBe('')+ expect(carry?.toString()).toBe('partial line')+ })++ it('returns everything as text when the data ends with a newline', () => {+ const { text, carry } = splitCompleteLines(Buffer.from('a\nb\n'))+ expect(text).toBe('a\nb\n')+ expect(carry).toBeNull()+ })++ it('splits at the last newline, carrying the partial tail', () => {+ const { text, carry } = splitCompleteLines(Buffer.from('a\nb\npart'))+ expect(text).toBe('a\nb\n')+ expect(carry?.toString()).toBe('part')+ })++ it('keeps a multibyte char torn across reads intact once completed', () => {+ // '✦' is 3 bytes in UTF-8; tear it in the middle as a byte-level read would.+ const whole = Buffer.from('line with ✦ mark\n')+ const first = whole.subarray(0, 12) // ends mid-✦+ const rest = whole.subarray(12)+ const r1 = splitCompleteLines(first)+ expect(r1.text).toBe('')+ const r2 = splitCompleteLines(Buffer.concat([r1.carry!, rest]))+ expect(r2.text).toBe('line with ✦ mark\n')+ expect(r2.carry).toBeNull()+ })+})++// --- createSubagentTail integration (real fs, 400ms tick) ---++function fakeWin(): { win: never; send: ReturnType<typeof vi.fn> } {+ const send = vi.fn()+ return { win: { isDestroyed: () => false, webContents: { send } } as never, send }+}++const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))++function setup(): { transcriptPath: string; subDir: string } {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-'))+ const transcriptPath = path.join(dir, 'sess.jsonl')+ const subDir = path.join(dir, 'sess', 'subagents')+ fs.mkdirSync(subDir, { recursive: true })+ return { transcriptPath, subDir }+}++const streamed = (send: ReturnType<typeof vi.fn>): string =>+ send.mock.calls.map((c) => (c[1] as { chunk: string }).chunk).join('')++describe('createSubagentTail', () => {+ it('does not drop a line written torn across two reads', async () => {+ const { transcriptPath, subDir } = setup()+ fs.writeFileSync(path.join(subDir, 'agent-1.meta.json'), JSON.stringify({ toolUseId: 'tu1' }))+ const file = path.join(subDir, 'agent-1.jsonl')+ const line = assistant('torn line survives')+ fs.writeFileSync(file, line.slice(0, 25)) // first half of the line, no newline yet+ const { win, send } = fakeWin()+ const tail = createSubagentTail(win)+ tail.track('tu1', transcriptPath)+ await wait(900) // two ticks land while the line is still half-written+ fs.appendFileSync(file, line.slice(25) + '\n')+ await wait(600) // next tick reads the rest+ expect(streamed(send)).toContain('torn line survives')+ tail.finish('tu1')+ })++ it('re-checks a meta file whose toolUseId was missing on first read', async () => {+ const { transcriptPath, subDir } = setup()+ const metaPath = path.join(subDir, 'agent-1.meta.json')+ fs.writeFileSync(metaPath, '{}') // parseable but mid-write: toolUseId not there yet+ fs.writeFileSync(path.join(subDir, 'agent-1.jsonl'), assistant('late meta') + '\n')+ const { win, send } = fakeWin()+ const tail = createSubagentTail(win)+ tail.track('tu1', transcriptPath)+ await wait(600) // first tick parses {} — must not blacklist this meta+ fs.writeFileSync(metaPath, JSON.stringify({ toolUseId: 'tu1' }))+ await wait(600)+ expect(streamed(send)).toContain('late meta')+ tail.finish('tu1')+ })++ it('flushes a final line that lacks a trailing newline on finish', async () => {+ const { transcriptPath, subDir } = setup()+ fs.writeFileSync(path.join(subDir, 'agent-1.meta.json'), JSON.stringify({ toolUseId: 'tu1' }))+ fs.writeFileSync(path.join(subDir, 'agent-1.jsonl'), assistant('unterminated final line'))+ const { win, send } = fakeWin()+ const tail = createSubagentTail(win)+ tail.track('tu1', transcriptPath)+ await wait(600) // read, but held back as a partial line+ tail.finish('tu1')+ await wait(200) // finish's final read + carry flush+ expect(streamed(send)).toContain('unterminated final line')+ })+})diff --git a/src/main/subagent-tail.ts b/src/main/subagent-tail.tsindex d923c09e9..ff9f35d7a 100644--- a/src/main/subagent-tail.ts+++ b/src/main/subagent-tail.ts@@ -18,6 +18,12 @@ interface Tracked {reading?: boolean/** Meta files already parsed and rejected — don't re-read them on every 400ms tick. */seenMetas?: Set<string>+ /**+ * Bytes past the last newline of the previous read — a line caught mid-write. Held back+ * (as raw bytes, so a torn multibyte char survives) and prepended to the next read; without+ * this the torn line's halves each fail JSON.parse and the whole line is silently lost.+ */+ carry?: Buffer | null}function textOf(content: unknown): string {@@ -108,6 +114,20 @@ export function formatSubagentChunk(text: string): string {.join('\n')}+// Split accumulated transcript bytes at the last newline: everything up to it decodes to+// complete lines, the rest is carried (still raw bytes) into the next read. Splitting at the+// byte level is what makes a mid-multibyte tear safe — '\n' (0x0a) never occurs inside a+// UTF-8 continuation, so the carry always rejoins into valid UTF-8.+export function splitCompleteLines(data: Buffer): { text: string; carry: Buffer | null } {+ const nl = data.lastIndexOf(0x0a)+ if (nl === -1) return { text: '', carry: data.length ? data : null }+ return {+ text: data.subarray(0, nl + 1).toString('utf-8'),+ // Copy the tail so the (possibly large) read buffer isn't retained by the slice.+ carry: nl + 1 < data.length ? Buffer.from(data.subarray(nl + 1)) : null+ }+}+export interface SubagentTail {track(toolUseId: string, transcriptPath: string | undefined): voidfinish(toolUseId: string): void@@ -143,7 +163,10 @@ export function createSubagentTail(win: BrowserWindow): SubagentTail {e.file = path.join(e.dir, m.replace(/\.meta\.json$/, '.jsonl'))break}- seen.add(m) // belongs to another subagent — skip it on future ticks+ // Only blacklist a meta that positively names another subagent. A parseable file+ // whose toolUseId hasn't landed yet (caught mid-write) must be re-read next tick,+ // or this subagent's own meta gets skipped forever and its transcript never streams.+ if (meta.toolUseId) seen.add(m)} catch {// unparseable (possibly still being written) — retry next tick, don't blacklist}@@ -160,7 +183,10 @@ export function createSubagentTail(win: BrowserWindow): SubagentTail {await fd.close()}e.offset = size- const out = formatSubagentChunk(buf.toString('utf-8'))+ const data = e.carry?.length ? Buffer.concat([e.carry, buf]) : buf+ const { text, carry } = splitCompleteLines(data)+ e.carry = carry+ const out = formatSubagentChunk(text)if (out) send(toolUseId, out + '\n')} catch {// file may not exist yet / transient read error@@ -185,9 +211,21 @@ export function createSubagentTail(win: BrowserWindow): SubagentTail {if (!timer) timer = setInterval(tick, 400) // only runs while subagents are active},finish(toolUseId) {+ // The file is complete now, so a held-back carry is a real final line that just lacks+ // its trailing newline — flush it after the final read instead of dropping it.+ const flushCarry = (e: Tracked): void => {+ if (!e.carry?.length) return+ const out = formatSubagentChunk(e.carry.toString('utf-8'))+ e.carry = null+ if (out) send(toolUseId, out + '\n')+ }const e = tracked.get(toolUseId)- if (e) void readOne(toolUseId, e) // final flush (completes well within the grace delay)- setTimeout(() => tracked.delete(toolUseId), 1500)+ if (e) void readOne(toolUseId, e).then(() => flushCarry(e)) // final flush (completes well within the grace delay)+ setTimeout(() => {+ const late = tracked.get(toolUseId)+ tracked.delete(toolUseId)+ if (late) flushCarry(late) // ticks during the grace window may have re-filled the carry+ }, 1500)}}}