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(pane): one -o per keyword (BSD parses the comma list as ONE column), and name custom agents

enesdb182ab5b608
diff --git a/src/core/agents/pane-owner.test.ts b/src/core/agents/pane-owner.test.ts
index cac63f040..40077769b 100644
--- a/src/core/agents/pane-owner.test.ts
+++ b/src/core/agents/pane-owner.test.ts
@@ -62,15 +62,35 @@ describe('isSafeTty', () => {
expect(isSafeTty(t)).toBe(false)
}
)
+
+ it('refuses an absurdly long tty — a bounded value, not just a well-charactered one', () => {
+ // Charset-clean and therefore past every other check, but no pty path is anywhere near this.
+ // The cost of not capping is DoS-shaped (a megabyte argv on the remote command line), which is
+ // why it is a cap rather than a pattern.
+ const long = `/dev/pts/${'0'.repeat(200)}`
+ expect(/^[A-Za-z0-9/._-]+$/.test(long)).toBe(true)
+ expect(isSafeTty(long)).toBe(false)
+ expect(isSafeTty(`/dev/pts/${'0'.repeat(100)}`)).toBe(true)
+ })
})
describe('foregroundArgvArgs', () => {
it('is one ps call on the pane tty, wide enough that BSD does not truncate the argv', () => {
expect(foregroundArgvArgs('/dev/pts/0')).toEqual({
bin: 'ps',
- args: ['-ww', '-o', 'pid=,pgid=,stat=,args=', '-t', '/dev/pts/0']
+ args: ['-ww', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat=', '-o', 'args=', '-t', '/dev/pts/0']
})
})
+
+ it('gives each keyword its OWN -o, because a comma list is one column on the BSDs', () => {
+ // FreeBSD parsefmt(): an item containing `=` is a column HEADER and is always the last item, so
+ // `-o pid=,pgid=,stat=,args=` asks for the single keyword `pid` with the header
+ // `,pgid=,stat=,args=` — one column, exit 0, a read that silently never works. The SSH leg runs
+ // this on the remote host, and FreeBSD/TrueNAS/pfSense is an ordinary SSH target.
+ const args = foregroundArgvArgs('/dev/pts/0')!.args
+ expect(args.filter((a) => a === '-o')).toHaveLength(4)
+ expect(args.some((a) => a.includes(','))).toBe(false)
+ })
it('refuses to build a command line around an unsafe tty', () => {
expect(foregroundArgvArgs('/dev/pts/0; id')).toBeNull()
})
diff --git a/src/core/agents/pane-owner.ts b/src/core/agents/pane-owner.ts
index 1119cafb6..fa9ad8379 100644
--- a/src/core/agents/pane-owner.ts
+++ b/src/core/agents/pane-owner.ts
@@ -116,7 +116,24 @@ export function foregroundArgvArgs(tty: string): { bin: string; args: string[] }
if (!isSafeTty(tty)) return null
// -ww: BSD ps truncates `args` to the terminal width without it, which would cut off exactly the
// script path that names the agent. Harmless (and also "unlimited") on procps.
- return { bin: 'ps', args: ['-ww', '-o', 'pid=,pgid=,stat=,args=', '-t', tty] }
+ //
+ // ONE `-o` PER KEYWORD, and it is not style. `-o pid=,pgid=,stat=,args=` is a single column on
+ // the BSDs: FreeBSD's `bin/ps/keyword.c` `parsefmt()` treats an item containing `=` as "a column
+ // header, may contain embedded separator characters and is always the last item" — it sets
+ // `tempstr = NULL` and the header swallows the rest, so the whole string parses as the keyword
+ // `pid` with the header `,pgid=,stat=,args=`. `ps` then exits 0 with one column and the read
+ // silently never works. macOS is NOT affected — Apple's adv_cmds wraps that branch in
+ // `#ifndef __APPLE__` and always `strsep`s on " \t,\n" — but FreeBSD/TrueNAS/pfSense is an
+ // ordinary SSH target and this call runs on the REMOTE host.
+ //
+ // The multi-`-o` form is sanctioned by FreeBSD's own ps(1) ("Multiple keywords may also be given
+ // in the form of more than one -o option… If all keywords have empty header texts, no header line
+ // is written") and is byte-identical on procps-ng 4.0.4 — diffed against the single-`-o` form on
+ // a real pane running `sleep 300 | cat`.
+ return {
+ bin: 'ps',
+ args: ['-ww', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat=', '-o', 'args=', '-t', tty]
+ }
}
/** One parsed `ps` row. Internal — only the argv leaves this module. */
diff --git a/src/core/agents/pane-probe.ts b/src/core/agents/pane-probe.ts
index a29094a07..4c02805a3 100644
--- a/src/core/agents/pane-probe.ts
+++ b/src/core/agents/pane-probe.ts
@@ -22,6 +22,17 @@
* repo at well under a second each), short enough that a wedged one is reported rather than sat on.
* The timeout is a REFUSAL, not a retry — `probeWithin` answers null and `isAgentPane(null)` is
* `unknown`, which the caller may retry deliberately rather than by hanging.
+ *
+ * ── DO NOT RETRY `unknown` ON A FIXED SHORT TIMER WITHOUT A CIRCUIT BREAKER ─────────────────────
+ *
+ * This deadline abandons the WAIT, not the WORK. Measured: the probe answers null at 2.0s while 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`, which means that
+ * when the master socket is DEAD 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 once at 72k logins/day
+ * (memory: ssh-controlmaster-fallback). Any caller that retries on `unknown` needs a breaker —
+ * backoff plus a per-target cap — before the second attempt, not after the incident.
*/
export const PANE_PROBE_TIMEOUT_MS = 2000
diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.ts
index bcad7c634..69474216a 100644
--- a/src/core/pty-manager.pane-owner.test.ts
+++ b/src/core/pty-manager.pane-owner.test.ts
@@ -112,7 +112,7 @@ describe('PtyManager.paneOwner', () => {
})
expect(calls[1]).toEqual({
file: 'ps',
- args: ['-ww', '-o', 'pid=,pgid=,stat=,args=', '-t', TTY]
+ args: ['-ww', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat=', '-o', 'args=', '-t', TTY]
})
expect(owner).toEqual({
panePid: 2485382,
@@ -136,7 +136,7 @@ describe('PtyManager.paneOwner', () => {
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=,pgid=,stat=,args=' '-t' '${TTY}'`
+ `ps '-ww' '-o' 'pid=' '-o' 'pgid=' '-o' 'stat=' '-o' 'args=' '-t' '${TTY}'`
)
expect(owner).toMatchObject({ tty: TTY, argv: [expect.stringContaining('claude'), 'rg --files'] })
})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 04d8c868c..8ea38a28b 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -2905,7 +2905,14 @@ export class PtyManager {
*
* 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.
+ * 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.
+ *
+ * `remotePaneOwnerArgs` 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.
*/
async paneOwner(persistKey: string): Promise<PaneOwner | null> {
const target = sessionName(persistKey)
diff --git a/src/core/remote-ssh/control-master.injection.test.ts b/src/core/remote-ssh/control-master.injection.test.ts
index d016a40f3..be1689622 100644
--- a/src/core/remote-ssh/control-master.injection.test.ts
+++ b/src/core/remote-ssh/control-master.injection.test.ts
@@ -202,7 +202,20 @@ describe('remoteForegroundArgvArgs: a tty the remote host reported is DATA, neve
expect(args).not.toBeNull()
const { argv, unquotedMeta } = shellParse(args![args!.length - 1])
expect(unquotedMeta).toEqual([])
- expect(argv).toEqual(['ps', '-ww', '-o', 'pid=,pgid=,stat=,args=', '-t', '/dev/pts/7'])
+ 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', () => {
diff --git a/src/shared/agents/pane-owner-predicate.test.ts b/src/shared/agents/pane-owner-predicate.test.ts
index 175f001bb..225f64911 100644
--- a/src/shared/agents/pane-owner-predicate.test.ts
+++ b/src/shared/agents/pane-owner-predicate.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { isAgentPane, AGENT_BINARIES } from './pane-owner-predicate'
+import { isAgentPane, AGENT_BINARIES, binariesFor, binaryFromLaunchCmd } from './pane-owner-predicate'
import { isShellCommand } from './pane'
import { BUILTIN_AGENT_IDS, AGENT_CONFIG } from './config'
@@ -70,12 +70,37 @@ describe('isAgentPane', () => {
expect(isAgentPane(owner(['node -claude']), 'claude')).toBe('not-agent')
})
- it('answers unknown for a custom agent whose binary nothing can name', () => {
- // `custom:<uuid>` has no entry, and guessing one would be the exact class of mistake this
- // module replaces. The caller refuses, retryably, rather than admitting the pane.
+ it('answers unknown for a custom agent whose definition the caller did not hand over', () => {
+ // `custom:<uuid>` alone names nothing, and guessing would be the exact class of mistake this
+ // module replaces. The fix for the dead end is `binariesFor(id, customAgents)` below, not a
+ // guess here.
expect(isAgentPane(owner(['node /opt/bin/whatever']), 'custom:abc')).toBe('unknown')
})
+ it('verifies a custom agent once its launch command is supplied', () => {
+ const customAgents = [{ id: 'custom:abc', launchCmd: 'npx -y my-agent --serve' }]
+ expect(
+ isAgentPane(owner(['node /home/u/.npm/_npx/1/node_modules/.bin/my-agent --serve']), 'custom:abc',
+ binariesFor('custom:abc', customAgents))
+ ).toBe('agent')
+ expect(isAgentPane(owner(['-zsh'], 'zsh'), 'custom:abc', binariesFor('custom:abc', customAgents)))
+ .toBe('not-agent')
+ })
+
+ it('proves the agent is IN the foreground group, not that it is READING the tty', () => {
+ // `sh -c "sleep 600 | claude"`: claude really is in the group, so `agent` is the honest answer —
+ // but its stdin is the pipe, and text written to the pane waits in the tty buffer for the shell.
+ // Documented here so the delivery gate does not read this verdict as "it will be read".
+ expect(isAgentPane(owner(['sh -c sleep 600 | claude', 'sleep 600', 'claude']), 'claude')).toBe('agent')
+ })
+
+ it('refuses two shapes it cannot see through, rather than guessing (documented false negatives)', () => {
+ // A script path with a space splits into two tokens; a symlink carries the name it was invoked
+ // as. Both answer not-agent — the safe direction, and the reason they are documented not fixed.
+ expect(isAgentPane(owner(['node /opt/my agents/claude']), 'claude')).toBe('not-agent')
+ expect(isAgentPane(owner(['/usr/local/bin/claude-work']), 'claude')).toBe('not-agent')
+ })
+
it('accepts a caller-supplied binary list for a custom agent', () => {
expect(isAgentPane(owner(['node /opt/bin/whatever']), 'custom:abc', ['whatever'])).toBe('agent')
expect(isAgentPane(owner(['node /opt/bin/other']), 'custom:abc', ['whatever'])).toBe('not-agent')
@@ -90,3 +115,65 @@ describe('isAgentPane', () => {
}
})
})
+
+describe('binaryFromLaunchCmd', () => {
+ it('sees through package runners and their verbs and flags', () => {
+ expect(binaryFromLaunchCmd('npx -y my-agent')).toBe('my-agent')
+ expect(binaryFromLaunchCmd('pnpm dlx some-cli --flag')).toBe('some-cli')
+ expect(binaryFromLaunchCmd('bun run my-agent')).toBe('my-agent')
+ expect(binaryFromLaunchCmd('npx @acme/[email protected]')).toBe('my-agent')
+ })
+
+ it('sees through env assignments and interpreters', () => {
+ expect(binaryFromLaunchCmd('env FOO=1 BAR=2 my-agent --serve')).toBe('my-agent')
+ expect(binaryFromLaunchCmd('node /opt/bin/my-agent.js')).toBe('my-agent.js')
+ })
+
+ it('takes a plain command as itself', () => {
+ expect(binaryFromLaunchCmd('my-agent')).toBe('my-agent')
+ expect(binaryFromLaunchCmd('/opt/vendor/bin/my-agent --x')).toBe('my-agent')
+ })
+
+ it('REFUSES to name a program every plain terminal also runs', () => {
+ // The danger is not a wrong name that matches nothing — it is a name that matches EVERYTHING.
+ // `bash` as an agent binary would make every idle shell on the canvas a delivery target.
+ for (const cmd of ['bash -lc "my-agent --serve"', 'sh -c my-agent', 'ssh host my-agent', 'sudo my-agent', 'zsh']) {
+ expect(binaryFromLaunchCmd(cmd), cmd).toBeNull()
+ }
+ })
+
+ it('answers null for nothing at all', () => {
+ expect(binaryFromLaunchCmd('')).toBeNull()
+ expect(binaryFromLaunchCmd(' ')).toBeNull()
+ expect(binaryFromLaunchCmd(null)).toBeNull()
+ expect(binaryFromLaunchCmd('--flag --only')).toBeNull()
+ })
+})
+
+describe('binariesFor', () => {
+ const customAgents = [
+ { id: 'custom:abc', launchCmd: 'npx -y my-agent' },
+ { id: 'custom:shell', launchCmd: 'bash -lc "run-me"' }
+ ]
+
+ it('answers the built-in table for a built-in id', () => {
+ expect(binariesFor('claude')).toEqual(AGENT_BINARIES.claude)
+ })
+
+ it('derives a custom agent binary from its launch command — the dead end, closed', () => {
+ expect(binariesFor('custom:abc', customAgents)).toEqual(['my-agent'])
+ })
+
+ it('stays null when the custom agent is not in the list we were handed', () => {
+ expect(binariesFor('custom:zzz', customAgents)).toBeNull()
+ expect(binariesFor('custom:abc')).toBeNull()
+ })
+
+ it('stays null when the launch command names something every shell runs', () => {
+ expect(binariesFor('custom:shell', customAgents)).toBeNull()
+ })
+
+ it('treats an unrecognised NON-custom id as its own command, mirroring resolveAgent', () => {
+ expect(binariesFor('aider')).toEqual(['aider'])
+ })
+})
diff --git a/src/shared/agents/pane-owner-predicate.ts b/src/shared/agents/pane-owner-predicate.ts
index aef2a6bec..5c851196b 100644
--- a/src/shared/agents/pane-owner-predicate.ts
+++ b/src/shared/agents/pane-owner-predicate.ts
@@ -50,6 +50,26 @@ export const AGENT_BINARIES: Record<string, readonly string[]> = {
grok: ['grok']
}
+/**
+ * Names that must NEVER become an agent's binary, however a launch command was written.
+ *
+ * Every one of them is a program the user's own plain terminals run. Admitting `bash` as "the
+ * codex-custom binary" would make every idle shell on the canvas a valid delivery target — the
+ * exact hole `isShellCommand`'s negation had, re-opened through the custom-agent door. When a
+ * launch command's first meaningful token is one of these, the honest answer is that we cannot name
+ * the binary (null ⇒ `unknown` ⇒ refuse), not that we can.
+ */
+const NEVER_A_BINARY = new Set([
+ 'sh', 'bash', 'zsh', 'fish', 'dash', 'ksh', 'tcsh', 'nu', 'pwsh', 'powershell', 'xonsh', 'elvish',
+ 'ssh', 'sudo', 'doas', 'su', 'tmux', 'screen', 'script'
+])
+
+/** Package runners: the interesting name is the package they fetch, not the runner. */
+const RUNNERS = new Set(['npx', 'bunx', 'pnpx', 'npm', 'pnpm', 'yarn', 'bun', 'deno', 'uvx', 'pipx'])
+
+/** Tokens that stand between a runner/interpreter and the name we are after. */
+const RUNNER_VERBS = new Set(['exec', 'run', 'dlx', 'x', '--'])
+
/**
* Interpreters that are followed by the script they run. `node /usr/local/bin/claude` is the shape
* every npm-installed agent CLI actually has on this host (measured), so argv[0]'s basename alone
@@ -83,6 +103,75 @@ function effectiveBinary(commandLine: string): string {
return baseName(next)
}
+/**
+ * The binary a LAUNCH COMMAND will end up running, as a bare name — or null when it cannot be named
+ * safely.
+ *
+ * `launchCmd` is free text the user typed into Settings → Agents, so it is not a program name: it
+ * is `npx -y my-agent`, `bash -lc "…"`, `env FOO=1 my-agent --flag`. The walk below skips wrappers
+ * to the first thing that looks like the program, and refuses outright when that thing is something
+ * every plain terminal also runs (`NEVER_A_BINARY`) — a wrong name here does not merely fail to
+ * match, it matches everything.
+ *
+ * A trailing npm version specifier is dropped (`@acme/[email protected]` → `my-agent`) because that is
+ * how the process will appear in argv. A `.js` extension is kept, for the same reason.
+ */
+export function binaryFromLaunchCmd(launchCmd: string | null | undefined): string | null {
+ if (!launchCmd) return null
+ const tokens = launchCmd.trim().split(/\s+/).filter(Boolean)
+ for (let i = 0; i < tokens.length && i < 16; i++) {
+ const token = tokens[i]
+ if (token.startsWith('-') || RUNNER_VERBS.has(token)) continue // an option or a runner verb
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) continue // `env FOO=1 …`'s assignments
+ const base = baseName(token)
+ if (!base) continue
+ if (NEVER_A_BINARY.has(base)) return null
+ if (RUNNERS.has(base) || INTERPRETERS.has(base) || base === 'env') continue
+ // Strip an npm version specifier, but never a leading scope: `@acme/x@1` → `x`, `@acme` → `@acme`.
+ const at = base.lastIndexOf('@')
+ return at > 0 ? base.slice(0, at) : base
+ }
+ return null
+}
+
+/**
+ * The binary names to expect for an agent id — built-in from the table, custom from its launch
+ * command.
+ *
+ * Without this a `custom:<uuid>` agent has no entry, `isAgentPane` answers `unknown`, and because
+ * `unknown` means "the caller may retry", a delivery gate refuses that pane on every attempt
+ * forever behind a retryable-looking error. That is a dead end wearing a transient error's clothes.
+ * The information to avoid it already exists — `resolveAgent`
+ * (`src/renderer/state/workspace.ts`) resolves exactly this `launchCmd`, and falls back to the
+ * agent id itself for an id it does not know, which is mirrored here.
+ *
+ * Still null (⇒ `unknown`, ⇒ refuse) in the two cases where no honest answer exists: a
+ * `custom:<uuid>` whose definition is not in the list handed to us, and a launch command whose
+ * program cannot be named without naming something every plain shell also runs. Null is a refusal,
+ * not a guess — but a caller holding the settings can now avoid it for every configured agent.
+ *
+ * `customAgents` is structural rather than `CustomAgent[]` so this stays a leaf module.
+ */
+export function binariesFor(
+ agentId: string,
+ customAgents?: readonly { id: string; launchCmd: string }[]
+): readonly string[] | null {
+ const builtin = AGENT_BINARIES[agentId]
+ if (builtin) return builtin
+ const custom = customAgents?.find((c) => c.id === agentId)
+ if (custom) {
+ const name = binaryFromLaunchCmd(custom.launchCmd)
+ return name ? [name] : null
+ }
+ // A `custom:` id we were given no definition for is unknowable — deriving from the id would yield
+ // `custom:<uuid>`, a name that matches nothing, i.e. `not-agent`: a terminal answer to a question
+ // we never actually asked. Anything else is treated as its own launch command, which is what
+ // resolveAgent does for an agent id it does not recognise.
+ if (agentId.startsWith('custom:')) return null
+ const name = binaryFromLaunchCmd(agentId)
+ return name ? [name] : null
+}
+
/**
* POSITIVE and kernel-truth, replacing `!isShellCommand(pane)`, which was neither.
*
@@ -99,9 +188,23 @@ function effectiveBinary(commandLine: string): string {
* Matched on the BASENAME of argv[0] (after interpreter resolution), never on a substring of the
* command line — `vim /etc/claude.conf` and `grep -r claude .` are not claude panes.
*
- * `binaries` overrides the built-in table for a custom agent whose binary the caller knows. Without
- * it an agent id with no entry answers `unknown`: we cannot name what should be there, so we cannot
- * claim to have seen it.
+ * `binaries` overrides the derived list. A caller holding the settings should pass
+ * `binariesFor(agentId, settings.customAgents)` so a CUSTOM agent is verifiable too; without it a
+ * `custom:<uuid>` cannot be named and answers `unknown`, which is a refusal, not a licence.
+ *
+ * ── WHAT THIS DOES NOT PROVE (carry into the delivery gate) ─────────────────────────────────────
+ *
+ * 1. **It proves the agent is IN the foreground process group, not that it is the thing READING
+ * the tty.** `sh -c "sleep 600 | claude"` answers `agent`, and correctly so — claude really is
+ * in the group. But claude's stdin is the PIPE, so text written to the pane sits in the tty
+ * buffer until the shell reads it after the pipeline exits. That is the "rename splice = lost
+ * launch" shape: the write succeeds and the payload surfaces later, somewhere else. A gate that
+ * needs "the agent is reading" needs a further check; this predicate is not it.
+ * 2. **Two false negatives are terminal and deliberate**, documented rather than fixed because the
+ * alternative is guessing: a script path containing a SPACE (the argv split cannot tell it from
+ * two tokens), and a differently-named SYMLINK to the agent binary (argv carries the name it
+ * was invoked as, not the target). Both answer `not-agent` — a refusal, which is the safe
+ * direction.
*
* `isShellCommand` is deliberately NOT deleted — its existing callers (the restart exit poll, the
* reconnect resync) ask a genuinely different question ("has the CLI let go of the pane?") for
@@ -110,11 +213,11 @@ function effectiveBinary(commandLine: string): string {
export function isAgentPane(
owner: PaneOwner | null | undefined,
expected: string,
- binaries?: readonly string[]
+ binaries?: readonly string[] | null
): AgentPaneVerdict {
if (!owner) return 'unknown'
if (!owner.argv || owner.argv.length === 0) return 'unknown'
- const wanted = binaries ?? AGENT_BINARIES[expected]
+ const wanted = binaries ?? binariesFor(expected)
if (!wanted || wanted.length === 0) return 'unknown'
for (const line of owner.argv) {
if (wanted.includes(effectiveBinary(line))) return 'agent'