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(models): gate PID termination on agent identity + add SIGTERM grace (#226)

enes04e6bdf7e13b
diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.ts
index 492812110..565268497 100644
--- a/src/core/pty-manager.pane-owner.test.ts
+++ b/src/core/pty-manager.pane-owner.test.ts
@@ -228,3 +228,113 @@ describe('PtyManager.paneOwner', () => {
expect(await mgr.paneOwner(NODE)).toBeNull()
})
})
+
+// ── terminateForeground identity gate (#226 review) ──────────────────────────────────────────────
+// The kill must fire ONLY when the expected harness owns the foreground group. Refusing a shell is
+// not enough: a stale model-switch menu could otherwise SIGTERM whatever the user is now running in
+// the pane (vim, a build). These drive the real `terminateForeground` over the same fake exec.
+
+/** Manager with getSettings wired (binariesFor needs customAgents) and a spy on process.kill. */
+async function killManager(opts: { customAgents?: unknown[] } = {}) {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager() as unknown as {
+ tmuxPath: string | null
+ sessions: Map<string, unknown>
+ getSettings: () => unknown
+ terminateForeground(k: string, expected?: string): Promise<boolean>
+ }
+ mgr.tmuxPath = '/usr/bin/tmux'
+ mgr.sessions.set('sess-1', { persistKey: NODE, sshRemote: undefined })
+ mgr.getSettings = () => ({ customAgents: opts.customAgents ?? [] })
+ return mgr
+}
+
+describe('PtyManager.terminateForeground — identity gate', () => {
+ let killed: number[]
+ let killSpy: ReturnType<typeof vi.spyOn>
+ beforeEach(() => {
+ calls.length = 0
+ ssh.path = '/usr/bin/ssh'
+ vi.resetModules()
+ initPlatform(fakePlatform())
+ killed = []
+ killSpy = vi.spyOn(process, 'kill').mockImplementation(((pid: number, sig?: string | number) => {
+ // The grace poll probes with signal 0 and expects ESRCH once the group is gone; make the
+ // first probe say "alive" then throw so the loop terminates fast.
+ if (sig === 0) throw new Error('ESRCH')
+ killed.push(pid)
+ return true
+ }) as typeof process.kill)
+ })
+ afterEach(() => {
+ killSpy.mockRestore()
+ resetPlatformForTests()
+ })
+
+ const claudeForeground = (file: string, args: string[]): { stdout: string } => {
+ // paneOwner's PANE_OWNER_FMT read (MOST specific — it also contains '#{pane_pid}').
+ if (args.includes(PANE_OWNER_FMT)) return { stdout: `2485382|${TTY}|node|%3\n` }
+ // display-message #{pane_pid}|#{pane_current_command} (the kill path's pane read)
+ if (args.join(' ').includes('#{pane_pid}')) return { stdout: '2485382|node' }
+ // ps -o tpgid= -p <panePid> (the kill-target read)
+ if (args.includes('tpgid=')) return { stdout: '2503294' }
+ // ps -ww ... -t tty (paneOwner argv listing)
+ if (file === 'ps') return { stdout: PS_OUT }
+ return { stdout: '' }
+ }
+
+ it('KILLS the foreground group when the expected agent owns it', async () => {
+ script.answer = claudeForeground
+ const mgr = await killManager()
+ expect(await mgr.terminateForeground(NODE, 'claude')).toBe(true)
+ expect(killed).toEqual([-2503294]) // SIGTERM to the negative process group
+ })
+
+ it('REFUSES (no kill) when the pane belongs to a different program than expected', async () => {
+ // Foreground group is vim, not the agent.
+ script.answer = (file, args) => {
+ if (args.includes(PANE_OWNER_FMT)) return { stdout: `2485382|${TTY}|vim|%3\n` }
+ if (args.join(' ').includes('#{pane_pid}')) return { stdout: '2485382|vim' }
+ if (args.includes('tpgid=')) return { stdout: '2503294' }
+ if (file === 'ps')
+ return { stdout: '2485382 2485382 Ss -bash\n2503294 2503294 Sl+ vim /etc/hosts' }
+ return { stdout: '' }
+ }
+ const mgr = await killManager()
+ expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
+ expect(killed).toEqual([])
+ })
+
+ it('REFUSES when the owner is unknown (paneOwner answers null) — fail closed on a kill', async () => {
+ script.answer = (file, args) =>
+ args.includes(PANE_OWNER_FMT) ? { stdout: `2485382|${TTY}|node\n` } : { stdout: '' } // ps empty ⇒ null owner
+ const mgr = await killManager()
+ expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
+ expect(killed).toEqual([])
+ })
+
+ it('verifies a custom agent by its launchCmd binary instead of failing closed', async () => {
+ script.answer = (file, args) => {
+ if (args.includes(PANE_OWNER_FMT)) return { stdout: `2485382|${TTY}|aider|%3\n` }
+ if (args.join(' ').includes('#{pane_pid}')) return { stdout: '2485382|aider' }
+ if (args.includes('tpgid=')) return { stdout: '2503294' }
+ if (file === 'ps')
+ return { stdout: '2485382 2485382 Ss -bash\n2503294 2503294 Sl+ /usr/bin/aider --model gpt' }
+ return { stdout: '' }
+ }
+ const mgr = await killManager({
+ customAgents: [{ id: 'custom:x', label: 'Aider', launchCmd: 'aider' }]
+ })
+ expect(await mgr.terminateForeground(NODE, 'custom:x')).toBe(true)
+ expect(killed).toEqual([-2503294])
+ })
+
+ it('with no expected id, keeps the legacy shell-only guard (kills a non-shell foreground)', async () => {
+ script.answer = claudeForeground
+ const mgr = await killManager()
+ // No identity read happens (no PANE_OWNER_FMT call) — only the tpgid path.
+ expect(await mgr.terminateForeground(NODE)).toBe(true)
+ expect(killed).toEqual([-2503294])
+ expect(calls.some((c) => c.args.includes(PANE_OWNER_FMT))).toBe(false)
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 76e8140a9..76dedf9a9 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -44,7 +44,7 @@ import {
shouldRecordOwnership
} from './agents/pane-ownership'
import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parsePaneOwner } from './agents/pane-owner'
-import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
+import { binariesFor, isAgentPane, type PaneOwner } from '../shared/agents/pane-owner-predicate'
import { readSpawnResources, spawnResourceNote } from './spawn-resources'
import {
primePtyCeiling,
@@ -1412,8 +1412,8 @@ export class PtyManager {
)
platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())
platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))
- platform().handle(IPC.ptyTerminateForeground, (persistKey: string) =>
- this.terminateForeground(persistKey)
+ platform().handle(IPC.ptyTerminateForeground, (persistKey: string, expectedAgentId?: string) =>
+ this.terminateForeground(persistKey, expectedAgentId)
)
}
@@ -3112,10 +3112,28 @@ export class PtyManager {
* Terminate the foreground agent process group in a node's tmux pane without writing anything
* into the terminal. This is intentionally narrower than recycling the session: model switching
* first stops the harness by PID, then uses the existing recycle path to rebuild the shell with
- * current gateway environment. A shell-owned pane is always refused.
+ * current gateway environment.
+ *
+ * `expectedAgentId` is the IDENTITY GATE. Refusing a shell (the old contract) is not enough: a
+ * model switch fires from a possibly-stale menu, and hours after the agent exited the pane may
+ * belong to vim, a build, or an ssh the user started — none of which should be SIGTERM'd. When an
+ * expected id is given, the foreground group's full argv is read (`paneOwner`) and the kill
+ * happens ONLY when `isAgentPane` confirms the expected harness owns the group; `not-agent` and
+ * `unknown` both refuse (fail-closed — we are about to send a signal). Omitting the id preserves
+ * the legacy shell-only guard for any caller that has no agent to assert.
*/
- async terminateForeground(persistKey: string): Promise<boolean> {
+ async terminateForeground(persistKey: string, expectedAgentId?: string): Promise<boolean> {
if (typeof persistKey !== 'string' || !persistKey || persistKey.length > REF_MAX_LEN) return false
+ // Identity gate: prove the expected harness owns the foreground group before signalling it.
+ // `paneOwner` reads the full argv (local or over the project's ControlMaster) and is null on
+ // any uncertainty, which `isAgentPane` maps to `unknown` → refuse.
+ if (expectedAgentId) {
+ const owner = await this.paneOwner(persistKey)
+ // Pass the custom-agent list so a `custom:<uuid>` harness is verifiable by its launchCmd
+ // binary instead of collapsing to `unknown` (which would fail-closed on every model switch).
+ const binaries = binariesFor(expectedAgentId, this.getSettings().customAgents)
+ if (isAgentPane(owner, expectedAgentId, binaries) !== 'agent') return false
+ }
const target = sessionName(persistKey)
const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
try {
@@ -3150,6 +3168,18 @@ export class PtyManager {
const processGroup = foregroundProcessGroup(pane, processTable.stdout)
if (!processGroup) return false
process.kill(-processGroup, 'SIGTERM')
+ // Grace: give the harness a window to flush session state (transcript, --resume id) before
+ // the caller recycles the session (tmux kill-session). Poll the group with signal 0 —
+ // ESRCH means it is gone — up to ~1.5s, then return regardless (the recycle is a kill either
+ // way; this only improves resume fidelity for an agent that exits promptly on SIGTERM).
+ for (let i = 0; i < 30; i++) {
+ try {
+ process.kill(-processGroup, 0)
+ } catch {
+ break // ESRCH: the group has exited
+ }
+ await new Promise((r) => setTimeout(r, 50))
+ }
return true
} catch {
return false
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index 43711ff66..ed8749327 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -479,9 +479,18 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
await create(80, 24)
paneProcessReply = '33293|codex\n'
processGroupReply = '33319\n'
- const signal = vi.spyOn(process, 'kill').mockImplementation(() => true)
+ // sig 0 is the post-SIGTERM grace probe: ESRCH means the group has already exited, so the
+ // bounded wait breaks on its first iteration (no fake-timer setTimeout is reached).
+ const signal = vi
+ .spyOn(process, 'kill')
+ .mockImplementation(((_pid: number, sig?: string | number) => {
+ if (sig === 0) throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' })
+ return true
+ }) as typeof process.kill)
execCalls.length = 0
+ // No expectedAgentId here — the legacy shell-only guard path (an SSH/codex node's own
+ // model switch passes its id; this asserts the base kill mechanism stays intact).
await expect(fake.handlers[IPC.ptyTerminateForeground]('solo-1')).resolves.toBe(true)
expect(signal).toHaveBeenCalledWith(-33319, 'SIGTERM')
diff --git a/src/preload/index.test.ts b/src/preload/index.test.ts
index c368786b4..53dc9247e 100644
--- a/src/preload/index.test.ts
+++ b/src/preload/index.test.ts
@@ -37,8 +37,8 @@ const api = h.exposed.nodeTerminal as NodeTerminalApi
describe('preload sshProject passphrase wiring', () => {
it('routes foreground process termination through request IPC', async () => {
- await api.pty.terminateForeground('node-1')
- expect(h.invoke).toHaveBeenCalledWith(IPC.ptyTerminateForeground, 'node-1')
+ await api.pty.terminateForeground('node-1', 'claude')
+ expect(h.invoke).toHaveBeenCalledWith(IPC.ptyTerminateForeground, 'node-1', 'claude')
})
it('exposes GitHub issue data and host-control namespaces on their exact channels', async () => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 602ddfdae..f4072ed00 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -74,8 +74,8 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),
tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),
paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),
- terminateForeground: (persistKey) =>
- ipcRenderer.invoke(IPC.ptyTerminateForeground, persistKey),
+ terminateForeground: (persistKey, expectedAgentId) =>
+ ipcRenderer.invoke(IPC.ptyTerminateForeground, persistKey, expectedAgentId),
readSessionName: (sessionId, accountId, agentId) =>
ipcRenderer.invoke(IPC.ptyReadSessionName, sessionId, accountId, agentId),
onData: (sessionId, listener) => {
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 177b77828..e9c6d11fa 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -237,8 +237,8 @@ export function buildRealApi(
// shell yet" and gives up on its own deadline.
paneCommand: (persistKey) =>
client.request(IPC.ptyPaneCommand, persistKey).catch(() => null) as Promise<string | null>,
- terminateForeground: (persistKey) =>
- client.request(IPC.ptyTerminateForeground, persistKey).catch(() => false) as Promise<boolean>,
+ terminateForeground: (persistKey, expectedAgentId) =>
+ client.request(IPC.ptyTerminateForeground, persistKey, expectedAgentId).catch(() => false) as Promise<boolean>,
// No server handler — the session-name poll degrades to no adopted name. A PRE-EXISTING gap,
// and not any one agent's: `IPC.ptyReadSessionName` has never been registered server-side, so
// claude's, grok's and gemini's read legs are equally stubbed here (the write leg works on both
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 03af93c47..ce8c291be 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -2906,7 +2906,9 @@ export function TerminalNode({
// core/settings store, so a local gateway must never be pushed into one.
if (targetModel) {
if (!selectedModel || session.source === 'relay') return 'not-eligible'
- if (!(await api.pty.terminateForeground(id))) return 'not-eligible'
+ // Identity-gated: core SIGTERMs the foreground group ONLY if `target`'s harness still
+ // owns it, so a stale model-switch menu can never kill vim or a build in this pane.
+ if (!(await api.pty.terminateForeground(id, target))) return 'not-eligible'
transport.recycle(id)
updateNodeData(id, (node) => ({
agentId: target,
diff --git a/src/shared/types.ts b/src/shared/types.ts
index c29d63495..4ab72f87c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -654,9 +654,11 @@ export interface PtyApi {
* node persistKey. null when it is unknown — no session, no tmux, or the query failed — which
* callers must read as "not observed", never as evidence of a particular command. */
paneCommand(persistKey: string): Promise<string | null>
- /** Terminate the foreground non-shell process group in a node's pane. Returns false when the
- * pane/process cannot be safely identified; it never kills the pane's login shell. */
- terminateForeground(persistKey: string): Promise<boolean>
+ /** Terminate the foreground process group in a node's pane. Returns false when the pane/process
+ * cannot be safely identified; it never kills the pane's login shell. When `expectedAgentId` is
+ * given, the kill happens only if that harness actually owns the foreground group (argv-verified)
+ * — so a stale menu can never SIGTERM vim or a build the user started in the pane. */
+ terminateForeground(persistKey: string, expectedAgentId?: string): Promise<boolean>
/** The agent session's display name (`/rename` name, else auto name) read from the agent's own
* session store, resolved strictly by sessionId; null if unknown. Keeps a node title in sync with
* the `/resume` name (e.g. after resume) without cross-contaminating same-folder sessions.