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): treat a not-yet-created transcript as idle in the remote context tail

reviewc93d5deb8a2e
diff --git a/CLAUDE.md b/CLAUDE.md
index 237c97112..f8ab7f0ca 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1883,11 +1883,20 @@ else, and its context links must keep classifying across restarts).
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. A SEPARATE idle
- backoff (`idleDelayMs`) stretches the 1 s poll after three consecutive empty successful reads
+ retain the cursor, and back off from 2s to 60s with payload-free diagnostics — logged when a
+ streak starts, when it settles at 60 s and when it recovers, never per retry, and naming only the
+ observed status (`exit 255`, `malformed reply`), never a guessed cause: the runner reports a
+ timeout as status 1. **A transcript that does not exist is not a failure.** Claude creates it on
+ the first prompt while SessionStart already hands over the path (measured on 2.1.283), so every
+ unused remote Claude node used to walk the failure backoff and log a line a minute. The command
+ answers `NODETERM_ABSENT` with status 0 and the tail polls it on the idle cadence; a file that
+ appears after being seen missing is live from byte 0 when its bootstrap window covers all of it.
+ A SEPARATE idle backoff (`idleDelayMs`) stretches the 1 s poll after three consecutive empty successful reads
(2/4/8 s, capped at 10 s) and is reset by any data-bearing read and by every same-ref `track()`
— i.e. every hook POST for the session, which is what keeps a `<task-notification>` (it rides
- a UserPromptSubmit hook) at ~1 s latency; never merge it with the failure backoff. Bootstrap and
+ a UserPromptSubmit hook) at ~1 s latency; never merge it with the failure backoff. That same
+ `track()` also skips the rest of a pending failure wait (the host just reached us) but keeps the
+ failure streak, so a read that fails again goes straight back to 60 s. 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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c054b5b35..39b21d076 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -444,7 +444,9 @@ 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.
+the poller can back off. A transcript that does not exist yet is idle, not a failure: Claude only
+creates it on the first prompt, long after SessionStart handed over its path. 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
diff --git a/src/core/remote-ssh/transcript-window.test.ts b/src/core/remote-ssh/transcript-window.test.ts
index 246f1f75a..1d838d6da 100644
--- a/src/core/remote-ssh/transcript-window.test.ts
+++ b/src/core/remote-ssh/transcript-window.test.ts
@@ -1,4 +1,8 @@
-import { describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { parseTranscriptPage, parseTranscriptWindow, transcriptPageCommand, transcriptWindowCommand } from './transcript-window'
const frame = (payload: string, status = 0): string => Buffer.from(payload + `\nNODETERM_READ_STATUS:${status}\n`).toString('base64')
@@ -18,11 +22,45 @@ describe('strict transcript window framing', () => {
it.each([-1, 1.5, NaN, Infinity])('rejects an invalid offset %s before invoking a shell', offset => {
expect(() => transcriptWindowCommand('/fixture', offset, 1024)).toThrow()
})
+ it('reads the absent marker as an empty, absent window — and only the exact marker', () => {
+ expect(parseTranscriptWindow('NODETERM_ABSENT\n', 4)).toMatchObject({ absent: true, data: Buffer.alloc(0) })
+ for (const reply of ['NODETERM_ABSENT', 'NODETERM_ABSENT\n0 0 0 1\n', 'x NODETERM_ABSENT\n']) {
+ expect(() => parseTranscriptWindow(reply, 4)).toThrow()
+ }
+ })
it.each([0, -1, 1.5, Infinity, 1024 * 1024 + 1])('rejects an invalid cap %s', cap => {
expect(() => transcriptWindowCommand('/fixture', null, cap)).toThrow()
})
})
+// Generated shell: run it for real, as the other remote scripts are (a composed fixture cannot tell
+// you what `sh` does with it).
+describe.skipIf(process.platform === 'win32')('transcript window command under a real /bin/sh', () => {
+ let dir: string
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'nt-window-')) })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+ const run = (path: string, offset: number | null): string =>
+ execFileSync('/bin/sh', ['-c', transcriptWindowCommand(path, offset, 1024)], { encoding: 'utf8' })
+
+ it('answers a missing file — or a missing project directory — with the marker and status 0', () => {
+ for (const path of [join(dir, "not ' yet.jsonl"), join(dir, 'no-project-dir', 'x.jsonl')]) {
+ const stdout = run(path, null)
+ expect(stdout).toBe('NODETERM_ABSENT\n')
+ expect(parseTranscriptWindow(stdout, 1024).absent).toBe(true)
+ }
+ })
+ it('still reads an existing file, empty or not', () => {
+ const path = join(dir, "here ' now.jsonl")
+ writeFileSync(path, '')
+ expect(parseTranscriptWindow(run(path, null), 1024)).toMatchObject({ initial: true, newOffset: 0, data: Buffer.alloc(0) })
+ writeFileSync(path, 'abc\n')
+ const r = parseTranscriptWindow(run(path, null), 1024)
+ expect(r).toMatchObject({ initial: true, start: 0, newOffset: 4 })
+ expect(r.absent).toBeUndefined()
+ expect(r.data.toString()).toBe('abc\n')
+ })
+})
+
describe('paged transcript read (⌘M panel) framing', () => {
it('trims block alignment to exactly the asked range, lookbehind byte included', () => {
const r = parseTranscriptPage('1 2 3\n' + frame('aéb'), null, 1)
diff --git a/src/core/remote-ssh/transcript-window.ts b/src/core/remote-ssh/transcript-window.ts
index 3d8254b3a..9467a5f5b 100644
--- a/src/core/remote-ssh/transcript-window.ts
+++ b/src/core/remote-ssh/transcript-window.ts
@@ -3,13 +3,18 @@ import { CHAT_PAGE_MAX_BYTES } from '../../shared/chat-page'
const BLOCK = 65536
const STATUS = '\nNODETERM_READ_STATUS:0\n'
+const ABSENT = 'NODETERM_ABSENT'
/** 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. */
+ * The dd status travels INSIDE base64: pipeline success alone hides a failed file read.
+ * A path that does not exist answers `NODETERM_ABSENT` with status 0: Claude creates its transcript
+ * on the first prompt while SessionStart already hands us the path, so an unused session has no
+ * file for as long as it stays unused (measured on 2.1.283). That is an answer, not a failed 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
+ return `if [ ! -e ${posixQuote(path)} ]; then echo ${ABSENT}; exit 0; fi
+exec 3< ${posixQuote(path)} || exit 1
size=$(wc -c < ${posixQuote(path)}) || exit 1
size=$((size + 0))
start=${offset ?? -1}
@@ -33,9 +38,12 @@ export interface TranscriptWindow {
start: number
newOffset: number
initial: boolean
+ /** The file does not exist (yet). `data` is empty and the offsets carry no meaning. */
+ absent?: boolean
}
export function parseTranscriptWindow(stdout: string, cap: number): TranscriptWindow {
+ if (stdout === `${ABSENT}\n`) return { data: Buffer.alloc(0), start: 0, newOffset: 0, initial: false, absent: true }
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')
diff --git a/src/main/remote-context-tail.test.ts b/src/main/remote-context-tail.test.ts
index 069fa904d..82d5fb98a 100644
--- a/src/main/remote-context-tail.test.ts
+++ b/src/main/remote-context-tail.test.ts
@@ -1,9 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { execFileSync } from 'node:child_process'
-import { mkdtempSync, writeFileSync, appendFileSync, rmSync } from 'node:fs'
+import { mkdtempSync, writeFileSync, appendFileSync, rmSync, unlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { createRemoteContextTail, idleDelayMs } from './remote-context-tail'
+import { createRemoteContextTail, failureDelayMs, idleDelayMs, logsFailure } from './remote-context-tail'
import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'
const cap = 1024 * 1024
@@ -36,9 +36,16 @@ describe('remote context polling', () => {
expect(readContextWindow).toHaveBeenCalledTimes(calls + 1)
}
expect(warn.mock.calls.flat().join()).not.toContain('SECRET')
+ // Eight failures, two lines: the first of the streak and the one that settles at the cap.
+ expect(warn.mock.calls.map(c => c[0])).toEqual([
+ '[remote-context-tail] Read for session s failed (unknown); retrying in 2000ms',
+ '[remote-context-tail] Read for session s still failing after 6 attempts (unknown); retrying every 60000ms until it recovers'
+ ])
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)
+ expect(warn.mock.calls.at(-1)?.[0]).toBe('[remote-context-tail] Read for session s recovered after 8 failed attempts')
+ expect(warn).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(1000)
expect(readContextWindow).toHaveBeenLastCalledWith(ref, 200, cap)
h.tail.untrack('s')
@@ -67,9 +74,9 @@ describe.skipIf(process.platform === 'win32')('real POSIX shell transcript fixtu
let dir: string
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'nt-transcript-')) })
afterEach(() => rmSync(dir, { recursive: true, force: true }))
- function fixture(initial: string | Buffer) {
+ function fixture(initial: string | Buffer | null) {
const path = join(dir, "transcript ' fixture.jsonl")
- writeFileSync(path, initial)
+ if (initial !== null) 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 })
@@ -127,6 +134,96 @@ describe.skipIf(process.platform === 'win32')('real POSIX shell transcript fixtu
expect(h.onTaskNotification.mock.calls.map(c => c[1].result)).toEqual(['fresh', 'next'])
h.tail.untrack('s')
})
+
+ // Claude creates its transcript on the first prompt, but SessionStart hands the path over at
+ // launch (measured on 2.1.283), so every unused remote Claude node starts here — and used to
+ // walk the failure backoff to 60 s and log a line a minute for as long as it stayed unused.
+ it('treats a transcript that does not exist yet as idle, then reads it from its first byte', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const h = fixture(null)
+ await flush()
+ await expect(h.read.mock.results[0].value).resolves.toMatchObject({ absent: true })
+ for (let i = 0; i < 120; i++) await vi.advanceTimersByTimeAsync(1000)
+ // Idle cadence (capped at 10 s), not the 60 s failure wait, and nothing logged.
+ expect(h.read.mock.calls.length).toBeGreaterThan(12)
+ expect(h.read.mock.calls.every(c => c[1] === null)).toBe(true)
+ expect(warn).not.toHaveBeenCalled()
+
+ // The first prompt: the file appears and its hook arrives. Everything in it is new.
+ writeFileSync(h.path, notification('first turn') + tool + usage(300))
+ const before = h.read.mock.calls.length
+ h.tail.track('s', { ...ref, path: h.path })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.read.mock.calls.length).toBe(before + 1)
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(300)
+ expect(h.onTaskNotification).toHaveBeenCalledExactlyOnceWith('s', expect.objectContaining({ result: 'first turn' }))
+ expect(h.onToolResult).toHaveBeenCalledExactlyOnceWith('s', 'tu')
+
+ // Removed and written again (not a realistic Claude path, but the same rule): new bytes, live.
+ unlinkSync(h.path)
+ await vi.advanceTimersByTimeAsync(1000)
+ writeFileSync(h.path, notification('rewritten') + usage(400))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification.mock.calls.map(c => c[1].result)).toEqual(['first turn', 'rewritten'])
+ expect(warn).not.toHaveBeenCalled()
+ h.tail.untrack('s')
+ })
+})
+
+describe('a file that appears after it was missing', () => {
+ it('is history again when it arrives bigger than the bootstrap window', async () => {
+ const readContextWindow = vi.fn()
+ .mockResolvedValue({ data: Buffer.alloc(0), start: 5000, newOffset: 5000, initial: false })
+ .mockResolvedValueOnce({ data: Buffer.alloc(0), start: 0, newOffset: 0, initial: false, absent: true })
+ .mockResolvedValueOnce({ data: Buffer.from(notification('copied in') + usage(50)), start: 4000, newOffset: 5000, initial: true })
+ const h = harness({ readContextWindow })
+ try {
+ h.tail.track('s', ref)
+ await flush()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(50)
+ // Bytes before `start` were never seen: this is someone else's history, not a new turn.
+ expect(h.onTaskNotification).not.toHaveBeenCalled()
+ } finally { h.tail.untrack('s') }
+ })
+})
+
+describe('failure log and wait', () => {
+ it('logs the first failure and the one that reaches the cap, and nothing in between', () => {
+ expect([1, 2, 3, 4, 5, 6, 7].map(failureDelayMs)).toEqual([2000, 4000, 8000, 16000, 32000, 60000, 60000])
+ expect(Array.from({ length: 30 }, (_, i) => i + 1).filter(logsFailure)).toEqual([1, 6])
+ })
+
+ it('names the observed status, never the reply', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const reader = new RemoteFile(async () => ({ code: 255, stdout: 'SECRET banner' }))
+ const h = harness(reader)
+ try {
+ h.tail.track('0123456789abcdef', ref)
+ await flush()
+ expect(warn.mock.calls[0][0]).toBe('[remote-context-tail] Read for session 01234567 failed (exit 255); retrying in 2000ms')
+ } finally { h.tail.untrack('0123456789abcdef') }
+ })
+
+ it('a hook for the session skips the rest of the failure wait, keeping the streak', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const readContextWindow = vi.fn().mockRejectedValue(new Error('down'))
+ const h = harness({ readContextWindow })
+ try {
+ h.tail.track('s', ref)
+ await flush()
+ for (const delay of [2000, 4000, 8000, 16000, 32000]) await vi.advanceTimersByTimeAsync(delay)
+ expect(readContextWindow).toHaveBeenCalledTimes(6) // now 60 s away
+ h.tail.track('s', { ...ref, conn: { ...ref.conn } })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(readContextWindow).toHaveBeenCalledTimes(7)
+ // Still failing: straight back to the capped wait, not to 2 s.
+ await vi.advanceTimersByTimeAsync(59_000)
+ expect(readContextWindow).toHaveBeenCalledTimes(7)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(readContextWindow).toHaveBeenCalledTimes(8)
+ } finally { h.tail.untrack('s') }
+ })
})
describe('session windows with bounded remote reads', () => {
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index c7e8d80f0..35c67e885 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -15,9 +15,10 @@ import {
type ContextTailOptions
} from '../core/context-tail'
import { splitCompleteLines } from '../core/subagent-tail'
-import type { RemoteFile, RemoteFileRef } from './remote-ssh/remote-file'
+import { ContextReadError, type RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'
const POLL_MS = 1000
+const FAILURE_MAX_DELAY_MS = 60_000
// Cap the first read like the local tail: a resumed transcript can be many MB. Only the LATEST
// assistant usage matters, so a tail of the file is enough. Defined locally (not imported) so
// context-tail.ts stays untouched; value mirrors its INITIAL_READ_CAP.
@@ -31,11 +32,27 @@ export function idleDelayMs(streak: number): number {
return Math.min(10_000, 1000 * 2 ** (streak - 3))
}
+/** Wait before the next read after the `failures`-th consecutive failed read: 2/4/8/16/32 s, then
+ * 60 s for as long as it keeps failing. */
+export function failureDelayMs(failures: number): number {
+ return Math.min(FAILURE_MAX_DELAY_MS, 2000 * 2 ** Math.min(Math.max(failures, 1) - 1, 5))
+}
+
+/** Whether the `failures`-th consecutive failure is logged: the first of a streak, and the one that
+ * settles at the 60 s cap. Not every retry — a host that stays unreachable used to print a line a
+ * minute for as long as the app ran. The recovery is logged separately. */
+export function logsFailure(failures: number): boolean {
+ return failures === 1 ||
+ (failureDelayMs(failures) === FAILURE_MAX_DELAY_MS && failureDelayMs(failures - 1) < FAILURE_MAX_DELAY_MS)
+}
+
interface Tracked {
ref: RemoteFileRef
offset: number | null
failures: number
retryAt: number
+ /** The last read found no file. Its first bytes, once it appears, are new — not history. */
+ sawAbsent: boolean
// Idle backoff, separate from the failure backoff above: consecutive successful EMPTY reads,
// and the time before which the tick skips this session (see idleDelayMs).
idleStreak: number
@@ -127,6 +144,9 @@ export function createRemoteContextTail(
else win.webContents.send(IPC.contextUpdate, payload)
}
+ // A session id names the session in a log line without saying anything about its content.
+ const label = (sessionId: string): string => `session ${sessionId.slice(0, 8)}`
+
// 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 || Date.now() < t.retryAt || Date.now() < t.idleUntil) return
@@ -134,27 +154,56 @@ export function createRemoteContextTail(
try {
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) {
+ if (result.absent) {
+ // Not created yet (see transcriptWindowCommand). An unused session stays here for as long
+ // as it stays unused, which is why this is not a failure: it used to walk the failure
+ // backoff to 60 s and log every retry. Poll it on the idle cadence instead — the hook for
+ // its first prompt resets that — and bootstrap from nothing when the file appears.
+ t.offset = null
t.carry = null
t.suppressCarry = false
- }
- t.offset = result.newOffset
- if (result.data.length) scan(sessionId, t, result.data, result.initial)
- if (!result.initial && result.data.length === 0) {
+ t.sawAbsent = true
t.idleStreak++
t.idleUntil = Date.now() + idleDelayMs(t.idleStreak)
} else {
- t.idleStreak = 0
- t.idleUntil = 0
+ // A file that appeared after we saw it missing is new from its first byte, so when the
+ // bootstrap read covers all of it (start 0) its events are live, not history.
+ const historical = result.initial && !(t.sawAbsent && result.start === 0)
+ t.sawAbsent = false
+ if (result.initial) {
+ t.carry = null
+ t.suppressCarry = false
+ }
+ t.offset = result.newOffset
+ if (result.data.length) scan(sessionId, t, result.data, historical)
+ if (!result.initial && result.data.length === 0) {
+ t.idleStreak++
+ t.idleUntil = Date.now() + idleDelayMs(t.idleStreak)
+ } else {
+ t.idleStreak = 0
+ t.idleUntil = 0
+ }
+ }
+ if (t.failures > 0) {
+ console.warn(`[remote-context-tail] Read for ${label(sessionId)} recovered after ` +
+ `${t.failures} failed attempt${t.failures === 1 ? '' : 's'}`)
}
t.failures = 0
t.retryAt = 0
- } catch {
+ } catch (err) {
if (sessions.get(sessionId) !== t) return
- const delay = Math.min(60_000, 2000 * 2 ** Math.min(t.failures++, 5))
+ const failures = ++t.failures
+ const delay = failureDelayMs(failures)
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`)
+ // A ContextReadError's reason is built to carry none of them; anything else stays unnamed.
+ if (logsFailure(failures)) {
+ const reason = err instanceof ContextReadError ? err.reason : 'unknown'
+ console.warn(failures === 1
+ ? `[remote-context-tail] Read for ${label(sessionId)} failed (${reason}); retrying in ${delay}ms`
+ : `[remote-context-tail] Read for ${label(sessionId)} still failing after ${failures} attempts ` +
+ `(${reason}); retrying every ${delay}ms until it recovers`)
+ }
return
} finally {
t.reading = false
@@ -190,9 +239,13 @@ export function createRemoteContextTail(
existing.ref.controlPath === ref.controlPath &&
JSON.stringify(existing.ref.conn) === JSON.stringify(ref.conn)) {
// A hook just arrived for this session — the transcript is about to grow, so drop the
- // idle backoff and let the next tick read it.
+ // idle backoff and let the next tick read it. The failure wait goes too: the host just
+ // reached us, so the outage behind the last failed read may well be over, and waiting out
+ // a 60 s retry would leave the meter stale that long after it recovered. The streak is
+ // kept, so a read that fails again goes straight back to its long wait.
existing.idleStreak = 0
existing.idleUntil = 0
+ existing.retryAt = 0
if (sessionWindow !== undefined && sessionWindow !== existing.sessionWindow) {
existing.sessionWindow = sessionWindow
existing.lastWindow = 0 // publish even if only provenance changed
@@ -205,6 +258,7 @@ export function createRemoteContextTail(
offset: null,
failures: 0,
retryAt: 0,
+ sawAbsent: false,
idleStreak: 0,
idleUntil: 0,
suppressCarry: false,
diff --git a/src/main/remote-ssh/remote-file.test.ts b/src/main/remote-ssh/remote-file.test.ts
index 05b549eb3..033972075 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, tailFromOffsetCappedArgs, tailLastBytesArgs, RemoteFile } from './remote-file'
+import { tailFromOffsetArgs, tailFromOffsetCappedArgs, tailLastBytesArgs, RemoteFile, ContextReadError } from './remote-file'
const conn = { host: 'h', user: 'u' }
const ref = { conn, controlPath: '/s.sock', path: '/home/u/.claude/projects/p/x.jsonl' }
@@ -99,6 +99,24 @@ describe('RemoteFile.readContextWindow', () => {
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()
})
+ // The poller logs `reason`, so it must say what was observed and nothing the host sent back.
+ it.each([
+ [async () => ({ code: 255, stdout: 'SECRET' }), 'exit 255'],
+ [async () => ({ code: 1, stdout: 'SECRET' }), 'exit 1'],
+ [async () => { throw new Error('SECRET') }, 'runner error'],
+ [async () => ({ code: 'ENOENT' as unknown as number, stdout: '' }), 'ENOENT'],
+ [async () => ({ code: 'SECRET token' as unknown as number, stdout: '' }), 'runner error'],
+ [async () => ({ code: 0, stdout: 'SECRET\n' }), 'malformed reply']
+ ])('fails with a payload-free reason (%#)', async (run, reason) => {
+ const err = await new RemoteFile(run).readContextWindow(ref, 42, 1024).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(ContextReadError)
+ expect((err as ContextReadError).reason).toBe(reason)
+ expect(String((err as Error).message)).not.toContain('SECRET')
+ })
+ it('answers a missing transcript as absent instead of failing', async () => {
+ const window = await new RemoteFile(async () => ({ code: 0, stdout: 'NODETERM_ABSENT\n' })).readContextWindow(ref, null, 1024)
+ expect(window).toMatchObject({ absent: true, data: Buffer.alloc(0) })
+ })
})
describe('RemoteFile.readTranscriptPage', () => {
diff --git a/src/main/remote-ssh/remote-file.ts b/src/main/remote-ssh/remote-file.ts
index 8b9636f63..6c5dd18ff 100644
--- a/src/main/remote-ssh/remote-file.ts
+++ b/src/main/remote-ssh/remote-file.ts
@@ -36,16 +36,45 @@ export function tailLastBytesArgs(conn: SshConnection, controlPath: string, path
return childArgs(conn, controlPath, `tail -c ${bytes} ${posixQuote(path)}`)
}
+/**
+ * A failed strict context read, with a `reason` the poller can log. The reason states only what was
+ * observed — the exit status, or that the reply did not parse — never the command, the path or the
+ * remote output, and never a guessed cause: the runner reports a timeout as status 1 (measured: a
+ * killed ssh has no status, which the runner maps to 1), the same as a remote command that exited 1,
+ * so a status is all it can honestly say. (255 is ssh's own status: no master, host unreachable,
+ * authentication.)
+ */
+export class ContextReadError extends Error {
+ constructor(readonly reason: string) {
+ super(`Remote transcript read failed (${reason})`)
+ }
+}
+
/** 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)
+ const command = transcriptWindowCommand(ref.path, offset, cap)
+ let result: { code: number; stdout: string }
+ try {
+ result = await this.run(childArgs(ref.conn, ref.controlPath, command))
+ } catch {
+ throw new ContextReadError('runner error')
+ }
+ const code: unknown = result.code
+ if (typeof code !== 'number') {
+ // The runner passes execFile's error code through, which is a Node identifier rather than a
+ // status when ssh never produced one (ENOENT, ERR_CHILD_PROCESS_STDIO_MAXBUFFER).
+ throw new ContextReadError(typeof code === 'string' && /^[A-Z0-9_]{1,64}$/.test(code) ? code : 'runner error')
+ }
+ if (code !== 0) throw new ContextReadError(`exit ${code}`)
+ try {
+ return parseTranscriptWindow(result.stdout, cap)
+ } catch {
+ throw new ContextReadError('malformed reply')
+ }
}
/**