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(ssh): bound context transcript polling and back off failures

enes9ee9410d6c4a
diff --git a/CLAUDE.md b/CLAUDE.md
index f108819c7..52a7cc4d3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1616,6 +1616,19 @@ else, and its context links must keep classifying across restarts).
because `/quit --delete` exits *and permanently deletes* the session history, i.e. exactly what the
restart exists to resume (pinned by its own test).
Full picture, measurements, gaps and a device checklist: **`docs/gemini-agent.md`**.
+- **SSH context polling is a bounded byte protocol** (issue #816). The initial snapshot reads
+ only the last 1 MiB and records the absolute end offset; subsequent polls process at most
+ 1 MiB. `core/remote-ssh/transcript-window.ts` measures size and uses block-aligned POSIX `dd`
+ with base64, transferring less than 1.6 MiB including alignment/framing; idle replies contain
+ only the size/range header. The encoded dd exit status must survive the shell pipeline:
+ pipeline success alone can hide a failed read. Short/malformed replies and SSH failures throw,
+ retain the cursor, and back off from 2s to 60s with payload-free diagnostics. Bootstrap and
+ detected truncation restore usage without replaying historical task notifications/tool results,
+ including a historical partial line completed later. A changed remote reference replaces its
+ tracking generation so stale in-flight replies cannot publish. Server Edition uses the local
+ core tail on its host (no SSH-project manager); mobile has its own direct-SSH implementation,
+ so this desktop fix makes no claim about that separate path. Real `/bin/sh` fixtures cover
+ >20 MiB idle files and a new notification split inside UTF-8; BSD/macOS SSH remains a device check.
- **Context-meter rehydration (`context:ensure`)** — the meter is fed by hook events, and a tmux
session outlives the app, so a continuing session that is idle after a restart emits nothing and
its meter stays blank until the user's next prompt. The mount-time read that exists to close that
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0223794bd..fd1e73468 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -350,6 +350,11 @@ come from git-shared JSON and can end up interpolated into a shell command line.
`/bin/sh` against a fixture tree. A composed fixture will not tell you that `echo ##MEM` prints an
empty line because `#` starts a comment.
+**Remote context polling must bound bytes before SSH transports them.** Bootstrap from the
+file's measured end, keep offsets in raw bytes, and distinguish an idle read from failure so
+the poller can back off. Bootstrap history restores usage only, never task/result events.
+`core/remote-ssh/transcript-window.ts` and the real-shell remote-context tests pin this contract.
+
**A shared agent daemon is live-session infrastructure.** Codex's app-server control socket is
shared by every `--remote` TUI in an account scope, so stopping or replacing one daemon disconnects
every attached canvas node. A managed launcher must keep the already-bound thread under a bounded
diff --git a/src/core/remote-ssh/transcript-window.test.ts b/src/core/remote-ssh/transcript-window.test.ts
new file mode 100644
index 000000000..239cbfc6f
--- /dev/null
+++ b/src/core/remote-ssh/transcript-window.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest'
+import { parseTranscriptWindow, transcriptWindowCommand } from './transcript-window'
+
+const frame = (payload: string, status = 0): string => Buffer.from(payload + `\nNODETERM_READ_STATUS:${status}\n`).toString('base64')
+describe('strict transcript window framing', () => {
+ it('preserves bytes rather than re-encoding UTF-8 and trims block alignment', () => {
+ const r = parseTranscriptWindow('1 1 3 0\n' + frame('aé'), 2)
+ expect(r.data).toEqual(Buffer.from([0xc3]))
+ expect(r.newOffset).toBe(2)
+ })
+ it.each([
+ 'bad\n', '0 5 4 0\n', '0 5 5 0\n', '0 0 0 1\nAAAA',
+ '0 1 1 0\n' + frame('a', 1), '0 1 1 0\n' + frame(''),
+ '0 1 1 0\n' + frame('a') + '!', '0 1 1 0\n' + Buffer.from('a').toString('base64')
+ ])('rejects malformed, oversized, failed or short responses: %s', response => {
+ expect(() => parseTranscriptWindow(response, 4)).toThrow()
+ })
+ it.each([-1, 1.5, NaN, Infinity])('rejects an invalid offset %s before invoking a shell', offset => {
+ expect(() => transcriptWindowCommand('/fixture', offset, 1024)).toThrow()
+ })
+ it.each([0, -1, 1.5, Infinity, 1024 * 1024 + 1])('rejects an invalid cap %s', cap => {
+ expect(() => transcriptWindowCommand('/fixture', null, cap)).toThrow()
+ })
+})
diff --git a/src/core/remote-ssh/transcript-window.ts b/src/core/remote-ssh/transcript-window.ts
new file mode 100644
index 000000000..5dc86770a
--- /dev/null
+++ b/src/core/remote-ssh/transcript-window.ts
@@ -0,0 +1,58 @@
+import { posixQuote } from '../../shared/ssh'
+
+const BLOCK = 65536
+const STATUS = '\nNODETERM_READ_STATUS:0\n'
+
+/** One size snapshot and at most cap + two blocks of file bytes. POSIX sh + BSD/GNU dd.
+ * The dd status travels INSIDE base64: pipeline success alone hides a failed file read. */
+export function transcriptWindowCommand(path: string, offset: number | null, cap: number): string {
+ if ((offset !== null && (!Number.isSafeInteger(offset) || offset < 0)) ||
+ !Number.isSafeInteger(cap) || cap < 1 || cap > 1024 * 1024) throw new Error('Invalid transcript read bounds')
+ return `exec 3< ${posixQuote(path)} || exit 1
+size=$(wc -c < ${posixQuote(path)}) || exit 1
+size=$((size + 0))
+start=${offset ?? -1}
+initial=0
+if [ "$start" -lt 0 ] || [ "$size" -lt "$start" ]; then
+ initial=1
+ start=$((size > ${cap} ? size - ${cap} : 0))
+fi
+count=$((size - start))
+if [ "$count" -gt ${cap} ]; then count=${cap}; fi
+printf '%s %s %s %s\n' "$start" "$count" "$size" "$initial"
+if [ "$count" -gt 0 ]; then
+ skip=$((start / ${BLOCK}))
+ blocks=$(((start % ${BLOCK} + count + ${BLOCK - 1}) / ${BLOCK}))
+ { dd bs=${BLOCK} skip="$skip" count="$blocks" <&3 2>/dev/null; result=$?; printf '\nNODETERM_READ_STATUS:%s\n' "$result"; } | base64
+fi`
+}
+
+export interface TranscriptWindow {
+ data: Buffer
+ start: number
+ newOffset: number
+ initial: boolean
+}
+
+export function parseTranscriptWindow(stdout: string, cap: number): TranscriptWindow {
+ const end = stdout.indexOf('\n')
+ const match = /^(\d+) (\d+) (\d+) ([01])$/.exec(stdout.slice(0, end))
+ if (!match) throw new Error('Invalid transcript read header')
+ const [start, count, size, initial] = match.slice(1).map(Number)
+ if (![start, count, size].every(Number.isSafeInteger) || count > cap || start + count > size) {
+ throw new Error('Invalid transcript read range')
+ }
+ const encoded = stdout.slice(end + 1).replace(/\s/g, '')
+ if (!count) {
+ if (encoded) throw new Error('Unexpected transcript read payload')
+ return { data: Buffer.alloc(0), start, newOffset: start, initial: !!initial }
+ }
+ const decoded = Buffer.from(encoded, 'base64')
+ if (decoded.toString('base64') !== encoded || !decoded.subarray(-STATUS.length).equals(Buffer.from(STATUS))) {
+ throw new Error('Failed transcript read')
+ }
+ const bytes = decoded.subarray(0, -STATUS.length)
+ const leading = start % BLOCK
+ if (bytes.length < leading + count || bytes.length > cap + 2 * BLOCK) throw new Error('Short or oversized transcript read')
+ return { data: bytes.subarray(leading, leading + count), start, newOffset: start + count, initial: !!initial }
+}
diff --git a/src/main/remote-context-tail.test.ts b/src/main/remote-context-tail.test.ts
index 39a994a61..eded37867 100644
--- a/src/main/remote-context-tail.test.ts
+++ b/src/main/remote-context-tail.test.ts
@@ -1,102 +1,130 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, writeFileSync, appendFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { createRemoteContextTail } from './remote-context-tail'
-import type { RemoteFileRef } from './remote-ssh/remote-file'
+import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'
-const ref: RemoteFileRef = { conn: { host: 'h', user: 'u' }, controlPath: '/s', path: '/abs/x.jsonl' }
-const line = (used: number, model: string): string =>
- JSON.stringify({ type: 'assistant', message: { model, usage: { input_tokens: used } } })
-
-function fakeWin(): { win: never; send: ReturnType<typeof vi.fn> } {
- const send = vi.fn()
- return { win: { isDestroyed: () => false, webContents: { send } } as never, send }
+const cap = 1024 * 1024
+const ref: RemoteFileRef = { conn: { host: 'fixture', user: 'fixture' }, controlPath: '/unused', path: '/fixture' }
+const usage = (used: number): string => JSON.stringify({ type: 'assistant', message: { model: 'claude-opus-4-8', usage: { input_tokens: used } } }) + '\n'
+const notification = (result: string): string => JSON.stringify({ type: 'queue-operation', operation: 'enqueue', content: `<task-notification><tool-use-id>tu</tool-use-id><status>completed</status><result>${result}</result></task-notification>` }) + '\n'
+const tool = JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'tu', content: 'done' }] } }) + '\n'
+function harness(remote: Pick<RemoteFile, 'readContextWindow'>) {
+ const send = vi.fn(), onTaskNotification = vi.fn(), onToolResult = vi.fn()
+ const tail = createRemoteContextTail({ isDestroyed: () => false, webContents: { send } } as never, remote as RemoteFile, { onTaskNotification, onToolResult })
+ return { tail, send, onTaskNotification, onToolResult }
}
+const flush = async (): Promise<void> => { await vi.advanceTimersByTimeAsync(0) }
-const tick = (): Promise<void> => new Promise((r) => setTimeout(r, 30))
+beforeEach(() => vi.useFakeTimers())
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
-describe('createRemoteContextTail', () => {
- it('reads the remote transcript via readTail and pushes ContextWindowUsage on first usage', async () => {
- const { win, send } = fakeWin()
- const remoteFile = {
- readTail: vi.fn(async () => line(120, 'claude-opus-4-8')),
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o }))
+describe('remote context polling', () => {
+ it('backs off failures to 60s, logs no remote error content, and recovers at the same offset', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const readContextWindow = vi.fn().mockRejectedValue(new Error('SECRET transcript'))
+ const h = harness({ readContextWindow })
+ h.tail.track('s', ref)
+ await flush()
+ for (const delay of [2000, 4000, 8000, 16000, 32000, 60000, 60000]) {
+ const calls = readContextWindow.mock.calls.length
+ await vi.advanceTimersByTimeAsync(delay - 1000)
+ expect(readContextWindow).toHaveBeenCalledTimes(calls)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(readContextWindow).toHaveBeenCalledTimes(calls + 1)
}
- const tail = createRemoteContextTail(win, remoteFile as never)
- tail.track('sess1', ref)
- await tick()
- expect(remoteFile.readTail).toHaveBeenCalled()
- expect(send).toHaveBeenCalled()
- const [channel, payload] = send.mock.calls.at(-1)!
- expect(channel).toBe('context:update')
- expect(payload).toMatchObject({
- sessionId: 'sess1',
- usedTokens: 120,
- model: 'claude-opus-4-8',
- windowTokens: 1_000_000
- })
- tail.untrack('sess1')
+ expect(warn.mock.calls.flat().join()).not.toContain('SECRET')
+ readContextWindow.mockResolvedValue({ data: Buffer.from(usage(120)), start: 0, newOffset: 200, initial: true })
+ await vi.advanceTimersByTimeAsync(60000)
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(120)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(readContextWindow).toHaveBeenLastCalledWith(ref, 200, cap)
+ h.tail.untrack('s')
})
- it('uses readFrom with the advancing offset after the first tail read', async () => {
- const { win } = fakeWin()
- const readFrom = vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o + 0 }))
- const remoteFile = {
- readTail: vi.fn(async () => line(50, 'claude-haiku')),
- readFrom
- }
- const tail = createRemoteContextTail(win, remoteFile as never)
- tail.track('sess2', ref)
- await tick()
- expect(remoteFile.readTail).toHaveBeenCalledTimes(1)
- // pathFor exposes the tracked path
- expect(tail.pathFor('sess2')).toBe('/abs/x.jsonl')
- tail.untrack('sess2')
+ it('serializes reads and ignores detached or replaced in-flight snapshots', async () => {
+ let finish!: (value: unknown) => void
+ const readContextWindow = vi.fn(() => new Promise(resolve => { finish = resolve }))
+ const h = harness({ readContextWindow } as never)
+ h.tail.track('s', ref)
+ const oldFinish = finish
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(readContextWindow).toHaveBeenCalledTimes(1)
+ h.tail.track('s', { ...ref, controlPath: '/new-owner' })
+ oldFinish({ data: Buffer.from(usage(100)), newOffset: 100, initial: true })
+ await flush()
+ expect(h.send).not.toHaveBeenCalled()
+ h.tail.untrack('s')
+ finish({ data: Buffer.from(usage(200)), newOffset: 200, initial: true })
+ await flush()
+ expect(h.send).not.toHaveBeenCalled()
})
+})
- it('fires onTaskNotification for a <task-notification> line in the remote transcript', async () => {
- const { win } = fakeWin()
- const notif = JSON.stringify({
- type: 'queue-operation',
- operation: 'enqueue',
- content: '<task-notification>\n<tool-use-id>tu-remote</tool-use-id>\n<status>completed</status>\n<result>remote done</result>\n</task-notification>'
+describe.skipIf(process.platform === 'win32')('real POSIX shell transcript fixture (no SSH/session access)', () => {
+ let dir: string
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'nt-transcript-')) })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+ function fixture(initial: string | Buffer) {
+ const path = join(dir, "transcript ' fixture.jsonl")
+ writeFileSync(path, initial)
+ const transfers: number[] = []
+ const reader = new RemoteFile(async args => {
+ const stdout = execFileSync('/bin/sh', ['-c', args.at(-1)!], { encoding: 'utf8', maxBuffer: 2 * cap })
+ transfers.push(Buffer.byteLength(stdout))
+ return { code: 0, stdout }
})
- let served = false
- const remoteFile = {
- readTail: vi.fn(async () => line(10, 'claude-opus-4-8') + '\n'),
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
- if (served) return { text: '', newOffset: o }
- served = true
- return { text: notif + '\n', newOffset: o + Buffer.byteLength(notif + '\n') }
- })
- }
- const onTaskNotification = vi.fn()
- const tail = createRemoteContextTail(win, remoteFile as never, { onTaskNotification })
- tail.track('sess4', ref)
- await new Promise((r) => setTimeout(r, 1200)) // first read + one poll tick
- expect(onTaskNotification).toHaveBeenCalledTimes(1)
- expect(onTaskNotification.mock.calls[0][0]).toBe('sess4')
- expect(onTaskNotification.mock.calls[0][1]).toMatchObject({ toolUseId: 'tu-remote', result: 'remote done' })
- tail.untrack('sess4')
- }, 5000)
+ const read = vi.spyOn(reader, 'readContextWindow')
+ const h = harness(reader)
+ h.tail.track('s', { ...ref, path })
+ return { ...h, path, transfers, read }
+ }
- it('only pushes again when the usage changes', async () => {
- const { win, send } = fakeWin()
- // Realistic JSONL: records are newline-terminated (the tail carries a torn trailing
- // line into the next read, so un-delimited records would garble on purpose).
- let nextFrom = line(200, 'claude-opus-4-8') + '\n'
- const remoteFile = {
- readTail: vi.fn(async () => line(100, 'claude-opus-4-8') + '\n'),
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
- const text = nextFrom
- nextFrom = ''
- return { text, newOffset: o + Buffer.byteLength(text) }
- })
- }
- const tail = createRemoteContextTail(win, remoteFile as never)
- tail.track('sess3', ref)
- await new Promise((r) => setTimeout(r, 1200)) // first tick (track) + one interval tick
- const usedValues = send.mock.calls.map((c) => c[1].usedTokens)
- expect(usedValues).toContain(100)
- expect(usedValues).toContain(200)
- tail.untrack('sess3')
+ it('bounds transfer for an idle >20 MiB file, starts at EOF, and never replays historical events', async () => {
+ const history = notification('historical') + tool + usage(100)
+ const content = Buffer.concat([Buffer.alloc(20 * cap, 10), Buffer.from(history)])
+ const h = fixture(content)
+ await flush()
+ await expect(h.read.mock.results[0].value).resolves.toHaveProperty('newOffset', content.length)
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(100)
+ expect(h.transfers[0]).toBeLessThan(1.6 * cap)
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(h.read.mock.calls.slice(1).every(c => c[1] === content.length)).toBe(true)
+ expect(h.transfers.slice(1).every(n => n < 100)).toBe(true)
+ expect(h.onTaskNotification).not.toHaveBeenCalled()
+ expect(h.onToolResult).not.toHaveBeenCalled()
+ expect(h.send).toHaveBeenCalledTimes(1)
+
+ // Position the cap in the middle of a UTF-8 character inside a new notification.
+ const event = Buffer.from(notification('yeni é 🐈'))
+ const split = event.indexOf(Buffer.from('é')) + 1
+ appendFileSync(h.path, Buffer.concat([Buffer.alloc(cap - split, 10), event, Buffer.from(tool + usage(200)), Buffer.alloc(18 * cap, 10)]))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification).toHaveBeenCalledExactlyOnceWith('s', expect.objectContaining({ result: 'yeni é 🐈' }))
+ expect(h.onToolResult).toHaveBeenCalledExactlyOnceWith('s')
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(200)
+ expect(h.transfers.every(n => n < 1.6 * cap)).toBe(true)
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(h.onTaskNotification).toHaveBeenCalledTimes(1)
+ h.tail.untrack('s')
+ })
+
+ it('suppresses historical torn lines, resets after truncation, and handles an initially empty file', async () => {
+ const h = fixture('')
+ await flush()
+ appendFileSync(h.path, notification('fresh') + usage(10))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification).toHaveBeenCalledTimes(1)
+ const torn = notification('old').trimEnd()
+ writeFileSync(h.path, torn.slice(0, -5))
+ await vi.advanceTimersByTimeAsync(1000)
+ appendFileSync(h.path, torn.slice(-5) + '\n' + notification('next'))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification.mock.calls.map(c => c[1].result)).toEqual(['fresh', 'next'])
+ h.tail.untrack('s')
})
})
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index fb094f8c8..d43cbfe84 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -25,7 +25,10 @@ const INITIAL_READ_CAP = 1024 * 1024 // 1 MB
interface Tracked {
ref: RemoteFileRef
- offset: number
+ offset: number | null
+ failures: number
+ retryAt: number
+ suppressCarry: boolean
used: number
window: number
model: string | null
@@ -58,8 +61,7 @@ export function createRemoteContextTail(
// value wins, so it must not wait for a newline. Notifications scan COMPLETE lines only,
// with the torn tail carried into the next read (see subagent-tail.ts), so a torn
// <task-notification> is completed later instead of being lost.
- const scan = (sessionId: string, t: Tracked, read: string): void => {
- const buf = Buffer.from(read)
+ const scan = (sessionId: string, t: Tracked, buf: Buffer, historical: boolean): void => {
const combined = t.carry?.length ? Buffer.concat([t.carry, buf]) : buf
t.carry = splitCompleteLines(combined).carry
// ONE split shared by all three scanners (mirrors the local tail): the last element is the
@@ -71,9 +73,13 @@ export function createRemoteContextTail(
t.used = latest.used
t.model = latest.model ?? t.model
}
- if (opts?.onToolResult && hasToolResult(completeLines)) opts.onToolResult(sessionId)
+ // A historical partial line may finish on a later poll; it still must not emit events.
+ const eventLines = historical ? [] : completeLines.slice(t.suppressCarry ? 1 : 0)
+ if (historical) t.suppressCarry = !!t.carry
+ else if (completeLines.length) t.suppressCarry = false
+ if (opts?.onToolResult && hasToolResult(eventLines)) opts.onToolResult(sessionId)
if (opts?.onTaskNotification) {
- for (const n of parseTaskNotifications(completeLines)) opts.onTaskNotification(sessionId, n)
+ for (const n of parseTaskNotifications(eventLines)) opts.onTaskNotification(sessionId, n)
}
}
@@ -91,23 +97,28 @@ export function createRemoteContextTail(
win.webContents.send(IPC.contextUpdate, payload)
}
- // One async read+reconcile pass for a session. Fail-open: RemoteFile already returns empty on
- // error, so a failed read keeps the last value. The `reading` flag skips overlapping ticks.
+ // One bounded read per tick; retain the last good meter through transport failures.
const read = async (sessionId: string, t: Tracked): Promise<void> => {
- if (t.reading) return
+ if (t.reading || Date.now() < t.retryAt) return
t.reading = true
try {
- if (t.offset === 0) {
- // First read: grab the tail of the (possibly huge) file in one shot. We can't stat the
- // remote size, so advance the offset by the bytes we actually received.
- const text = await remoteFile.readTail(t.ref, INITIAL_READ_CAP)
- t.offset = Buffer.byteLength(text)
- scan(sessionId, t, text)
- } else {
- const { text, newOffset } = await remoteFile.readFrom(t.ref, t.offset)
- t.offset = newOffset
- if (text) scan(sessionId, t, text)
+ const result = await remoteFile.readContextWindow(t.ref, t.offset, INITIAL_READ_CAP)
+ if (sessions.get(sessionId) !== t) return // detached/replaced while SSH was in flight
+ if (result.initial) {
+ t.carry = null
+ t.suppressCarry = false
}
+ t.offset = result.newOffset
+ if (result.data.length) scan(sessionId, t, result.data, result.initial)
+ t.failures = 0
+ t.retryAt = 0
+ } catch {
+ if (sessions.get(sessionId) !== t) return
+ const delay = Math.min(60_000, 2000 * 2 ** Math.min(t.failures++, 5))
+ t.retryAt = Date.now() + delay
+ // Never log the remote command, path, transcript or transport error (may contain secrets).
+ console.warn(`[remote-context-tail] Read failed; retrying in ${delay}ms`)
+ return
} finally {
t.reading = false
}
@@ -137,17 +148,15 @@ export function createRemoteContextTail(
track(sessionId, ref) {
if (!sessionId || !ref) return
const existing = sessions.get(sessionId)
- if (existing) {
- if (existing.ref.path !== ref.path) {
- existing.ref = ref
- existing.offset = 0
- existing.carry = null
- }
- return
- }
+ if (existing && existing.ref.path === ref.path &&
+ existing.ref.controlPath === ref.controlPath &&
+ JSON.stringify(existing.ref.conn) === JSON.stringify(ref.conn)) return
const t: Tracked = {
ref,
- offset: 0,
+ offset: null,
+ failures: 0,
+ retryAt: 0,
+ suppressCarry: false,
used: 0,
window: 0,
model: null,
diff --git a/src/main/remote-ssh/remote-file.test.ts b/src/main/remote-ssh/remote-file.test.ts
index 3eb707d74..5289dc5b9 100644
--- a/src/main/remote-ssh/remote-file.test.ts
+++ b/src/main/remote-ssh/remote-file.test.ts
@@ -89,3 +89,14 @@ describe('RemoteFile.readFromCapped', () => {
expect(Buffer.concat(chunks).toString('utf-8')).toBe('aé-tail\n')
})
})
+
+describe('RemoteFile.readContextWindow', () => {
+ it('propagates transport failure instead of returning an idle snapshot', async () => {
+ for (const run of [async () => ({ code: 1, stdout: '' }), async () => { throw new Error('offline') }]) {
+ await expect(new RemoteFile(run).readContextWindow(ref, 42, 1024)).rejects.toThrow()
+ }
+ })
+ it('rejects malformed responses instead of advancing the cursor', async () => {
+ await expect(new RemoteFile(async () => ({ code: 0, stdout: 'invalid' })).readContextWindow(ref, 42, 1024)).rejects.toThrow()
+ })
+})
diff --git a/src/main/remote-ssh/remote-file.ts b/src/main/remote-ssh/remote-file.ts
index 8e30ac3b1..41014ca94 100644
--- a/src/main/remote-ssh/remote-file.ts
+++ b/src/main/remote-ssh/remote-file.ts
@@ -1,6 +1,7 @@
// 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 { transcriptWindowCommand, parseTranscriptWindow, type TranscriptWindow } from '../../core/remote-ssh/transcript-window'
import { childArgs } from '../../core/remote-ssh/control-master'
import { posixQuote, type SshConnection } from '../../shared/ssh'
@@ -28,10 +29,18 @@ export function tailLastBytesArgs(conn: SshConnection, controlPath: string, path
return childArgs(conn, controlPath, `tail -c ${bytes} ${posixQuote(path)}`)
}
-/** Reads a remote file over the project's ControlMaster. Fail-open: errors → empty. */
+/** Reads over the project's ControlMaster. Legacy methods fail open; context reads throw. */
export class RemoteFile {
constructor(private run: (args: string[]) => Promise<{ code: number; stdout: string }>) {}
+ /** Strict snapshot read for the context poller: failure must trigger backoff, not look idle. */
+ async readContextWindow(ref: RemoteFileRef, offset: number | null, cap: number): Promise<TranscriptWindow> {
+ const { code, stdout } = await this.run(childArgs(ref.conn, ref.controlPath,
+ transcriptWindowCommand(ref.path, offset, cap)))
+ if (code !== 0) throw new Error('Remote transcript command failed')
+ return parseTranscriptWindow(stdout, cap)
+ }
+
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))