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.

fix(main): cap remote subagent-tail reads at 1MB per tick, byte-safe via base64

enes7e7d79641ddc
diff --git a/src/main/remote-ssh/remote-file.test.ts b/src/main/remote-ssh/remote-file.test.ts
index 43f015da1..3eb707d74 100644
--- a/src/main/remote-ssh/remote-file.test.ts
+++ b/src/main/remote-ssh/remote-file.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { tailFromOffsetArgs, tailLastBytesArgs, RemoteFile } from './remote-file'
+import { tailFromOffsetArgs, tailFromOffsetCappedArgs, 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' }
@@ -12,6 +12,10 @@ describe('remote-file builders', () => {
it('tailLastBytesArgs reads the last N bytes', () => {
expect(tailLastBytesArgs(conn, '/s.sock', '/a.jsonl', 4096).join(' ')).toContain(`tail -c 4096 '/a.jsonl'`)
})
+ it('tailFromOffsetCappedArgs caps the read and base64s it (byte-exact over a string stdout)', () => {
+ expect(tailFromOffsetCappedArgs(conn, '/s.sock', '/a b.jsonl', 10, 4096).join(' '))
+ .toContain(`tail -c +11 '/a b.jsonl' | head -c 4096 | base64`)
+ })
})
describe('RemoteFile', () => {
@@ -29,3 +33,59 @@ describe('RemoteFile', () => {
expect(await new RemoteFile(async () => ({ code: 1, stdout: '' })).readTail(ref, 10)).toBe('')
})
})
+
+// The fake host: slices the fixture BYTES exactly as `tail -c +N | head -c M` would, then
+// base64-encodes — GNU's base64 wraps at 76 cols, so the wrap is reproduced here too.
+function fakeHost(file: Buffer): (args: string[]) => Promise<{ code: number; stdout: string }> {
+ return async (args: string[]) => {
+ const m = /tail -c \+(\d+) .* \| head -c (\d+) \| base64/.exec(args.join(' '))
+ if (!m) throw new Error(`unexpected command: ${args.join(' ')}`)
+ const slice = file.subarray(Number(m[1]) - 1, Number(m[1]) - 1 + Number(m[2]))
+ return { code: 0, stdout: (slice.toString('base64').match(/.{1,76}/g) ?? []).join('\n') + '\n' }
+ }
+}
+
+describe('RemoteFile.readFromCapped', () => {
+ it('decodes wrapped base64 and advances the offset by the exact decoded byte count', async () => {
+ const payload = Buffer.from('x'.repeat(200) + '\n')
+ const rf = new RemoteFile(fakeHost(payload))
+ const { data, newOffset } = await rf.readFromCapped(ref, 0, 4096)
+ expect(data.equals(payload)).toBe(true)
+ expect(newOffset).toBe(payload.length)
+ })
+
+ it('fails open: non-zero code → empty buffer, offset unchanged', async () => {
+ const rf = new RemoteFile(async () => ({ code: 1, stdout: 'garbage' }))
+ const { data, newOffset } = await rf.readFromCapped(ref, 100, 4096)
+ expect(data.length).toBe(0)
+ expect(newOffset).toBe(100)
+ })
+
+ it('fails open: a thrown run → empty buffer, offset unchanged', async () => {
+ const rf = new RemoteFile(async () => {
+ throw new Error('ssh died')
+ })
+ const { data, newOffset } = await rf.readFromCapped(ref, 100, 4096)
+ expect(data.length).toBe(0)
+ expect(newOffset).toBe(100)
+ })
+
+ it('byte-exact: a multibyte char split by the cap reassembles across two reads', async () => {
+ // 'é' is 2 bytes; the cap lands between them. A decoded-string read would turn the torn
+ // halves into U+FFFD (3 bytes each) and drift the offset — base64 round-trips the bytes.
+ const file = Buffer.from('aé-tail\n', 'utf-8')
+ const cap = 2 // cuts mid-'é'
+ const rf = new RemoteFile(fakeHost(file))
+ const chunks: Buffer[] = []
+ let offset = 0
+ for (let i = 0; i < 10 && offset < file.length; i++) {
+ const r = await rf.readFromCapped(ref, offset, cap)
+ expect(r.newOffset).toBe(offset + r.data.length)
+ offset = r.newOffset
+ chunks.push(r.data)
+ }
+ expect(offset).toBe(file.length)
+ expect(Buffer.concat(chunks).equals(file)).toBe(true)
+ expect(Buffer.concat(chunks).toString('utf-8')).toBe('aé-tail\n')
+ })
+})
diff --git a/src/main/remote-ssh/remote-file.ts b/src/main/remote-ssh/remote-file.ts
index 705eef931..8e30ac3b1 100644
--- a/src/main/remote-ssh/remote-file.ts
+++ b/src/main/remote-ssh/remote-file.ts
@@ -13,6 +13,17 @@ export interface RemoteFileRef {
export function tailFromOffsetArgs(conn: SshConnection, controlPath: string, path: string, offset: number): string[] {
return childArgs(conn, controlPath, `tail -c +${offset + 1} ${posixQuote(path)}`)
}
+export function tailFromOffsetCappedArgs(
+ conn: SshConnection,
+ controlPath: string,
+ path: string,
+ offset: number,
+ maxBytes: number
+): string[] {
+ // base64 wraps at 76 cols on GNU and not at all on BSD — the reader strips whitespace, so
+ // no -w flag is used (macOS/BSD base64 has none).
+ return childArgs(conn, controlPath, `tail -c +${offset + 1} ${posixQuote(path)} | head -c ${maxBytes} | base64`)
+}
export function tailLastBytesArgs(conn: SshConnection, controlPath: string, path: string, bytes: number): string[] {
return childArgs(conn, controlPath, `tail -c ${bytes} ${posixQuote(path)}`)
}
@@ -31,6 +42,26 @@ export class RemoteFile {
}
}
+ /** Capped, byte-exact read: base64 round-trips the bytes so a mid-multibyte cut cannot
+ * corrupt the offset accounting (stdout is a decoded string — see tailFromOffsetCappedArgs).
+ * Fail-open: errors → empty buffer, offset unchanged. */
+ async readFromCapped(
+ ref: RemoteFileRef,
+ offset: number,
+ maxBytes: number
+ ): Promise<{ data: Buffer; newOffset: number }> {
+ try {
+ const { code, stdout } = await this.run(
+ tailFromOffsetCappedArgs(ref.conn, ref.controlPath, ref.path, offset, maxBytes)
+ )
+ if (code !== 0) return { data: Buffer.alloc(0), newOffset: offset }
+ const data = Buffer.from(stdout.replace(/\s+/g, ''), 'base64')
+ return { data, newOffset: offset + data.length }
+ } catch {
+ return { data: Buffer.alloc(0), 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))
diff --git a/src/main/remote-subagent-tail.test.ts b/src/main/remote-subagent-tail.test.ts
index f8e90c1df..9977aa31d 100644
--- a/src/main/remote-subagent-tail.test.ts
+++ b/src/main/remote-subagent-tail.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { createRemoteSubagentTail } from './remote-subagent-tail'
-import { formatSubagentChunk } from '../core/subagent-tail'
+import { formatSubagentChunk, SUBAGENT_READ_CAP } from '../core/subagent-tail'
import type { RemoteFileRef } from './remote-ssh/remote-file'
const ref: RemoteFileRef = { conn: { host: 'h', user: 'u' }, controlPath: '/s', path: '/abs/agent-1.jsonl' }
@@ -21,10 +21,11 @@ describe('createRemoteSubagentTail', () => {
const raw = assistant('hello from subagent')
let served = false
const remoteFile = {
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
- if (served) return { text: '', newOffset: o }
+ readFromCapped: vi.fn(async (_r: RemoteFileRef, o: number, _cap: number) => {
+ if (served) return { data: Buffer.alloc(0), newOffset: o }
served = true
- return { text: raw + '\n', newOffset: o + Buffer.byteLength(raw + '\n') }
+ const data = Buffer.from(raw + '\n')
+ return { data, newOffset: o + data.length }
})
}
const tail = createRemoteSubagentTail(win, remoteFile as never)
@@ -35,6 +36,7 @@ describe('createRemoteSubagentTail', () => {
expect(channel).toBe('agent:subagent-activity')
expect(payload.toolUseId).toBe('tool-1')
expect(payload.chunk).toContain(formatSubagentChunk(raw + '\n'))
+ expect(remoteFile.readFromCapped.mock.calls[0][2]).toBe(SUBAGENT_READ_CAP)
tail.untrack('tool-1')
})
@@ -45,10 +47,10 @@ describe('createRemoteSubagentTail', () => {
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] ?? ''
+ readFromCapped: vi.fn(async (_r: RemoteFileRef, o: number) => {
+ const data = Buffer.from(parts[i] ?? '')
i++
- return { text, newOffset: o + Buffer.byteLength(text) }
+ return { data, newOffset: o + data.length }
})
}
const tail = createRemoteSubagentTail(win, remoteFile as never)
@@ -62,7 +64,7 @@ describe('createRemoteSubagentTail', () => {
it('does not send when the chunk is empty', async () => {
const { win, send } = fakeWin()
const remoteFile = {
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o }))
+ readFromCapped: vi.fn(async (_r: RemoteFileRef, o: number) => ({ data: Buffer.alloc(0), newOffset: o }))
}
const tail = createRemoteSubagentTail(win, remoteFile as never)
tail.track('tool-2', ref)
@@ -70,4 +72,27 @@ describe('createRemoteSubagentTail', () => {
expect(send).not.toHaveBeenCalled()
tail.untrack('tool-2')
})
+
+ it('reassembles a multibyte char the read cap split across two reads', async () => {
+ const { win, send } = fakeWin()
+ const raw = Buffer.from(assistant('emoji 🚀 survives') + '\n', 'utf-8')
+ // The cap lands inside the emoji's 4 bytes; the carry holds RAW bytes, so the halves rejoin.
+ const cut = raw.indexOf(Buffer.from('🚀', 'utf-8')) + 2
+ const parts = [raw.subarray(0, cut), raw.subarray(cut)]
+ let i = 0
+ const remoteFile = {
+ readFromCapped: vi.fn(async (_r: RemoteFileRef, o: number) => {
+ const data = parts[i] ?? Buffer.alloc(0)
+ i++
+ return { data, newOffset: o + data.length }
+ })
+ }
+ const tail = createRemoteSubagentTail(win, remoteFile as never)
+ tail.track('tool-4', ref)
+ await new Promise((r) => setTimeout(r, 1100)) // next poll (1s) delivers the rest
+ const streamed = send.mock.calls.map((c) => (c[1] as { chunk: string }).chunk).join('')
+ expect(streamed).toContain('emoji 🚀 survives')
+ expect(streamed).not.toContain('�')
+ tail.untrack('tool-4')
+ }, 5000)
})
diff --git a/src/main/remote-subagent-tail.ts b/src/main/remote-subagent-tail.ts
index cf2f15361..5760c82c5 100644
--- a/src/main/remote-subagent-tail.ts
+++ b/src/main/remote-subagent-tail.ts
@@ -7,9 +7,14 @@
//
// Unlike the local tail, the remote transcript path is resolved by the caller (the hook raw-
// listener already learned it), so each entry is tracked directly by its RemoteFileRef.
+//
+// Each read is capped at SUBAGENT_READ_CAP (core's, shared with the local tail) so the first
+// tick after track() can't pull a whole transcript over ssh into one string; the cap costs
+// nothing, since the offset-based tail continues next tick. It goes through readFromCapped —
+// a capped read lands mid-multibyte routinely, and only base64 keeps the byte accounting exact.
import { type BrowserWindow } from 'electron'
import { IPC } from '../shared/ipc'
-import { formatSubagentChunk, splitCompleteLines } from '../core/subagent-tail'
+import { formatSubagentChunk, splitCompleteLines, SUBAGENT_READ_CAP } from '../core/subagent-tail'
import type { RemoteFile, RemoteFileRef } from './remote-ssh/remote-file'
const POLL_MS = 1000
@@ -41,10 +46,10 @@ export function createRemoteSubagentTail(win: BrowserWindow, remoteFile: RemoteF
if (e.reading) return
e.reading = true
try {
- const { text, newOffset } = await remoteFile.readFrom(e.ref, e.offset)
+ const { data, newOffset } = await remoteFile.readFromCapped(e.ref, e.offset, SUBAGENT_READ_CAP)
e.offset = newOffset
- if (text) {
- const read = Buffer.from(text)
+ if (data.length) {
+ const read = data
const { text: complete, carry } = splitCompleteLines(e.carry?.length ? Buffer.concat([e.carry, read]) : read)
e.carry = carry
const out = formatSubagentChunk(complete)