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(windows): session-host terminateOwnerV1 and writeDetachedV1 verbs

reviewb5602848b3f4
diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.ts
index 821497f6a..a91fa78f2 100644
--- a/src/core/session-host-backend.ts
+++ b/src/core/session-host-backend.ts
@@ -34,6 +34,18 @@ export async function sessionHostMessageEnvelope(
return getClient().messageEnvelope(name, envelope, expected)
}
+/** End the proven agent tree on a session-host pane (never the shell). See `terminateOwner`. */
+export async function sessionHostTerminateOwner(
+ name: string, expected: PaneOwner
+): Promise<boolean | 'unsupported'> {
+ return getClient().terminateOwner(name, expected)
+}
+
+/** Raw verbatim write into a released (unattached) session. False = not delivered or unknown. */
+export async function sessionHostWriteDetached(name: string, data: string): Promise<boolean> {
+ return getClient().writeDetached(name, data)
+}
+
let client: SessionHostClient | null = null
function getClient(): SessionHostClient {
diff --git a/src/core/session-host-client.test.ts b/src/core/session-host-client.test.ts
index 71500c59e..7de6e4a06 100644
--- a/src/core/session-host-client.test.ts
+++ b/src/core/session-host-client.test.ts
@@ -241,6 +241,63 @@ describe('SessionHostClient handshake transition', () => {
expect(commands).toEqual(['hello', 'sendKeysV2'])
})
+ const WIN_OWNER = {
+ panePid: 42, tty: 'win32-console:42', paneId: 'win32:g:b', command: 'node', argv: ['claude'],
+ pids: [43], processBirths: ['b43']
+ }
+
+ it("maps an older host's unknown terminateOwnerV1 to 'unsupported' and anything else to false", async () => {
+ const { userDataDir, paths } = createUserData('terminate-owner-refusals')
+ const commands: string[] = []
+ const answers = ['unknown command', 'no such session']
+ await serve(paths.endpoint, (request, socket) => {
+ commands.push(request.cmd)
+ if (request.cmd === 'hello') socket.write(acceptedHello(request.id))
+ else socket.write(encodeFrame({ id: request.id, ok: false, error: answers.shift() ?? 'x' }))
+ })
+ const client = new SessionHostClient({ userDataDir, repoRoot: userDataDir })
+ expect(await within(client.terminateOwner('nt-a', WIN_OWNER))).toBe('unsupported')
+ expect(await within(client.terminateOwner('nt-a', WIN_OWNER))).toBe(false)
+ // Exactly one request per call: no retry, no fallback to a write or a kill.
+ expect(commands).toEqual(['hello', 'terminateOwnerV1', 'terminateOwnerV1'])
+ })
+
+ it('returns terminated only when the host says so, carrying the expected owner verbatim', async () => {
+ const { userDataDir, paths } = createUserData('terminate-owner-ok')
+ const seen: unknown[] = []
+ const results = [{ terminated: true }, { terminated: false }, undefined]
+ await serve(paths.endpoint, (request, socket) => {
+ if (request.cmd === 'hello') return void socket.write(acceptedHello(request.id))
+ seen.push(request)
+ socket.write(encodeFrame({ id: request.id, ok: true, result: results.shift() }))
+ })
+ const client = new SessionHostClient({ userDataDir, repoRoot: userDataDir })
+ expect(await within(client.terminateOwner('nt-a', WIN_OWNER))).toBe(true)
+ expect(await within(client.terminateOwner('nt-a', WIN_OWNER))).toBe(false)
+ expect(await within(client.terminateOwner('nt-a', WIN_OWNER))).toBe(false)
+ expect(seen[0]).toMatchObject({ cmd: 'terminateOwnerV1', name: 'nt-a', expected: WIN_OWNER })
+ })
+
+ it('writeDetached sends the raw bytes once and never retries or falls back on a refusal', async () => {
+ const { userDataDir, paths } = createUserData('write-detached')
+ const seen: Array<{ cmd: string; data?: string }> = []
+ const answers = [true, false]
+ await serve(paths.endpoint, (request, socket) => {
+ if (request.cmd === 'hello') return void socket.write(acceptedHello(request.id))
+ seen.push(request as { cmd: string; data?: string })
+ socket.write(answers.shift()
+ ? encodeFrame({ id: request.id, ok: true })
+ : encodeFrame({ id: request.id, ok: false, error: 'unknown command' }))
+ })
+ const client = new SessionHostClient({ userDataDir, repoRoot: userDataDir })
+ expect(await within(client.writeDetached('nt-a', '\x1b[A'))).toBe(true)
+ expect(await within(client.writeDetached('nt-a', 'y'))).toBe(false)
+ expect(seen).toEqual([
+ { id: expect.any(Number), cmd: 'writeDetachedV1', name: 'nt-a', data: '\x1b[A' },
+ { id: expect.any(Number), cmd: 'writeDetachedV1', name: 'nt-a', data: 'y' }
+ ])
+ })
+
it('hands the socket to the production listener before the first attach response and data', async () => {
const { userDataDir, paths, token } = createUserData('test-token-kept-off-argv')
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index 451882439..39a530cbc 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -1645,6 +1645,34 @@ export class SessionHostClient {
} catch { return false }
}
+ /** `terminateOwnerV1`. `'unsupported'` = the live host predates the verb (it answered `unknown
+ * command`) — distinct from `false`, so the UI can say "restart the app" instead of "busy". Any
+ * other failure, a lost reply included, is `false`: the caller then refuses to recycle. Never
+ * retried — a second kill aimed at a re-proven owner is the host's job, not a resend's. */
+ async terminateOwner(name: string, expected: PaneOwner): Promise<boolean | 'unsupported'> {
+ try {
+ const result = await this.request<{ terminated?: unknown } | undefined>({ cmd: 'terminateOwnerV1', name, expected })
+ return result?.terminated === true
+ } catch (error) {
+ return error instanceof SessionHostRequestRejectedError && error.message === 'unknown command'
+ ? 'unsupported'
+ : false
+ }
+ }
+
+ /** `writeDetachedV1`: raw bytes into a session this process holds no attachment on. True only on
+ * the host's acknowledgement. NEVER retried and never re-routed through `sendKeys`: a lost reply
+ * may still have been typed, and an older host's refusal never reached the pty at all — either
+ * way a second attempt risks typing the input twice or in a different shape. */
+ async writeDetached(name: string, data: string): Promise<boolean> {
+ try {
+ await this.request<unknown>({ cmd: 'writeDetachedV1', name, data })
+ return true
+ } catch {
+ return false
+ }
+ }
+
async capture(name: string, full: boolean): Promise<string> {
const result = await this.request<CaptureResult>({ cmd: 'capture', name, full })
return result.text
diff --git a/src/session-host/agent-ops-host.test.ts b/src/session-host/agent-ops-host.test.ts
new file mode 100644
index 000000000..2ff15dfa9
--- /dev/null
+++ b/src/session-host/agent-ops-host.test.ts
@@ -0,0 +1,185 @@
+// Wiring test for the additive agent-operation verbs: drives the REAL bundled host over its real
+// socket protocol against a fake node-pty that logs its writes (the host is its own process, so a
+// spy cannot be shared). `terminate-owner.test.ts` pins the kill's refusal matrix; this pins that
+// the host dispatches both verbs, and that `writeDetachedV1` needs no attachment.
+import { afterEach, describe, expect, it } from 'vitest'
+import { spawn, type ChildProcess } from 'child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import net, { type Socket } from 'net'
+import os from 'os'
+import path from 'path'
+import { build, type Plugin } from 'esbuild'
+import { LineFramer, encodeFrame, type SessionHostFrame, type SessionHostResponse } from './protocol'
+import { sessionHostPaths, type SessionHostState } from './paths'
+
+function fakePtyPlugin(): Plugin {
+ return {
+ name: 'session-host-agent-ops-fake-pty',
+ setup(bundle) {
+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({ path: 'node-pty', namespace: 'agent-ops' }))
+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'agent-ops' }, () => ({
+ loader: 'js',
+ contents: `
+ const fs = require('fs')
+ export function spawn() {
+ let onExit
+ return {
+ pid: 4242,
+ onData() {},
+ onExit(cb) { onExit = cb },
+ write(data) { fs.appendFileSync(process.env.NT_TEST_WRITE_LOG, JSON.stringify(data) + '\\n') },
+ resize() {}, pause() {}, resume() {},
+ kill() { setTimeout(() => onExit?.({ exitCode: 0 }), 20) }
+ }
+ }
+ `
+ }))
+ }
+ }
+}
+
+const cleanup: Array<() => Promise<void> | void> = []
+afterEach(async () => {
+ for (const step of cleanup.splice(0).reverse()) await step()
+})
+
+async function bootHost(): Promise<{ connect(): Promise<Conn>; writes(): string[] }> {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-agent-ops-'))
+ cleanup.push(() => rmSync(fixtureDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }))
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanup.push(() => rmSync(paths.endpoint, { force: true }))
+ const writeLog = path.join(fixtureDir, 'writes.log')
+ writeFileSync(writeLog, '')
+ const bundlePath = path.join(fixtureDir, 'host.cjs')
+ await build({
+ absWorkingDir: process.cwd(),
+ entryPoints: ['src/session-host/host.ts'],
+ outfile: bundlePath,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ plugins: [fakePtyPlugin()],
+ logLevel: 'silent'
+ })
+ const child: ChildProcess = spawn(process.execPath, [bundlePath, dataDir], {
+ stdio: 'ignore',
+ windowsHide: true,
+ env: { ...process.env, NT_TEST_WRITE_LOG: writeLog }
+ })
+ cleanup.push(async () => {
+ child.kill()
+ if (child.exitCode === null && child.signalCode === null) {
+ await new Promise((resolve) => child.once('exit', resolve))
+ }
+ })
+ let identity: { state: SessionHostState; token: string } | null = null
+ for (let attempt = 0; attempt < 200 && !identity; attempt++) {
+ try {
+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState
+ const token = readFileSync(paths.tokenPath, 'utf8').trim()
+ if (state.endpoint && token) identity = { state, token }
+ } catch { /* published asynchronously */ }
+ if (!identity) await new Promise((resolve) => setTimeout(resolve, 20))
+ }
+ if (!identity) throw new Error('session host did not publish its identity')
+ const { state, token } = identity
+ return {
+ connect: async () => {
+ const conn = await connect(state.endpoint)
+ cleanup.push(() => void conn.socket.destroy())
+ await expect(conn.call({ cmd: 'hello', token })).resolves.toMatchObject({ ok: true })
+ return conn
+ },
+ writes: () => readFileSync(writeLog, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as string)
+ }
+}
+
+interface Conn {
+ socket: Socket
+ call(body: Record<string, unknown>): Promise<SessionHostResponse>
+}
+
+function connect(endpoint: string): Promise<Conn> {
+ return new Promise((resolve, reject) => {
+ const socket = net.connect(endpoint)
+ const framer = new LineFramer()
+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()
+ let nextId = 1
+ socket.on('data', (chunk: Buffer) => {
+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {
+ if ('id' in frame) waiters.get(frame.id)?.(frame)
+ }
+ })
+ socket.once('error', reject)
+ socket.once('connect', () =>
+ resolve({
+ socket,
+ call: (body) => {
+ const id = nextId++
+ return new Promise<SessionHostResponse>((res, rej) => {
+ const timer = setTimeout(() => rej(new Error(`no response to ${String(body.cmd)}`)), 6_000)
+ waiters.set(id, (frame) => {
+ clearTimeout(timer)
+ res(frame)
+ })
+ socket.write(encodeFrame({ id, ...body }))
+ })
+ }
+ })
+ )
+ })
+}
+
+const SPAWN = { cwd: '.', shell: 'fake-shell', args: [], env: {}, cols: 80, rows: 24 }
+const OWNER = {
+ panePid: 4242, tty: 'win32-console:4242', paneId: 'win32:g:b', command: 'node', argv: ['claude'],
+ pids: [4243], processBirths: ['b']
+}
+
+describe('session-host agent-operation verbs', () => {
+ it('writeDetachedV1 types verbatim into a session this connection never attached', async () => {
+ const host = await bootHost()
+ const owner = await host.connect()
+ await expect(owner.call({ cmd: 'attach', name: 'nt-a', spawn: SPAWN, scrollback: 100 }))
+ .resolves.toMatchObject({ ok: true })
+ const stranger = await host.connect()
+ // The ordinary `write` still demands an attachment — the new verb is the only way around it.
+ await expect(stranger.call({ cmd: 'write', name: 'nt-a', data: 'no' }))
+ .resolves.toMatchObject({ ok: false, error: 'not attached to session' })
+ await expect(stranger.call({ cmd: 'writeDetachedV1', name: 'nt-a', data: '\x1b[Aline\r' }))
+ .resolves.toMatchObject({ ok: true })
+ await expect(stranger.call({ cmd: 'writeDetachedV1', name: 'nt-missing', data: 'x' }))
+ .resolves.toMatchObject({ ok: false, error: 'no such session' })
+ await expect(stranger.call({ cmd: 'writeDetachedV1', name: 'nt-a', data: '' }))
+ .resolves.toMatchObject({ ok: false })
+ await expect(stranger.call({ cmd: 'noSuchVerbV9', name: 'nt-a' }))
+ .resolves.toMatchObject({ ok: false, error: 'unknown command' })
+ expect(host.writes()).toEqual(['\x1b[Aline\r'])
+ }, 30_000)
+
+ it('writeDetachedV1 refuses an exited session', async () => {
+ const host = await bootHost()
+ const owner = await host.connect()
+ await owner.call({ cmd: 'attach', name: 'nt-b', spawn: SPAWN, scrollback: 100 })
+ await expect(owner.call({ cmd: 'killSession', name: 'nt-b', operationId: 'op-1', reserveReplacement: false }))
+ .resolves.toMatchObject({ ok: true })
+ await expect(owner.call({ cmd: 'writeDetachedV1', name: 'nt-b', data: 'x' }))
+ .resolves.toMatchObject({ ok: false, error: 'no such session' })
+ expect(host.writes()).toEqual([])
+ }, 30_000)
+
+ it('terminateOwnerV1 answers terminated:false when the owner cannot be proven (no Windows console here)', async () => {
+ const host = await bootHost()
+ const conn = await host.connect()
+ await conn.call({ cmd: 'attach', name: 'nt-c', spawn: SPAWN, scrollback: 100 })
+ await expect(conn.call({ cmd: 'terminateOwnerV1', name: 'nt-c', expected: OWNER }))
+ .resolves.toMatchObject({ ok: true, result: { terminated: false } })
+ await expect(conn.call({ cmd: 'terminateOwnerV1', name: 'nt-missing', expected: OWNER }))
+ .resolves.toMatchObject({ ok: true, result: { terminated: false } })
+ // The session survived and nothing was typed into it.
+ await expect(conn.call({ cmd: 'hasSession', name: 'nt-c' })).resolves.toMatchObject({ result: { exists: true } })
+ expect(host.writes()).toEqual([])
+ }, 30_000)
+})
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index a06d1a9d0..e2eb25f6d 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -29,6 +29,7 @@ import {
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
+ type TerminateOwnerResult,
type KillSessionResult,
type ListSessionsResult,
type ShutdownResult
@@ -37,6 +38,8 @@ import { HostSession } from './session'
import { sendTextWhenSettled } from '../core/settled-text'
import { paneCommand as readPaneCommand } from './process-tree'
import { terminateWindowsProcessTree } from './windows-process-tree'
+import { terminatePaneOwner } from './terminate-owner'
+import { readWindowsConsoleOwner } from './windows-pane-owner'
import { publishSessionHostState } from './state-file'
import {
EMPTY_LOCK_STALE_MS,
@@ -993,6 +996,21 @@ async function main(): Promise<void> {
ok: true,
result: await hostMessagePane(() => sessions.get(req.name)).send(req.envelope, req.expected)
}
+ case 'terminateOwnerV1': {
+ const terminated = await terminatePaneOwner(() => sessions.get(req.name), req.expected, {
+ probe: readWindowsConsoleOwner,
+ terminate: (pid) => terminateWindowsProcessTree(pid)
+ })
+ return { ok: true, result: { terminated } satisfies TerminateOwnerResult }
+ }
+ case 'writeDetachedV1': {
+ // No subscriber check, exactly like sendKeys: the caller holds no attachment on purpose.
+ const s = sessions.get(req.name)
+ if (!s || s.exited) return { ok: false, error: 'no such session' }
+ if (typeof req.data !== 'string' || !req.data) return { ok: false, error: 'nothing to write' }
+ s.proc.write(req.data)
+ return { ok: true }
+ }
case 'capture': {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: true, result: { text: '' } satisfies CaptureResult }
diff --git a/src/session-host/protocol.test.ts b/src/session-host/protocol.test.ts
index 472559950..d418d38b7 100644
--- a/src/session-host/protocol.test.ts
+++ b/src/session-host/protocol.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest'
-import { LineFramer, FrameTooLargeError, MAX_FRAME_BYTES, encodeFrame } from './protocol'
+import {
+ LineFramer,
+ FrameTooLargeError,
+ MAX_FRAME_BYTES,
+ SESSION_HOST_FEATURES,
+ encodeFrame,
+ type SessionHostRequest
+} from './protocol'
describe('LineFramer', () => {
it('reassembles a frame split across chunks and drops a corrupt line without wedging', () => {
@@ -31,3 +38,27 @@ describe('LineFramer', () => {
expect(framer.push<any>('{"ok":true}\n')).toEqual([{ ok: true }])
})
})
+
+describe('agent-operation verbs', () => {
+ it('round-trip raw control bytes and the expected owner unchanged through the framer', () => {
+ const requests: SessionHostRequest[] = [
+ { id: 7, cmd: 'writeDetachedV1', name: 'nt-a', data: '\x1b[A\r\n\u0003' },
+ {
+ id: 8,
+ cmd: 'terminateOwnerV1',
+ name: 'nt-a',
+ expected: {
+ panePid: 1, tty: 'win32-console:1', paneId: 'win32:g:b', command: 'node',
+ argv: ['claude'], pids: [2], processBirths: ['b']
+ }
+ }
+ ]
+ const framer = new LineFramer()
+ expect(framer.push(requests.map(encodeFrame).join(''))).toEqual(requests)
+ })
+
+ it('are negotiated by command name, not by a hello feature (an older host answers unknown command)', () => {
+ // Features gate PUSH frames an older client would misread; these are plain requests.
+ expect(SESSION_HOST_FEATURES).toEqual(['geometry', 'shutdown'])
+ })
+})
diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.ts
index 5bdae9e02..9eaa99cff 100644
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@ -98,6 +98,14 @@ export type SessionHostRequest =
| { id: number; cmd: 'messageOwnerV1'; name: string }
| { id: number; cmd: 'messagePasteReadyV1'; name: string }
| { id: number; cmd: 'messageEnvelopeV1'; name: string; envelope: string; expected: PaneOwner }
+ /** End the proven agent process tree (`expected`, from `messageOwnerV1`) without touching the
+ * console root. Result: `TerminateOwnerResult`. Additive like the messaging extension: an older
+ * live host answers `unknown command`, which the client reports as unsupported. */
+ | { id: number; cmd: 'terminateOwnerV1'; name: string; expected: PaneOwner }
+ /** Raw, verbatim keystroke bytes into a session this connection need NOT be attached to — the
+ * `tmux send-keys -H` of a released node. No framing, no sanitizing, no Enter. An older host
+ * answers `unknown command`; the client then fails closed and never falls back to sendKeys. */
+ | { id: number; cmd: 'writeDetachedV1'; name: string; data: string }
| { id: number; cmd: 'capture'; name: string; full: boolean }
| {
id: number
@@ -238,6 +246,9 @@ export interface ExecuteLaunchResult {
export interface PaneCommandResult {
command: string | null
}
+export interface TerminateOwnerResult {
+ terminated: boolean
+}
export interface CaptureResult {
text: string
}
diff --git a/src/session-host/terminate-owner.test.ts b/src/session-host/terminate-owner.test.ts
new file mode 100644
index 000000000..c357a3133
--- /dev/null
+++ b/src/session-host/terminate-owner.test.ts
@@ -0,0 +1,116 @@
+import { spawn } from 'child_process'
+import { describe, expect, it, vi } from 'vitest'
+import { terminateWindowsProcessTree } from './windows-process-tree'
+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
+import { terminatePaneOwner, type TerminateOwnerSession } from './terminate-owner'
+
+const OWNER: PaneOwner = {
+ panePid: 700,
+ tty: 'win32-console:700',
+ paneId: 'win32:gen-1:2026-10-01T00:00:00Z',
+ command: 'node',
+ argv: ['claude'],
+ pids: [701],
+ processBirths: ['2026-10-01T00:00:05Z']
+}
+
+function harness(current: PaneOwner | null, session: TerminateOwnerSession | undefined = {
+ generation: 'gen-1', exited: false, proc: { pid: 700 }
+}) {
+ const probe = vi.fn(async () => current)
+ const terminate = vi.fn(async (_pid: number) => {})
+ return { session, probe, terminate, lookup: () => session }
+}
+
+describe('terminatePaneOwner', () => {
+ it('kills exactly the proven pid, after re-probing under the host generation', async () => {
+ const h = harness(OWNER)
+ expect(await terminatePaneOwner(h.lookup, OWNER, h)).toBe(true)
+ expect(h.probe).toHaveBeenCalledWith(700, 'gen-1')
+ expect(h.terminate).toHaveBeenCalledWith(701)
+ })
+
+ it.each([
+ ['birth time (PID reuse)', { processBirths: ['2026-10-01T09:00:00Z'] }],
+ ['pane generation', { paneId: 'win32:gen-2:2026-10-01T00:00:00Z' }],
+ ['executable', { argv: ['codex'] }],
+ ['an ambiguous owner (two pids)', { pids: [701, 702], processBirths: ['a', 'b'] }]
+ ])('refuses an owner that differs by %s', async (_label, diff) => {
+ const h = harness({ ...OWNER, ...diff } as PaneOwner)
+ expect(await terminatePaneOwner(h.lookup, OWNER, h)).toBe(false)
+ expect(h.terminate).not.toHaveBeenCalled()
+ })
+
+ it('never kills the console root', async () => {
+ const root = { ...OWNER, pids: [700] }
+ const h = harness(root)
+ expect(await terminatePaneOwner(h.lookup, root, h)).toBe(false)
+ expect(h.terminate).not.toHaveBeenCalled()
+ })
+
+ it('never kills a nested shell that owns the pane', async () => {
+ const shell = { ...OWNER, command: 'pwsh', argv: ['pwsh'] }
+ const h = harness(shell)
+ expect(await terminatePaneOwner(h.lookup, shell, h)).toBe(false)
+ expect(h.terminate).not.toHaveBeenCalled()
+ })
+
+ it('refuses with no expected owner, no session, an exited one, or an unreadable owner', async () => {
+ const h = harness(OWNER)
+ expect(await terminatePaneOwner(h.lookup, undefined, h)).toBe(false)
+ expect(await terminatePaneOwner(() => undefined, OWNER, h)).toBe(false)
+ const exited = harness(OWNER, { generation: 'gen-1', exited: true, proc: { pid: 700 } })
+ expect(await terminatePaneOwner(exited.lookup, OWNER, exited)).toBe(false)
+ const unknown = harness(null)
+ expect(await terminatePaneOwner(unknown.lookup, OWNER, unknown)).toBe(false)
+ expect(h.terminate).not.toHaveBeenCalled()
+ })
+
+ it('refuses when the session was replaced while the probe ran', async () => {
+ const h = harness(OWNER)
+ let calls = 0
+ const replaced = { generation: 'gen-2', exited: false, proc: { pid: 900 } }
+ const lookup = () => (calls++ === 0 ? h.session : replaced)
+ expect(await terminatePaneOwner(lookup, OWNER, h)).toBe(false)
+ expect(h.terminate).not.toHaveBeenCalled()
+ })
+
+ it('reports true only after terminate resolves, and false when it rejects', async () => {
+ let resolveKill: () => void = () => {}
+ const h = harness(OWNER)
+ h.terminate.mockImplementation(() => new Promise<void>((r) => { resolveKill = r }))
+ let settled = false
+ const pending = terminatePaneOwner(h.lookup, OWNER, h).then((v) => { settled = true; return v })
+ await new Promise((r) => setTimeout(r, 5))
+ expect(settled).toBe(false)
+ resolveKill()
+ expect(await pending).toBe(true)
+
+ const failing = harness(OWNER)
+ failing.terminate.mockRejectedValue(new Error('still alive after 8000ms'))
+ expect(await terminatePaneOwner(failing.lookup, OWNER, failing)).toBe(false)
+ })
+})
+
+describe('terminatePaneOwner against real taskkill', () => {
+ // Windows only: the production `terminate` is `taskkill /T /F`, which exists nowhere else. Proves
+ // the proven child dies while the pane root (this test's stand-in shell) keeps running.
+ it.skipIf(process.platform !== 'win32')('ends the owner tree and leaves the root alive', async () => {
+ const root = spawn('ping.exe', ['-n', '30', '127.0.0.1'], { windowsHide: true, stdio: 'ignore' })
+ const agent = spawn('ping.exe', ['-n', '30', '127.0.0.1'], { windowsHide: true, stdio: 'ignore' })
+ try {
+ const owner = { ...OWNER, panePid: root.pid!, tty: `win32-console:${root.pid}`, pids: [agent.pid!] }
+ const session = { generation: 'gen-1', exited: false, proc: { pid: root.pid! } }
+ const agentExit = new Promise((resolve) => agent.once('exit', resolve))
+ expect(await terminatePaneOwner(() => session, owner, {
+ probe: async () => owner,
+ terminate: (pid) => terminateWindowsProcessTree(pid)
+ })).toBe(true)
+ await agentExit
+ expect(root.exitCode).toBeNull()
+ } finally {
+ root.kill()
+ agent.kill()
+ }
+ }, 20_000)
+})
diff --git a/src/session-host/terminate-owner.ts b/src/session-host/terminate-owner.ts
new file mode 100644
index 000000000..03e13d6a5
--- /dev/null
+++ b/src/session-host/terminate-owner.ts
@@ -0,0 +1,55 @@
+// `terminateOwnerV1` (the session-host leg of `PtyManager.terminateForeground`): end the proven
+// agent process tree on a pane WITHOUT touching the pane's console root (the shell). A model switch
+// stops the harness this way and then recycles the session, so the shell must survive the kill.
+//
+// Pure apart from its two injected effects, so the whole refusal matrix runs on Linux. The host
+// wires `probe` to `readWindowsConsoleOwner` and `terminate` to `terminateWindowsProcessTree`.
+import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
+import { isConsoleShellBinary, sameNativeProcess } from './windows-pane-owner'
+
+export interface TerminateOwnerSession {
+ generation: string
+ exited: boolean
+ proc: { pid: number }
+}
+
+export interface TerminateOwnerDeps {
+ /** Re-reads the pane owner from the OS (`readWindowsConsoleOwner`). */
+ probe: (rootPid: number, generation: string) => Promise<PaneOwner | null>
+ /** Ends a process TREE rooted at `pid`; resolves only once the root is observed gone. */
+ terminate: (pid: number) => Promise<void>
+}
+
+/**
+ * True only when the exact process `expected` names still owns the pane AND its tree was ended.
+ *
+ * Refusals, every one of them a `false` with nothing signalled:
+ * - no session, an exited one, or one replaced while the probe ran (`lookup()` is re-asked);
+ * - `expected` missing, or not the SAME native process the probe sees now (`sameNativeProcess`:
+ * pane generation, root pid, single pid, OS birth time and executable — a reused PID fails);
+ * - the owner is the console root itself, or a shell: killing either would end the session the
+ * caller is about to recycle, and "the shell owns the pane" means there is no agent to stop.
+ * A `terminate` that rejects is `false` too — `terminateWindowsProcessTree` never reports a partial
+ * kill as success, and neither does this.
+ */
+export async function terminatePaneOwner(
+ lookup: () => TerminateOwnerSession | undefined,
+ expected: PaneOwner | undefined,
+ deps: TerminateOwnerDeps
+): Promise<boolean> {
+ const s = lookup()
+ if (!s || s.exited || !expected) return false
+ const current = await deps.probe(s.proc.pid, s.generation)
+ if (s.exited || lookup() !== s) return false
+ if (!current || !sameNativeProcess(expected, current)) return false
+ const pid = current.pids?.[0]
+ if (pid === undefined || !Number.isSafeInteger(pid) || pid <= 0) return false
+ if (pid === s.proc.pid || current.panePid !== s.proc.pid) return false
+ if (isConsoleShellBinary(current.command)) return false
+ try {
+ await deps.terminate(pid)
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/src/session-host/windows-pane-owner.ts b/src/session-host/windows-pane-owner.ts
index 8652fa76c..4c180843c 100644
--- a/src/session-host/windows-pane-owner.ts
+++ b/src/session-host/windows-pane-owner.ts
@@ -37,6 +37,10 @@ export interface WindowsConsoleSnapshot {
}
const SHELLS = new Set(['pwsh', 'powershell', 'cmd', 'bash', 'sh'])
+/** Is `command` (a `PaneOwner.command`, i.e. the lower-cased executable name) a console shell? */
+export function isConsoleShellBinary(command: string): boolean {
+ return SHELLS.has(command.toLowerCase().replace(/\.exe$/, ''))
+}
/**
* Interpreters whose identity is the script they run, not their own executable. An npm-installed
* agent CLI on Windows is `cmd` -> `node <package>\bin\<cli>.js` (Codex measured 2026-09-14, with