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): terminate agents by PID

Darren Kattanbcc6d9a2e194
diff --git a/CLAUDE.md b/CLAUDE.md
index feb87c391..67b16ac1a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -674,20 +674,31 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
**`docs/grok-agent.md`**, **`docs/gemini-agent.md`**, **`docs/copilot-agent.md`** (there is none for codex — its approval mapping
and every value's reasoning live in `src/shared/agents/approval-mode.ts`);
the distilled rules are **Adding a new agent** at the end of this section.
-- **Model gateway / switcher** — `settings.modelGateway` stores one Bifrost-compatible root +
- virtual key; `shared/agents/model-gateway.ts` is the ONE mapping from a base harness to derived
- routes, env vars, compatible models and safely quoted model flags. It derives `/v1/models`,
- `/openai/v1` and `/anthropic`; discovery runs in core (`agent:discover-models`) so browser CORS
- cannot block the Server Edition and the key never enters a terminal command. Support is a
+- **Model gateway / switcher** — `settings.modelGateway` stores one gateway root + a NON-SECRET
+ credential reference: `${env:VAR}` for environment mode or
+ `${secret:model-gateway-api-key}` for a literal held by `ModelGatewayCredentialService`. Desktop
+ literal keys reuse the GitHub token store's safeStorage encryption / 0600 fallback; Server
+ Edition uses the same generic 0600 atomic store. Legacy plaintext settings migrate only after
+ the secret write succeeds. `shared/agents/model-gateway.ts` is the ONE mapping from a base
+ harness to derived routes, env vars, compatible models and safely quoted model flags. Env
+ expansion reuses `shared/agents/expansion.ts` and happens only in core against the host process
+ environment; an unset reference fails closed instead of sending a token or partial credential.
+ Discovery at `/v1/models` is the **OpenAI Models API convention**, implemented by both LiteLLM
+ and Bifrost; the current `/openai/v1` + `/anthropic` launch-route derivation is Bifrost's layout,
+ not the source of the discovery convention. Discovery sends the standard bearer header plus
+ Bifrost's `x-bf-vk` header (needed by legacy, non-`sk-bf-` virtual keys), and runs in core
+ (`agent:discover-models`) so browser CORS cannot block the Server Edition and the key never
+ enters a terminal command. Support is a
capability (`MODEL_SWITCH_CAPABLE = claude/codex/copilot`) resolved through `capabilityAgentId`, so a
custom agent with a supported `baseAgent` inherits it automatically — the settings UI and canvas
- menu carry no agent allowlist. A model switch cleanly exits the CLI 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 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.
+ menu carry no agent allowlist. A model switch SIGTERMs the pane's foreground non-shell process
+ 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 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.
- **Grok** (`@xai-official/grok` 1.0.0, builtin since 2026-08) — in `AGENT_HOOK_TARGETS`,
`RESUMABLE_AGENTS`, `RENAME_CAPABLE`, `PERMISSION_MODE_CAPABLE` and `CANVAS_CONTROL_CAPABLE`; NOT in
`USAGE_CAPABLE` / `CONTEXT_LINK_CAPABLE` / `SUBAGENT_CAPABLE` (each blocked on a fixture that needs a
@@ -1370,8 +1381,9 @@ principle. Per-agent write-ups: `docs/grok-agent.md`, `docs/gemini-agent.md`.
command grammar as one unit instead of four copies that drift.
18. **A model switch must refresh the shell environment without printing the key.** An already-live
shell does not inherit a later `tmux set-environment`, and prefixing the resume line with
- `KEY=secret` leaks it into the pane/history. Exit the idle CLI, recycle the persistent session,
- and let cold restore resume with the new model under the newly injected environment.
+ `KEY=secret` leaks it into the pane/history. SIGTERM the pane's foreground non-shell process
+ group (a typed `/exit` can land in the agent composer as prompt text), recycle the persistent
+ session, and let cold restore resume with the new model under the newly injected environment.
## Session memory (the RAM pill + the per-session panel)
diff --git a/src/core/pane-process.test.ts b/src/core/pane-process.test.ts
new file mode 100644
index 000000000..987582a21
--- /dev/null
+++ b/src/core/pane-process.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest'
+import { foregroundProcessGroup, parsePaneProcess } from './pane-process'
+
+describe('pane foreground process safety', () => {
+ it('parses the tmux pane pid and foreground command', () => {
+ expect(parsePaneProcess('33293|codex\n')).toEqual({ panePid: 33293, command: 'codex' })
+ expect(parsePaneProcess('bad|codex')).toBeNull()
+ expect(parsePaneProcess('33293|')).toBeNull()
+ })
+
+ it('accepts only a distinct positive foreground process group', () => {
+ const pane = { panePid: 33293, command: 'codex' }
+ expect(foregroundProcessGroup(pane, '33319\n')).toBe(33319)
+ expect(foregroundProcessGroup(pane, '33293')).toBeNull()
+ expect(foregroundProcessGroup(pane, '-1')).toBeNull()
+ expect(foregroundProcessGroup(pane, 'not-a-pid')).toBeNull()
+ })
+
+ it('never treats a shell-owned pane as an agent to terminate', () => {
+ expect(foregroundProcessGroup({ panePid: 33293, command: '-zsh' }, '33319')).toBeNull()
+ expect(foregroundProcessGroup({ panePid: 33293, command: '/bin/bash' }, '33319')).toBeNull()
+ })
+})
diff --git a/src/core/pane-process.ts b/src/core/pane-process.ts
new file mode 100644
index 000000000..576a2472f
--- /dev/null
+++ b/src/core/pane-process.ts
@@ -0,0 +1,38 @@
+import { isShellCommand } from '../shared/agents/pane'
+
+export interface PaneProcess {
+ panePid: number
+ command: string
+}
+
+/** Parse the deliberately tiny tmux format used before terminating a pane's foreground agent. */
+export function parsePaneProcess(value: string): PaneProcess | null {
+ const line = value.trim()
+ const split = line.indexOf('|')
+ if (split <= 0) return null
+ const panePid = Number(line.slice(0, split))
+ const command = line.slice(split + 1).trim()
+ if (!Number.isSafeInteger(panePid) || panePid <= 0 || !command) return null
+ return { panePid, command }
+}
+
+/**
+ * Validate `ps -o tpgid=` against the tmux pane we just observed. The pane PID is its login
+ * shell/process-group leader; killing that group would destroy the shell rather than only the
+ * foreground agent, so it is always refused. A shell reported directly by tmux is refused too.
+ */
+export function foregroundProcessGroup(
+ pane: PaneProcess,
+ value: string
+): number | null {
+ if (isShellCommand(pane.command)) return null
+ const processGroup = Number(value.trim())
+ if (
+ !Number.isSafeInteger(processGroup) ||
+ processGroup <= 0 ||
+ processGroup === pane.panePid
+ ) {
+ return null
+ }
+ return processGroup
+}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index a8c29a226..a40e49a52 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -32,6 +32,8 @@ import {
remotePaneCommandArgs,
remotePaneOwnerArgs,
remoteForegroundArgvArgs,
+ remotePaneProcessArgs,
+ remoteTerminateForegroundArgs,
remotePaneCursorArgs
} from './remote-ssh/control-master'
import { parsePaneCursor } from './pane-cursor'
@@ -76,6 +78,8 @@ import { hasSharedIdentity, setCustomAgentBaseResolver, type AgentId } from '../
import { findCustomAgent } from '../shared/agents/custom-agent'
import { applyCustomAgentEnv, customAgentEnvArgs } from './custom-agent-env'
import { modelGatewayEnv } from '../shared/agents/model-gateway'
+import { foregroundProcessGroup, parsePaneProcess } from './pane-process'
+import { isShellCommand } from '../shared/agents/pane'
// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which
// kills the tmux server) can still replay recent output on cold restart. A final snapshot also
@@ -1340,6 +1344,9 @@ 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)
+ )
}
/** Feeds the renderer's "tmux not found" banner. Without tmux the app silently degrades to a
@@ -2994,6 +3001,54 @@ 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.
+ */
+ async terminateForeground(persistKey: string): Promise<boolean> {
+ if (typeof persistKey !== 'string' || !persistKey || persistKey.length > REF_MAX_LEN) return false
+ const target = sessionName(persistKey)
+ const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
+ try {
+ if (sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return false
+ const { stdout } = await runAsync(
+ ssh,
+ remotePaneProcessArgs(sshRemote.conn, sshRemote.controlPath, target)
+ )
+ const pane = parsePaneProcess(stdout)
+ if (!pane || isShellCommand(pane.command)) return false
+ await runAsync(
+ ssh,
+ remoteTerminateForegroundArgs(sshRemote.conn, sshRemote.controlPath, pane.panePid)
+ )
+ return true
+ }
+ if (!this.tmuxPath) return false
+ const { stdout } = await runAsync(this.tmuxPath, [
+ '-L',
+ TMUX_SOCKET,
+ 'display-message',
+ '-p',
+ '-t',
+ target,
+ '#{pane_pid}|#{pane_current_command}'
+ ])
+ const pane = parsePaneProcess(stdout)
+ if (!pane) return false
+ const processTable = await runAsync('ps', ['-o', 'tpgid=', '-p', String(pane.panePid)])
+ const processGroup = foregroundProcessGroup(pane, processTable.stdout)
+ if (!processGroup) return false
+ process.kill(-processGroup, 'SIGTERM')
+ return true
+ } catch {
+ return false
+ }
+ }
+
/**
* WHO owns a node's pane right now, read from the kernel: the pane's pid and tty from tmux, then
* the full argv of the tty's FOREGROUND PROCESS GROUP. `paneCommand` above answers one name —
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index 0d2ff654c..21baa5b1e 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -80,6 +80,8 @@ vi.mock('node-pty', () => ({
*/
const execCalls: Array<{ file: string; args: string[] }> = []
const liveTmuxSessions = new Set<string>()
+let paneProcessReply = ''
+let processGroupReply = ''
vi.mock('child_process', () => {
type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void
@@ -98,6 +100,10 @@ vi.mock('child_process', () => {
ok('__NT_PATH_START__/usr/bin:/bin__NT_PATH_END__')
} else if (args.includes('capture-pane')) {
ok('PANE SNAPSHOT')
+ } else if (args.includes('#{pane_pid}|#{pane_current_command}')) {
+ ok(paneProcessReply)
+ } else if (file === 'ps' && args.includes('tpgid=')) {
+ ok(processGroupReply)
} else {
ok('')
}
@@ -132,6 +138,8 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
spawnArgs.length = 0
execCalls.length = 0
liveTmuxSessions.clear()
+ paneProcessReply = ''
+ processGroupReply = ''
userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-solo-'))
fake = fakePlatform({ userDataDir })
initPlatform(fake)
@@ -139,6 +147,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
})
afterEach(() => {
vi.useRealTimers()
+ vi.restoreAllMocks()
resetPlatformForTests()
// BEST EFFORT, and it must stay that way. This races a write it cannot wait for: the scrollback
// snapshot is fired and forgotten by design (`snapshotScrollback` is best-effort and nothing
@@ -473,6 +482,33 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
expect(tmuxCalls('kill-session')).toEqual([]) // the session keeps running
})
+ it('terminates an agent foreground process group without typing into its pane', async () => {
+ await tmuxManager()
+ await create(80, 24)
+ paneProcessReply = '33293|codex\n'
+ processGroupReply = '33319\n'
+ const signal = vi.spyOn(process, 'kill').mockImplementation(() => true)
+ execCalls.length = 0
+
+ await expect(fake.handlers[IPC.ptyTerminateForeground]('solo-1')).resolves.toBe(true)
+
+ expect(signal).toHaveBeenCalledWith(-33319, 'SIGTERM')
+ expect(tmuxCalls('send-keys')).toEqual([])
+ expect(execCalls.some((call) => call.file === 'ps' && call.args.includes('tpgid='))).toBe(true)
+ })
+
+ it('refuses to terminate the pane login shell', async () => {
+ await tmuxManager()
+ await create(80, 24)
+ paneProcessReply = '33293|-zsh\n'
+ processGroupReply = '33293\n'
+ const signal = vi.spyOn(process, 'kill').mockImplementation(() => true)
+
+ await expect(fake.handlers[IPC.ptyTerminateForeground]('solo-1')).resolves.toBe(false)
+
+ expect(signal).not.toHaveBeenCalled()
+ })
+
it('the detach path still snapshots the scrollback (cold restore after a reboot)', async () => {
await tmuxManager()
const { sessionId } = await create(80, 24)
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 38af19235..2bab11d45 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -11,6 +11,8 @@ import {
probeSaysAbsent,
remoteCapturePaneArgs,
remotePaneCommandArgs,
+ remotePaneProcessArgs,
+ remoteTerminateForegroundArgs,
remoteListSessionsArgs,
parseRemoteSessionNames,
remoteTmuxPtyArgs,
@@ -238,6 +240,27 @@ describe('remotePaneCommandArgs', () => {
})
})
+describe('remote foreground process termination', () => {
+ it('reads pane pid + command through the existing ControlMaster', () => {
+ const args = remotePaneProcessArgs(conn, '/s.sock', 'nt-x')
+ expect(args[args.length - 1]).toBe(
+ `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t nt-x '#{pane_pid}|#{pane_current_command}'`
+ )
+ })
+
+ it('revalidates the foreground group and never targets the pane shell group', () => {
+ const args = remoteTerminateForegroundArgs(conn, '/s.sock', 33293)
+ const command = args[args.length - 1]
+ expect(command).toContain('ps -o tpgid= -p 33293')
+ expect(command).toContain('[ "$tpgid" -ne 33293 ]')
+ expect(command).toContain('kill -TERM -- "-$tpgid"')
+ })
+
+ it('refuses an invalid pane pid before building a remote shell command', () => {
+ expect(() => remoteTerminateForegroundArgs(conn, '/s.sock', -1)).toThrow('invalid-pane-pid')
+ })
+})
+
describe('remoteListSessionsArgs', () => {
it('asks the remote nodeterm tmux socket for session names only', () => {
const args = remoteListSessionsArgs(conn, '/cm/p1')
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index c5db1f51f..e5a5757f1 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -486,6 +486,41 @@ export function remotePaneCommandArgs(conn: SshConnection, controlPath: string,
`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_current_command}'`
)
}
+
+/** Ask remote tmux for the shell PID and current command as one parseable, bounded record. */
+export function remotePaneProcessArgs(
+ conn: SshConnection,
+ controlPath: string,
+ sessionId: string
+): string[] {
+ return childArgs(
+ conn,
+ controlPath,
+ `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_pid}|#{pane_current_command}'`
+ )
+}
+
+/**
+ * SIGTERM the remote pane's foreground process group, after core has already confirmed tmux is
+ * reporting an agent rather than a shell. The shell re-reads tpgid here to close the process-race
+ * window and refuses its own group (`panePid`) before invoking kill.
+ */
+export function remoteTerminateForegroundArgs(
+ conn: SshConnection,
+ controlPath: string,
+ panePid: number
+): string[] {
+ if (!Number.isSafeInteger(panePid) || panePid <= 0) {
+ throw new Error('invalid-pane-pid')
+ }
+ return childArgs(
+ conn,
+ controlPath,
+ `tpgid=$(ps -o tpgid= -p ${panePid} | tr -d '[:space:]') && ` +
+ `case "$tpgid" in ''|*[!0-9]*) exit 1;; esac && ` +
+ `[ "$tpgid" -gt 0 ] && [ "$tpgid" -ne ${panePid} ] && kill -TERM -- "-$tpgid"`
+ )
+}
/**
* Ask the REMOTE tmux for everything the ownership read needs in one round-trip — the remote
* counterpart of `PtyManager.paneOwner`'s first call. Same single-quoting rule as
diff --git a/src/preload/index.test.ts b/src/preload/index.test.ts
index 5deb6fa58..c368786b4 100644
--- a/src/preload/index.test.ts
+++ b/src/preload/index.test.ts
@@ -36,6 +36,11 @@ import './index'
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')
+ })
+
it('exposes GitHub issue data and host-control namespaces on their exact channels', async () => {
await api.githubIssues.query({ projectId: 'p1', columnId: null, pageSize: 50 })
await api.githubControl.saveToken('write-only-secret')
diff --git a/src/preload/index.ts b/src/preload/index.ts
index a23ae3124..76835be62 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -74,6 +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),
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 4cff76a7a..e8c9616ef 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -237,6 +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>,
// 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 18a9182ac..11610480f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -4664,12 +4664,10 @@ export function Canvas() {
[setNodes]
)
- // Restart ONE agent CLI in place: quit it and relaunch it with the provider's own `--resume`, so
- // a newly released model shows up in its model list without losing the conversation. The node's
- // registered closure owns the whole choreography (and re-checks eligibility + liveness at call
- // time, so a stale menu cannot force a restart onto a session that just went busy); all that is
- // left here is telling the user how it went. Up to ~6s of exit polling plus the echo-verified
- // resume line, hence the await before the notice.
+ // Restart ONE agent CLI while preserving its provider session. Ordinary restart/reopen asks the
+ // harness to exit and types its resume command; model switching terminates the foreground agent
+ // process and rebuilds the tmux session so gateway env is re-applied. The node closure owns that
+ // distinction and re-checks eligibility/liveness at call time; this layer reports the outcome.
const restartAgentNode = useCallback(async (
nodeId: string,
targetAgentId?: AgentId,
@@ -4726,7 +4724,7 @@ export function Canvas() {
useSettings.getState().settings.customAgents.find((c) => c.id === targetAgentId)?.label ??
targetAgentId)
// 'info' fades itself out; anything that did NOT restart is left on screen to be read and
- // dismissed — the pane is untouched either way (nothing is ever killed).
+ // dismissed.
setNotice(
outcome === 'restarted'
? {
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index cde5e94cd..f2d2b0d76 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -2887,21 +2887,15 @@ export function TerminalNode({
target,
getNode(id)?.data.agentModel as string | undefined
)
- // A model switch must rebuild the terminal session, not merely type a new command into its
- // existing shell: URL/key env was fixed when that shell was spawned and may have been
- // configured AFTER this node was created. Recycling after a clean CLI exit gives the new
- // shell the current gateway env without ever exposing the key in the pane. Relay sessions
- // belong to another core/settings store, so a local gateway must never be pushed into one.
+ // A model switch must rebuild the terminal session: URL/key env was fixed when that shell
+ // was spawned and may have been configured AFTER this node was created. Do not type the
+ // harness's slash-exit command here — an agent composer can treat it as prompt text. Core
+ // instead SIGTERMs the pane's foreground non-shell process group, then recycling gives the
+ // replacement shell the current gateway env. Relay sessions belong to another
+ // core/settings store, so a local gateway must never be pushed into one.
if (targetModel) {
if (!selectedModel || session.source === 'relay') return 'not-eligible'
- const exited = await performExitPhase({
- agentId: target,
- sessionId: agentSessionId,
- io: restartIo,
- paneCommand: () => api.pty.paneCommand(id),
- isLive: restartTarget
- })
- if (exited !== 'exited') return exited
+ if (!(await api.pty.terminateForeground(id))) return 'not-eligible'
transport.recycle(id)
updateNodeData(id, (node) => ({
agentId: target,
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 8f9916fb3..df4788871 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -21,6 +21,9 @@ export const IPC = {
/** The foreground command of a node's tmux pane (`#{pane_current_command}`) — how the in-place
* agent restart sees that the CLI has exited and a shell owns the pane again. */
ptyPaneCommand: 'pty:pane-command',
+ /** Renderer → core: SIGTERM the non-shell foreground process group in this node's pane.
+ * Model switching uses this instead of typing an exit slash-command into an agent composer. */
+ ptyTerminateForeground: 'pty:terminate-foreground',
ptyReadSessionName: 'pty:read-session-name',
/** Shell → renderer: this MACHINE's pty-device pressure band changed (core/pty-pressure.ts).
* Payload: `PtyPressure` — `{ level, usage, ceiling }`. Sent on band CHANGES only, and re-sent
diff --git a/src/shared/types.ts b/src/shared/types.ts
index ea5f8b2c4..db1882649 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -641,6 +641,9 @@ 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>
/** 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.