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(windows): stop agents and write released sessions on the session host

review26df4664844b
diff --git a/CLAUDE.md b/CLAUDE.md
index 640506558..0da840d68 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2234,7 +2234,9 @@ else, and its context links must keep classifying across restarts).
group (never types `/exit`) and RECYCLES the tmux session before cold-resume: an existing shell may
predate the gateway setting, and tmux env changes do not retroactively change that shell's
environment. Recreating it guarantees the current URL/key applies without typing a secret into
- the pane. Ordinary Restart stays in-place. Custom-agent env is still merged last and may override
+ the pane. On Windows (session host / direct ConPTY — no process groups) the kill is `taskkill /T
+ /F` on the re-proven agent pid only, never the console root, and requires the agent-identity gate
+ (`session-host/terminate-owner.ts`; an older live host answers `'unsupported'`). Ordinary Restart stays in-place. Custom-agent env is still merged last and may override
the shared mapping. Desktop and Server Edition use the same core handler; relay tabs deliberately
do not apply this machine's gateway to another core. Mobile needs a settings/model-picker surface
before it can expose the feature.
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.md
index 5abf4f1de..58f06510d 100644
--- a/docs/windows-session-host.md
+++ b/docs/windows-session-host.md
@@ -138,6 +138,8 @@ long-lived connection (no positional-FIFO fragility, unlike this app's tmux cont
| `attach` | `new-session -A` / `attach-session` | full, plus a screen the tmux path never needed (see below) |
| `hasSession` | `has-session -t <name>` | full (implemented; not on the hot create path — see below) |
| `write` | raw bytes on an attached client's stdin | full |
+| `writeDetachedV1` | `send-keys -H` into a released session (no client) | full — additive; an older host answers `unknown command` and the write fails closed (never re-sent as `sendKeys`) |
+| `terminateOwnerV1` | `kill -TERM -<foreground pgid>` | Windows shape — `taskkill /T /F` on the re-proven agent pid, never the console root (see below) |
| `resize` | ConPTY/pty resize + `refresh-client -C` | full; each view claims a size, the app's grid follows its most recently active view (issue #914) |
| `pause` / `resume` | node-pty `pause()`/`resume()` | full; per-viewer in core and per-connection in the host (first pause / last resume) |
| `sendKeys` | `send-keys -l -- <text>` (+ `Enter`) | full — works with no attached client, exactly like tmux |
@@ -163,7 +165,11 @@ long-lived connection (no positional-FIFO fragility, unlike this app's tmux cont
tmux CLI command (a whole subprocess per invocation), every session-host verb is a stateless
request over the ONE already-open connection, addressed by session name — the exact problem the
shadow-client machinery exists to make cheap for tmux is simply not a problem here. See the
- `sendKeys`/`paneCommand`/`capture` rows above: none of them need an attached client.
+ `sendKeys`/`paneCommand`/`capture` rows above: none of them need an attached client. A raw
+ background write to a RELEASED node (`PtyManager.backgroundWrite`, the tier tmux serves through a
+ shadow) uses `writeDetachedV1`: verbatim bytes, addressed by name, no attachment. It is not gated
+ on `ptyShadowClients` (that switch governs `tmux -C` children) and is never retried — a lost
+ reply may still have typed.
## The seeding trap (read this before touching `spawnNew`/`join`/`SessionHostPty`)
@@ -729,6 +735,18 @@ offscreen release). `targetLive` comes from `PtyManager.sessionExists`, and the
probes route by `sessionHostOwns`, which reads the release record when no `Session` is left and
otherwise applies `sendText`'s rule (no local tmux means the host owns persistence).
+**Stopping the agent (`terminateOwnerV1`, model switch / "Restart on subscription").** Windows has
+no foreground process group, so `PtyManager.terminateForeground` cannot SIGTERM one. On a
+session-host pane it sends the owner it just proved with `messageOwnerV1` (the agent-identity gate
+is MANDATORY here — the legacy "not a shell" guard is not provable on Windows); the host re-reads
+the owner, requires `sameNativeProcess` (pane generation, root pid, the single pid, OS birth time,
+executable), refuses the console root and any shell, and only then runs `taskkill /T /F` on that
+pid (`session-host/terminate-owner.ts`). The shell survives for the recycle that follows. A direct
+ConPTY pane runs the same helper in core against `NativeWindowsPane.owner()`. An older host answers
+`unknown command`; the client maps that to `'unsupported'` and the canvas says the host predates
+the verb instead of "busy". Unlike SIGTERM, `/F` gives the agent no chance to flush — the CLI's
+transcript is appended per message, so `--resume` still finds the conversation (device item).
+
The extension is independently versioned so the existing terminal protocol v1/v2 is unchanged.
Old live hosts reject the new command names, and the client returns null/false without falling
back to `write`, `sendKeys`, or a local tmux. **Installing a new app does not upgrade an already
diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.ts
index fd059e7fe..ceab4071f 100644
--- a/src/core/pty-manager.pane-owner.test.ts
+++ b/src/core/pty-manager.pane-owner.test.ts
@@ -58,13 +58,19 @@ 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)
+ 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
+ sessionHostMessageEnvelope: hostMessaging.send,
+ sessionHostTerminateOwner: hostMessaging.terminate,
+ sessionHostWriteDetached: hostMessaging.writeDetached,
+ sessionHostSupported: hostMessaging.supported
}))
const TARGET = sessionName(NODE)
const TTY = '/dev/pts/7'
@@ -472,3 +478,185 @@ describe('PtyManager.terminateForeground — identity gate', () => {
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()
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 0e7282b15..945be241d 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -213,10 +213,13 @@ import {
sessionHostMessageEnvelope,
sessionHostSendKeys,
sessionHostSupported,
+ sessionHostTerminateOwner,
+ sessionHostWriteDetached,
SessionHostProtocolCompatibilityError
} from './session-host-backend'
import type { SessionHostPty } from './session-host-pty'
import { NativeWindowsPane } from './native-windows-pane'
+import { terminatePaneOwner } from '../session-host/terminate-owner'
import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'
// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which
@@ -1243,6 +1246,9 @@ export class PtyManager {
private readonly confirmedProcessRun: ConfirmedProcessRun
/** Injectable only so Windows-only routing stays behavior-testable on every CI host. */
private readonly runtimePlatform: NodeJS.Platform
+ /** The direct-ConPTY kill (`terminateForeground`). A field, not a deps entry, so a test can swap
+ * it on an instance the same way the pane-owner tests reach `tmuxPath`; production never does. */
+ private terminateProcessTree: (pid: number) => Promise<void> = (pid) => terminateWindowsProcessTree(pid)
constructor(
deps: {
@@ -1601,6 +1607,8 @@ export class PtyManager {
* re-used by whoever attached it, and a write does not need a session-scoped client.
* 3. **the shared control client** (`sharedClientFor`) — one `tmux -C` child for the whole
* server, because `send-keys -t <session>` is a server-wide command.
+ * A released **session-host** node (Windows) takes none of tiers 2–3: the host writes by session
+ * name (`writeDetachedV1`), so there is no client to pick.
*
* Returns whether the keys were delivered. **A false is never retried on another client**: a
* timed-out `send-keys` may well have run — control mode loses the REPLY, not necessarily the
@@ -1638,6 +1646,18 @@ export class PtyManager {
const run = settings.tmuxEnabled ? this.zellijRun() : null
return run ? zellijWriteChars(run, sessionName(persistKey), data) : false
}
+ // A released SESSION-HOST node: the host writes by name, no attachment needed
+ // (`writeDetachedV1`). Same refusals as below — no released record, or a remote one, is no
+ // claim — but NOT gated on `ptyShadowClients`: that switch governs `tmux -C` children, and
+ // this leg spawns none. An older host refuses the verb; that is a plain `false`, never a
+ // fallback to `sendKeys` (a different delivery shape) and never a retry.
+ const releasedHost = this.released.get(persistKey)
+ if (releasedHost?.sessionHost) {
+ if (releasedHost.remote || !settings.tmuxEnabled || !sessionHostSupported()) return false
+ const hostTarget = sessionName(persistKey)
+ if (!isSessionName(hostTarget)) return false
+ return sessionHostWriteDetached(hostTarget, data)
+ }
if (!this.tmuxPath || !settings.tmuxEnabled) return false
// The kill switch, and the reason it sits BELOW tier 1: the painter is the session's own pty,
// which exists with or without this feature — gating it would turn "no control clients" into
@@ -6072,21 +6092,46 @@ export class PtyManager {
* `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, expectedAgentId?: string): Promise<boolean> {
+ async terminateForeground(persistKey: string, expectedAgentId?: string): Promise<boolean | 'unsupported'> {
if (typeof persistKey !== 'string' || !persistKey || persistKey.length > REF_MAX_LEN) return false
+ const live = this.liveSessionForPersistKey(persistKey)
// Refused on Zellij (ZELLIJ_BACKEND_GAPS): a signal aimed at a process group read off `ps`
// without the pane-owner proof the tmux leg has would be a guess at which process to kill.
- if (this.isZellij(persistKey, this.liveSessionForPersistKey(persistKey))) return false
+ if (this.isZellij(persistKey, live)) 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.
+ let owner: PaneOwner | null = null
if (expectedAgentId) {
- const owner = await this.paneOwner(persistKey)
+ 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
}
+ // Windows panes (a direct ConPTY, or a session-host session) have no process group and no
+ // `ps`: the kill is the PROVEN agent's process tree (`taskkill /T /F` on the one pid the owner
+ // read named), re-proven by OS birth time right before it, and never the console root — the
+ // shell survives for the recycle that follows. Both legs REQUIRE the identity gate: the legacy
+ // "not a shell" guard below has no Windows equivalent that could stand in for it.
+ if (live?.nativeWindowsPane) {
+ if (!owner) return false
+ const pane = live.nativeWindowsPane
+ const handle = { generation: '', exited: false, proc: { pid: live.proc.pid } }
+ return terminatePaneOwner(
+ () => (this.liveSessionForPersistKey(persistKey) === live ? handle : undefined),
+ owner,
+ { probe: () => pane.owner(), terminate: (pid) => this.terminateProcessTree(pid) }
+ )
+ }
+ if (!live?.sshRemote && this.sessionHostOwns(persistKey, live)) {
+ if (!owner) return false
+ try {
+ return await sessionHostTerminateOwner(sessionName(persistKey), owner)
+ } catch {
+ return false
+ }
+ }
const target = sessionName(persistKey)
const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
try {
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 8df46c1e0..011e0d446 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -315,7 +315,7 @@ export function buildRealApi(
paneOwner: (persistKey) =>
client.request(IPC.ptyPaneOwner, persistKey).catch(() => null) as Promise<PaneOwner | null>,
terminateForeground: (persistKey, expectedAgentId) =>
- client.request(IPC.ptyTerminateForeground, persistKey, expectedAgentId).catch(() => false) as Promise<boolean>,
+ client.request(IPC.ptyTerminateForeground, persistKey, expectedAgentId).catch(() => false) as Promise<boolean | 'unsupported'>,
// 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/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 011d2fd9e..f457b4c97 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -8148,18 +8148,30 @@ export function Canvas() {
// a bare shell with no agent (issue #899), so the notice carries the resume line.
text: exitTimeoutNotice(action, exitTimeoutResumeLine(nodeId))
}
- : {
+ : outcome === 'host-unsupported'
+ ? {
+ kind: 'error',
+ // Windows only: the session host serving this pane predates the verb that stops
+ // the agent by process. A live host is never replaced by an app update or restart
+ // (docs/windows-session-host.md) — it retires once its sessions end, which is what
+ // "Prepare for update…" coordinates.
+ text:
+ `${action} skipped: this session runs on a session host started by an older ` +
+ 'nodeterm, which cannot stop the agent safely. It is replaced once its sessions ' +
+ 'end (Prepare for update… does this). Nothing was written to the pane.'
+ }
+ : {
kind: 'error',
// 'not-eligible' is every "not a target right now": the gate re-checked and refused,
- // the tmux session is closed / ended / gone (which the menu row cannot see — only the
- // node knows its session state), the pane cannot be observed at all (persistent tmux
- // sessions off, or no tmux on this machine — the restart needs to watch the pane to
- // know when the CLI has quit), or a restart of this node was already in flight (the
- // per-node action and the bulk one can reach the same node).
+ // the session is closed / ended / gone (which the menu row cannot see — only the
+ // node knows its session state), the pane cannot be observed at all (persistent
+ // sessions off, or no persistence backend on this machine — the restart needs to
+ // watch the pane to know when the CLI has quit), or a restart of this node was
+ // already in flight (the per-node action and the bulk one can reach the same node).
text:
`${action} skipped: this session is busy, already restarting, not attached ` +
'(closed, ended, or nothing to resume), or its pane cannot be watched without ' +
- 'persistent tmux sessions. Nothing was written to the pane.'
+ 'persistent sessions. Nothing was written to the pane.'
}
)
}, [setNodes, markDirty])
@@ -8486,7 +8498,11 @@ export function Canvas() {
})
)
if (copy?.ok) markDirty()
- if (outcome !== 'restarted') return { kind: 'not-restarted', outcome }
+ // `host-unsupported` only comes from the terminate leg (model switch / clearEnv), which this
+ // restartShell path never takes; folded into the refusal it would be if it ever did.
+ if (outcome !== 'restarted') {
+ return { kind: 'not-restarted', outcome: outcome === 'host-unsupported' ? 'not-eligible' : outcome }
+ }
const moved = copy as ClaudeSessionCopyResult | undefined
return moved?.ok ? { kind: 'switched' } : { kind: 'copy-failed', reason: moved?.ok === false ? moved.reason : 'failed' }
},
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 7a49858f8..b6d69243b 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -4424,7 +4424,9 @@ export function TerminalNode({
if (!clearGate.ok || !sourceAgentId) return 'not-eligible'
// Identity-gated (same as a model switch): core SIGTERMs the foreground group ONLY if
// this agent still owns it, so a stale menu can never kill vim or a build in this pane.
- if (!(await api.pty.terminateForeground(id, sourceAgentId))) return 'not-eligible'
+ const stopped = await api.pty.terminateForeground(id, sourceAgentId)
+ if (stopped === 'unsupported') return 'host-unsupported'
+ if (!stopped) return 'not-eligible'
transport.recycle(id)
// `clearEnv` rides the respawn's `transport.create` (read from data above) to strip env at
// spawn; the cold-restore auto-resume relaunches the same agent against the default provider.
@@ -4474,7 +4476,9 @@ export function TerminalNode({
if (!selectedModel || session.source === 'relay') 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'
+ const stopped = await api.pty.terminateForeground(id, target)
+ if (stopped === 'unsupported') return 'host-unsupported'
+ if (!stopped) return 'not-eligible'
transport.recycle(id)
updateNodeData(id, (node) => ({
agentId: target,
diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.ts
index 01199aa13..04c8c1209 100644
--- a/src/renderer/terminal/agent-restart.test.ts
+++ b/src/renderer/terminal/agent-restart.test.ts
@@ -1531,6 +1531,12 @@ describe('summarizeBulkRestart', () => {
).toBe('1 restarted · 1 skipped (working) · 3 skipped (no session)')
})
+ it("folds 'host-unsupported' into the same skip bucket, so it never vanishes from the line", () => {
+ expect(summarizeBulkRestart(['restarted', 'host-unsupported'], { working: 0, noSession: 0 })).toBe(
+ '1 restarted · 1 skipped (no session)'
+ )
+ })
+
it('reports a run where every node was busy', () => {
expect(summarizeBulkRestart([], { working: 2, noSession: 0 })).toBe(
'0 restarted · 2 skipped (working)'
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index 0e141d5d4..8ac1afad6 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -142,7 +142,10 @@ export function clearEnvEligibility(
return { ok: true }
}
-export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible'
+/** `'host-unsupported'`: the kill a model switch / "Restart on subscription" needs went to a
+ * Windows session host that predates `terminateOwnerV1`. Nothing was signalled or written; the
+ * remedy (restart the app so a current host serves new sessions) differs from `'not-eligible'`'s. */
+export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible' | 'host-unsupported'
export const RESTART_EXIT_TIMEOUT_MS = 6000
export const RESTART_POLL_MS = 250
@@ -837,7 +840,7 @@ export function summarizeBulkRestart(
outcomes: RestartOutcome[],
skipped: { working: number; noSession: number }
): string {
- const notEligible = outcomes.filter((o) => o === 'not-eligible').length
+ const notEligible = outcomes.filter((o) => o === 'not-eligible' || o === 'host-unsupported').length
return summarizeOutcomes(outcomes, {
working: skipped.working,
noSession: skipped.noSession + notEligible
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 679d2e87a..515e82c24 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1350,8 +1350,10 @@ export interface PtyApi {
/** 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>
+ * — so a stale menu can never SIGTERM vim or a build the user started in the pane. On Windows
+ * (session host / direct ConPTY) the identity gate is mandatory and the kill is the proven agent's
+ * process tree, never the shell; `'unsupported'` = the running session host predates that verb. */
+ terminateForeground(persistKey: string, expectedAgentId?: string): Promise<boolean | 'unsupported'>
/** 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.