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(pane): read what actually owns a pane — pid, tty, foreground pgid, argv

enesb8230311e6d3
diff --git a/src/core/agents/pane-owner.test.ts b/src/core/agents/pane-owner.test.ts
new file mode 100644
index 000000000..5cb771499
--- /dev/null
+++ b/src/core/agents/pane-owner.test.ts
@@ -0,0 +1,203 @@
+// The pure parsers, then the same parsers against a REAL tmux pane.
+//
+// The `ps` fixtures below are not invented: they are literal output captured on this host while
+// writing the module (Linux 6.8, procps-ng 4.0.4), which is why they carry a `stat` column and why
+// the foreground group is found through its `+` flag rather than through `tpgid`. See the module
+// docblock for what was measured and what it ruled out.
+import { describe, it, expect, afterAll } from 'vitest'
+import { execFileSync } from 'child_process'
+import {
+ PANE_OWNER_FMT,
+ foregroundArgvArgs,
+ foregroundPgid,
+ isSafeTty,
+ parseForegroundArgv,
+ parsePaneOwner
+} from './pane-owner'
+
+describe('PANE_OWNER_FMT', () => {
+ it('asks for pid, tty and current command in one round-trip', () => {
+ expect(PANE_OWNER_FMT).toBe('#{pane_pid}|#{pane_tty}|#{pane_current_command}')
+ })
+})
+
+describe('parsePaneOwner', () => {
+ it('parses a well-formed line', () => {
+ expect(parsePaneOwner('4242|/dev/pts/9|claude')).toEqual({
+ panePid: 4242,
+ tty: '/dev/pts/9',
+ command: 'claude'
+ })
+ })
+
+ it('tolerates the trailing newline a real display-message writes', () => {
+ expect(parsePaneOwner('4242|/dev/pts/9|node\n')?.command).toBe('node')
+ })
+
+ // Unknown is never evidence of a particular command — paneCommand's contract, verbatim.
+ it.each(['', ' ', 'notanumber|/dev/pts/9|claude', '0|/dev/pts/9|claude', '4242', '4242||claude', '4242|/dev/pts/9|'])(
+ 'answers null for %j rather than guessing',
+ (s) => {
+ expect(parsePaneOwner(s)).toBeNull()
+ }
+ )
+
+ it('answers null for a missing read rather than throwing', () => {
+ expect(parsePaneOwner(null)).toBeNull()
+ expect(parsePaneOwner(undefined)).toBeNull()
+ })
+})
+
+describe('isSafeTty', () => {
+ it.each(['/dev/pts/0', '/dev/ttys004', 'pts/9'])('accepts the real thing: %s', (t) => {
+ expect(isSafeTty(t)).toBe(true)
+ })
+ it.each(['', '/dev/pts/0; rm -rf ~', '/dev/pts/$(id)', '/dev/../etc/passwd', '/dev/pts/0 && x', '/dev/pts/`id`'])(
+ 'refuses %j — nothing shell-live reaches a command line',
+ (t) => {
+ expect(isSafeTty(t)).toBe(false)
+ }
+ )
+})
+
+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']
+ })
+ })
+ it('refuses to build a command line around an unsafe tty', () => {
+ expect(foregroundArgvArgs('/dev/pts/0; id')).toBeNull()
+ })
+})
+
+// Captured verbatim from `ps -ww -o pid=,pgid=,stat=,args= -t /dev/pts/0` while a pipeline ran in a
+// real tmux pane. `Ss` (no `+`) is the pane's own shell; the `S+` rows are the foreground group.
+const REAL_PS = [
+ '2485382 2485382 Ss -bash',
+ '2489089 2489089 S+ /bin/sh -c sleep 200 | cat',
+ '2489091 2489089 S+ sleep 200',
+ '2489092 2489089 S+ cat'
+].join('\n')
+
+describe('foregroundPgid', () => {
+ it('reads the foreground group off the + flag, not off the pane shell', () => {
+ expect(foregroundPgid(REAL_PS)).toBe(2489089)
+ })
+ it('answers null when nothing is marked foreground', () => {
+ expect(foregroundPgid('2485382 2485382 Ss -bash')).toBeNull()
+ })
+ it('answers null on garbage and on nothing at all', () => {
+ expect(foregroundPgid('<<ps: illegal option>>')).toBeNull()
+ expect(foregroundPgid('')).toBeNull()
+ expect(foregroundPgid(null)).toBeNull()
+ })
+})
+
+describe('parseForegroundArgv', () => {
+ it('returns every argv in the group, group leader first', () => {
+ expect(parseForegroundArgv(REAL_PS, 2489089)).toEqual([
+ '/bin/sh -c sleep 200 | cat',
+ 'sleep 200',
+ 'cat'
+ ])
+ })
+
+ it('ignores rows from another pgid — a backgrounded job shares the tty', () => {
+ expect(parseForegroundArgv(REAL_PS, 2489089)).toHaveLength(3)
+ expect(parseForegroundArgv(REAL_PS, 2489089).join('\n')).not.toContain('-bash')
+ })
+
+ it('keeps the full argv, so the script path an interpreter runs is still there', () => {
+ const ps = '2503294 2503294 Sl+ node /home/u/.npm/bin/claude --resume x'
+ expect(parseForegroundArgv(ps, 2503294)).toEqual(['node /home/u/.npm/bin/claude --resume x'])
+ })
+
+ it('answers [] on garbage — never throws, never partially guesses', () => {
+ expect(parseForegroundArgv('<<ps: illegal option>>', 4243)).toEqual([])
+ expect(parseForegroundArgv(REAL_PS, 0)).toEqual([])
+ expect(parseForegroundArgv(null, 4243)).toEqual([])
+ })
+})
+
+/**
+ * THE REAL PANE (Global Constraint 9).
+ *
+ * Everything above trusts our own fixtures. This drives a real tmux server on a socket of its own,
+ * runs a real command in a real pane, and asks the real `ps` — so the format string, the `ps`
+ * columns and the `+` flag are judged by the programs that produce them, not by us.
+ *
+ * tmux allocates the pane's pty itself, so no node-pty wrapper is needed to make this real: the
+ * process under test genuinely has a controlling terminal and a foreground process group.
+ *
+ * The socket is private (`nt-paneowner-<pid>-<rand>`) and killed in afterAll — nothing here can
+ * touch the app's `node-terminal` socket or the SSH `nodeterm-rmt` one.
+ */
+const tmuxBin = (() => {
+ try {
+ return execFileSync('sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null
+ } catch {
+ return null
+ }
+})()
+
+const SOCKET = `nt-paneowner-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
+const tmux = (...args: string[]) =>
+ execFileSync(tmuxBin as string, ['-L', SOCKET, ...args], { encoding: 'utf8', timeout: 10_000 })
+
+afterAll(() => {
+ if (!tmuxBin) return
+ try {
+ tmux('kill-server')
+ } catch {
+ // already gone — the server exits on its own when the last session dies
+ }
+})
+
+describe.skipIf(!tmuxBin)('against a real tmux pane', () => {
+ it('finds the command actually running in the pane, which pane_current_command cannot name', () => {
+ tmux('new-session', '-d', '-s', 'owner', 'sh')
+ // A distinctive argv the pane's shell could never be confused with.
+ tmux('send-keys', '-t', 'owner', 'sleep 411', 'Enter')
+ // The pane's shell forks and execs asynchronously; poll rather than sleep a fixed time.
+ let argv: string[] = []
+ let identity: ReturnType<typeof parsePaneOwner> = null
+ const deadline = Date.now() + 10_000
+ while (Date.now() < deadline) {
+ identity = parsePaneOwner(tmux('display-message', '-p', '-t', 'owner', PANE_OWNER_FMT))
+ if (identity) {
+ const call = foregroundArgvArgs(identity.tty)
+ expect(call).not.toBeNull()
+ const out = execFileSync(call!.bin, call!.args, { encoding: 'utf8', timeout: 10_000 })
+ const pgid = foregroundPgid(out)
+ if (pgid !== null) argv = parseForegroundArgv(out, pgid)
+ }
+ if (argv.some((a) => a.includes('sleep 411'))) break
+ }
+ expect(identity).not.toBeNull()
+ expect(identity!.panePid).toBeGreaterThan(0)
+ expect(identity!.tty).toMatch(/^\/dev\//)
+ expect(argv.join('\n')).toContain('sleep 411')
+ // And the pane's own shell — which is NOT in the foreground group — is not reported as owner.
+ expect(argv.every((a) => !/(^|\/)-?sh$/.test(a))).toBe(true)
+ }, 30_000)
+
+ it('reports the pane shell as owner once the command finishes, so an idle pane is never an agent', () => {
+ tmux('new-session', '-d', '-s', 'idle', 'sh')
+ let argv: string[] = []
+ const deadline = Date.now() + 10_000
+ while (Date.now() < deadline) {
+ const identity = parsePaneOwner(tmux('display-message', '-p', '-t', 'idle', PANE_OWNER_FMT))
+ if (identity) {
+ const call = foregroundArgvArgs(identity.tty)!
+ const out = execFileSync(call.bin, call.args, { encoding: 'utf8', timeout: 10_000 })
+ const pgid = foregroundPgid(out)
+ if (pgid !== null) argv = parseForegroundArgv(out, pgid)
+ }
+ if (argv.length > 0) break
+ }
+ expect(argv).toHaveLength(1)
+ expect(argv[0]).toMatch(/(^|\/)-?sh$/)
+ }, 30_000)
+})
diff --git a/src/core/agents/pane-owner.ts b/src/core/agents/pane-owner.ts
new file mode 100644
index 000000000..532a310a1
--- /dev/null
+++ b/src/core/agents/pane-owner.ts
@@ -0,0 +1,175 @@
+/**
+ * WHO OWNS A PANE — read from the kernel, not from a name allowlist.
+ *
+ * The question this module answers is not `#{pane_current_command}`. That is one name, tmux's own
+ * shallow reading of the pane's process, and it is wrong in both directions for a safety gate:
+ *
+ * - measured on this host, a pane running the fake agent `…/fakebin/claude --resume x` (a
+ * `#!/usr/bin/env node` script) reports `#{pane_current_command}` = `node`. Every npm-installed
+ * agent CLI has that shape, so a name gate cannot tell claude from any other node process.
+ * - `isShellCommand` (`src/shared/agents/pane.ts`) is a SEVEN-name allowlist, so `!isShellCommand`
+ * — the old "this pane is an agent" gate — is true for `nu`, `pwsh`, `xonsh`, `elvish`, `ssh`
+ * and `python`. Text delivered there executes, because `sendText` appends Enter.
+ *
+ * The kernel already tracks the right thing: every terminal has a FOREGROUND PROCESS GROUP
+ * (`tcgetpgrp`), and only that group can read the tty. Whatever is in it is what will receive the
+ * bytes we are about to write. So: `#{pane_tty}` from tmux, then one `ps` on that tty, then the
+ * argv of the group the kernel marks as the foreground one. Nothing here is spoofable by a
+ * persisted field going stale.
+ *
+ * ── THE MEASUREMENT (Global Constraint: measure the shape, do not assume it) ────────────────────
+ *
+ * Run on this host, Linux 6.8, procps-ng 4.0.4, against a tmux session on a private socket
+ * (2026-08-15):
+ *
+ * $ tmux -L probe display-message -p -t owner-probe '#{pane_pid}|#{pane_tty}|#{pane_current_command}'
+ * 2485382|/dev/pts/0|sh
+ * $ ps -ww -o pid=,pgid=,stat=,args= -t /dev/pts/0
+ * 2485382 2485382 Ss -bash <- the pane's own shell, NOT foreground
+ * 2489089 2489089 S+ /bin/sh -c sleep 200 | cat <- the foreground group, three members
+ * 2489091 2489089 S+ sleep 200
+ * 2489092 2489089 S+ cat
+ *
+ * Two facts the plan's sketch got wrong here, both measured rather than reasoned:
+ *
+ * 1. `ps -g <pgid>` does NOT select a process group on this procps. `-g` selects by SESSION or by
+ * effective group NAME, and the GNU long option `--pgid` does not exist (`error: unknown gnu
+ * long option`). So the Linux-specific "read `tpgid`, then `ps -g` that pgid" route does not
+ * work here at all, and a second round-trip would have bought nothing.
+ * 2. Selecting by TTY works identically on Linux and BSD — `-t /dev/pts/0` and `-t pts/0` are both
+ * accepted — and `stat`'s `+` flag marks foreground-group membership on BOTH (procps STAT and
+ * BSD STAT define `+` the same way: "in the foreground process group of its controlling
+ * terminal"). `tpgid` is a procps-only column, so asking for it is what would have forced a
+ * `process.platform === 'darwin'` branch.
+ *
+ * Hence ONE invocation for both platforms — `ps -ww -o pid=,pgid=,stat=,args= -t <tty>` — and the
+ * foreground group derived from the `+` flag rather than from a column only Linux has. `-ww` is
+ * load-bearing on BSD, where `ps` truncates the command to the terminal width by default; a
+ * truncated argv would hide the script path that names the agent.
+ *
+ * macOS was NOT reachable from the host this was measured on, so the darwin leg is unverified —
+ * but it is unverified for a shape whose every piece is POSIX/BSD-documented, rather than for a
+ * `tpgid` column BSD is documented not to have. **Mac verification owed.** If `ps` fails on some
+ * platform, `parseForegroundArgv` answers `[]`, `PtyManager.paneOwner` answers `null`, and gate 1
+ * refuses there — a refusal, never a guess.
+ *
+ * No credential is involved anywhere in this module — a tty path and a pid are the only inputs — so
+ * Global Constraint 6 ("no credential on any argv") is trivially satisfied. Do not add one: if this
+ * read ever needs to authenticate, it needs a stdin channel, not a flag.
+ */
+import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'
+
+/** What one `display-message` round-trip yields: everything but the argv. */
+export type PaneIdentity = Omit<PaneOwner, 'argv'>
+
+/**
+ * One round-trip for the three fields the read needs. Same `|` separator as `session-memory.ts`'s
+ * `PANE_FMT`, for the same reason: one string, one parser, no second copy to drift.
+ */
+export const PANE_OWNER_FMT = '#{pane_pid}|#{pane_tty}|#{pane_current_command}'
+
+/**
+ * Parse `display-message -p '<PANE_OWNER_FMT>'`.
+ *
+ * Same failure contract as `PtyManager.paneCommand`, copied deliberately: unknown is never evidence
+ * of a particular command, so anything malformed answers null rather than a partial object. A pid
+ * of 0 is rejected the way `parsePaneList` rejects it — an empty field parses as 0 and would
+ * produce a phantom pane.
+ */
+export function parsePaneOwner(stdout: string | null | undefined): PaneIdentity | null {
+ if (!stdout) return null
+ const line = stdout.trim().split('\n')[0]?.trim()
+ if (!line) return null
+ const parts = line.split('|')
+ if (parts.length < 3) return null
+ const panePid = Number(parts[0])
+ if (!Number.isInteger(panePid) || panePid <= 0) return null
+ const tty = parts[1].trim()
+ const command = parts[2].trim()
+ if (!tty || !command) return null
+ return { panePid, tty, command }
+}
+
+/**
+ * Is this a pty path safe to carry into a command line?
+ *
+ * `#{pane_tty}` is kernel-supplied (`/dev/pts/N`, `/dev/ttys00N`) and not user-controllable, so
+ * this is the second layer, applied where the value ENTERS a command line — the same posture as
+ * `remote-safety.ts`'s `isSafeNodeId`. It matters most on the SSH leg, where the value is spliced
+ * into a string a REMOTE shell parses.
+ */
+export function isSafeTty(tty: string | null | undefined): boolean {
+ if (!tty || tty.length > 128) return false
+ return /^\/?(dev\/)?[A-Za-z0-9][A-Za-z0-9/._-]*$/.test(tty) && !tty.includes('..')
+}
+
+/**
+ * The `ps` invocation that lists every process on a pane's tty, with the columns
+ * `parseForegroundArgv` reads. Returns null for a tty that fails `isSafeTty` — the caller then
+ * answers null, i.e. "unknown", rather than running something it did not fully construct.
+ *
+ * `panePid` is deliberately NOT a parameter: the measurement above showed the pid-based selectors
+ * (`-g <pgid>`, `--pgid`) do not do what the sketch assumed on this procps, and the tty is the
+ * handle the kernel actually keys the foreground group on.
+ */
+export function foregroundArgvArgs(tty: string): { bin: string; args: string[] } | null {
+ 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 parsed `ps` row. Internal — only the argv leaves this module. */
+interface PsRow {
+ pid: number
+ pgid: number
+ stat: string
+ args: string
+}
+
+const PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/
+
+function parsePsRows(stdout: string | null | undefined): PsRow[] {
+ if (!stdout) return []
+ const rows: PsRow[] = []
+ for (const line of stdout.split('\n')) {
+ const m = PS_ROW.exec(line)
+ if (!m) continue // a header, an error message, a blank — skipped, never guessed at
+ const pid = Number(m[1])
+ const pgid = Number(m[2])
+ if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(pgid) || pgid <= 0) continue
+ rows.push({ pid, pgid, stat: m[3], args: m[4] })
+ }
+ return rows
+}
+
+/**
+ * Which process group owns the tty right now, from `stat`'s `+` flag.
+ *
+ * Null when no row is marked — an empty `ps`, a `ps` that errored, or a pane whose foreground group
+ * exited between the two round-trips. Null means "unknown", and the caller must not fall back to
+ * "the pane's own shell, probably": that guess is precisely the failure this module exists to end.
+ */
+export function foregroundPgid(stdout: string | null | undefined): number | null {
+ for (const row of parsePsRows(stdout)) {
+ if (row.stat.includes('+')) return row.pgid
+ }
+ return null
+}
+
+/**
+ * Every command line in one process group, in the order `ps` listed them — pid order on both
+ * platforms, which puts the group leader (the longest-lived member, e.g. the `sh -c` wrapper)
+ * first.
+ *
+ * Rows from any other pgid are ignored: other panes never share a tty, but a job that was
+ * backgrounded on this one does share the tty and must not be read as the owner.
+ *
+ * Garbage answers `[]` — never throws, never partially guesses.
+ */
+export function parseForegroundArgv(stdout: string | null | undefined, pgid: number): string[] {
+ if (!Number.isInteger(pgid) || pgid <= 0) return []
+ return parsePsRows(stdout)
+ .filter((row) => row.pgid === pgid)
+ .map((row) => row.args)
+}
diff --git a/src/shared/agents/pane-owner-predicate.ts b/src/shared/agents/pane-owner-predicate.ts
new file mode 100644
index 000000000..045f62f70
--- /dev/null
+++ b/src/shared/agents/pane-owner-predicate.ts
@@ -0,0 +1,37 @@
+// The shape of "who owns this pane", and the predicate that reads it.
+//
+// The TYPE lives here, in `src/shared`, because both directions need it: `src/core` PRODUCES it
+// (`core/agents/pane-owner.ts` parses it out of tmux + ps, `PtyManager.paneOwner` assembles it) and
+// the predicate below CONSUMES it. `src/shared` is the leaf every shell already imports, so this is
+// the one placement that does not make `src/shared` depend on `src/core`.
+
+/**
+ * Kernel truth about a tmux pane at one instant.
+ *
+ * - `panePid` — `#{pane_pid}`, the process tmux forked for the pane (usually the login shell).
+ * - `tty` — `#{pane_tty}`, the pane's pty. This is the handle the foreground process GROUP is
+ * read through, because the kernel tracks that per terminal, not per process.
+ * - `command` — `#{pane_current_command}`, tmux's own shallow answer. Kept because it is free and
+ * because it is what the old gate used; it is NOT what the predicate decides on.
+ * Measured on this host: a pane running `node …/claude --resume x` reports
+ * `command: 'node'`. A name-based gate cannot see the difference between that and
+ * any other node process.
+ * - `argv` — every member of the pane's FOREGROUND process group, full command line, in the
+ * order `ps` listed them (pid order, so the group leader is first).
+ */
+export interface PaneOwner {
+ panePid: number
+ tty: string
+ command: string
+ argv: readonly string[]
+}
+
+/**
+ * Three-valued on purpose — `unknown` is NOT a shade of `not-agent`.
+ *
+ * - `agent` — the kernel answered and the expected agent binary owns the foreground group.
+ * - `not-agent` — the kernel answered and the answer was no. Terminal; do not retry.
+ * - `unknown` — the probe failed (no tmux, dead pane, `ps` unavailable, deadline lapsed). The
+ * caller may retry. It must never be upgraded to `agent`.
+ */
+export type AgentPaneVerdict = 'agent' | 'not-agent' | 'unknown'