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(pause): pause a whole project, group or selection — including sessions not on screen (#1184)

Mina Sameh18d3dd2e100c
diff --git a/CLAUDE.md b/CLAUDE.md
index b52ce3c19..8a7146887 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1100,8 +1100,9 @@ Lifecycle, by intent:
restart nothing can hibernate and deferring would make Eco a memory regression). Eco is
structurally inert for sessions with no turn in the current app run, and that is now a DECISION,
not a follow-up: the persisted `agentStatus.lastSeen` clock (see **Status-grouped sessions**) is
- deliberately never an idle proof — see "A restored clock is not an idle proof" in
- `terminal/hibernation-policy.ts`.
+ deliberately never an idle proof FOR ECO — see "A restored clock is not an idle proof" in
+ `terminal/hibernation-policy.ts`. (A user-confirmed bulk pause is the one place it is read as weak
+ evidence; see **Bulk pause** and the `lastSeen` rules under **Status-grouped sessions**.)
The deferral is also unaware of `paused`: a deep-paused node's freshly recycled shell keeps its
xterm alive until the hard cap, waiting for a hibernation that (being already exited, or having
no CLI to exit) can never come — a second documented follow-up.
@@ -1127,6 +1128,63 @@ Lifecycle, by intent:
on the manual path, closed here on the automatic one. Node menu only today (canvas right-click +
the sessions sidebar row menu, which shares the same `selectionItems` builder, plus a read-only
kanban card badge and a clickable one in the card modal); no command palette entry.
+- **Bulk pause** (tab menu and sessions-sidebar project menu: *Pause project* / *Cancel pending
+ pauses* / *Resume all*; group frame menu: *Pause group*; a multi-selection of ≥2 agents: *Pause N
+ sessions*; a count badge on the tab) → the shallow "Pause session" above, applied to many nodes
+ at once, and it works on nodes that are NOT mounted (a project that is not on screen has no
+ `TerminalNode`, so no registered pause closure). It never recycles a tmux session. Rules a
+ refactor must not undo:
+ (1) **Typing into a pane by node id is ONE primitive, `PtyManager.sendPaneKeys(persistKey, data)`**
+ (`pty:send-pane-keys`, `HOST_ONLY`, classified `EDITOR_ONLY` in the relay access policy and
+ `SCOPED_REFUSED` for a scoped guest). Keys go over stdin to `tmux source-file -` through the
+ existing `controlInputPlan` / `remoteControlInputPlan`, never argv, to the exact `=nt-<id>:`.
+ (2) **An SSH-project node is never read or typed into on the local socket.** `paneRemoteRef`
+ resolves an unmounted SSH node through `remoteNodeOwner` (the machine-local index); a
+ disconnected master, or a stray LIVE local session for an SSH-project node, is `not-connected` /
+ unreachable, never a local fallback. `paneCommand` / `paneOwner` take an opt-in
+ `{ resolveUnmounted: true }` and **the default stays the legacy live-only path ON PURPOSE**:
+ agent messaging and `terminateForeground` also call them, and if they resolved an unmounted
+ remote node they would prove an owner on the HOST and then act on the LOCAL socket. Zellij, the
+ Windows session host, a native Windows pane and a plain shell answer `unsupported-backend`.
+ (3) **`planBulkPause` (`lib/bulkPause.ts`) is the whole decision**: `now` (idle `done`, or an
+ UNKNOWN state whose persisted `agentStatus.lastSeen.state` is `done` — `idleForPause`),
+ `whenDone` (working / waiting / blocked, or a held question/approval ticket — typing `/exit` into
+ those would answer a prompt), `alreadyExited` (hibernated by Eco: nothing to type, just mark it
+ paused), and named skips, exactly the `BulkPauseSkip` reasons: `not-agent`, `no-session-id`,
+ `not-resumable` (also an agent with no `exitSequence`, e.g. antigravity: resumable, but nothing
+ can ask it to quit), `already-paused`, `relay`, `dropped`, `ended`, `state-unknown`. The
+ unknown-state rule exists because state is transient: right after an app restart every node reads
+ unknown, and an idle CLI and one mid-turn look the same — typing an exit into a running turn
+ abandons it. `lastSeen` is the one clock that survives the restart, so a node last seen `done` is
+ paused and every other unknown node is skipped, never guessed at (the runner re-asks the same
+ rule at fire time). A skipped node says why; nothing is silently dropped, and the result line
+ (`bulkPauseResultText`) counts EVERY outcome — paused, pending, unreachable, `unverified`, not
+ eligible, still running, skipped — so a batch against a disconnected host never reads "Paused 0".
+ (4) **`whenDone` is `state/pendingPause.ts`, TRANSIENT** (never persisted: after a restart nothing
+ is watched, so a stored mark would lie). It fires on a CLEAN `done` edge only (not errored,
+ interrupted or held), the mark is removed BEFORE the fire so a second edge cannot double it, and
+ Resume, Cancel, node delete or the fire clear it, and the watcher also drops a mark when the node
+ is paused elsewhere or its status disappears. **A mark is bound to the session it was planned
+ against** (`BulkPauseTarget.sessionId`): the watcher drops it unfired when the node's session id
+ changes, the runner refuses a mismatch, and every Canvas funnel that replaces the CLI —
+ `restartAgentNode` (restart, fresh shell, model switch, reopen as), the Claude and Codex account
+ switches, the bulk idle restart and both `transport.recycle` sites — removes it, or a mark taken
+ for one turn would quit the NEW session on its first turn end.
+ (5) **Every exit holds `guardConcurrentRestart(nodeId, …)`** (the Eco / Pause / restart set) and
+ runs through ONE `createHostLimiter(BULK_PAUSE_HOST_CAP = 3)` per host key, shared by the batch
+ and the pending fires; owner reads are bounded. The host key is `local` or the **SSH project id**,
+ not the host: ControlMasters are per project, so the cap bounds channels per master.
+ `pauseNodeHeadless` (`terminal/headless-pause.ts`) is `performExitPhase` over `sendPaneKeys`, with
+ the menu restart's late window (`RESTART_LATE_EXIT_MS`) so a CLI that quits just after the base
+ 6 s is paused rather than reported "still running"; a failed key write ends that wait at once
+ (`unreachable`). A pane owner that cannot be read before the exit (no live ControlMaster, a hung
+ read) is `unverified`, distinct from `not-eligible` (read and refused): nothing is typed in
+ either case.
+ (6) **Resume all is the active project only**: waking is the mounted node's `wakeHibernatedNode`,
+ so elsewhere the row is disabled with `Open the project to resume`.
+ Surfaces: Desktop full (local + SSH); Server Edition has the core primitive and a real ws-bridge
+ leg, but pending fires need an open browser tab (the watcher is the renderer's); relay tabs are
+ refused; the kanban card menus inherit the rows through `nodeActionItems`; Mobile: follow-up.
The node id is the `persistKey` (passed to `transport.create`), so it must stay stable.
If tmux is unavailable, `PtyManager` falls back to a plain shell (no cross-restart
@@ -3854,6 +3912,13 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
prompt after boot would not be enough: the background-task stamp and the subagent cards Eco
also needs are transient and cannot be rebuilt after a restart, and `/exit` kills both
silently. A session becomes a candidate again from its next live `done`.
+ - **Bulk pause is the ONE reader that acts on it** (`idleForPause`, `lib/bulkPause.ts`): an
+ unknown-state session is pausable only when `lastSeen.state === 'done'`. The difference from Eco
+ is consent and proof, not the clock: a person confirmed the pause, the runner still proves the
+ agent owns its pane before typing, and without it every session after a restart would be
+ unpausable exactly when memory is tightest. The residual is stated there: a session last seen
+ idle that started a turn while the app was closed (cron, loop, task notification) can be
+ interrupted. Nothing automatic may read it.
- **Its own key, so the main table's write cadence is unchanged.** State events still write
nothing to `nodeterm.agentStatus`. That matters twice: the main table carries `loop.items` (up to
100 × 4000 chars per loop node — 428 KB and ~2.1 ms per stringify with one full loop, measured in
@@ -6474,7 +6539,8 @@ about which machine they describe. Reading + parsing is `core/session-memory.ts`
"end the tmux session too" was not built. The control is NOT a third depth: it calls
`pauseAgentNode(id, false)` — the same "Pause session" the node menu offers, the same
`performExitPhase`, the same PAUSED chip and the same Resume — because a panel-only "hibernate"
- would be a third concept for the user and a second exit path to keep in step with Eco's. Which
+ would be a third concept for the user and a second exit path to keep in step with Eco's. To pause
+ many rows at once, use **Bulk pause** (Terminal session continuity), not a loop over this control. Which
rows may offer it is the pure `renderer/lib/sessionPause.ts`, and its two directions are
deliberate: a row that could NEVER be paused (an orphan, a plain terminal, an agent we cannot
quit-and-resume) renders **nothing** — a dead control on most rows of a machine-wide list is
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index dc549d160..4d3135114 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -265,6 +265,11 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
## House rules
+- **Typing into a pane by node id goes through `PtyManager.sendPaneKeys`, and an SSH-project node
+ is never read or typed into on the local tmux socket.** An unmounted remote node resolves through
+ `remoteNodeOwner` or is refused (`not-connected`); `paneCommand` / `paneOwner` resolve unmounted
+ nodes only with the explicit `{ resolveUnmounted: true }` option. See Bulk pause in `CLAUDE.md`.
+
- **Branch labels describe a checkout on one core.** Share existing status reads through
`renderer/state/gitBranches.ts`; do not cache a branch forever by project id or copy a project
branch onto worktree nodes. Source, Sessions and worktree headers consume the same observations,
diff --git a/src/core/pty-manager.pane-keys.test.ts b/src/core/pty-manager.pane-keys.test.ts
new file mode 100644
index 000000000..0126f8d20
--- /dev/null
+++ b/src/core/pty-manager.pane-keys.test.ts
@@ -0,0 +1,203 @@
+// `PtyManager.sendPaneKeys` + the remote-aware pane target of `paneCommand` / `paneOwner`: a node
+// asked about BY ID with no mounted terminal. An SSH-project node resolves on its host through the
+// persisted index (`setRemoteNodeOwner`), and never falls back to the local tmux socket. Mock
+// harness copied from pty-manager.control-input.test.ts (stdin-carrying runner).
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { DEFAULT_SETTINGS } from '../shared/types'
+
+const calls = vi.hoisted(() => [] as Array<{ file: string; args: string[]; input: string | undefined }>)
+const script = vi.hoisted(() => ({
+ answer: (() => ({ stdout: '' })) as (file: string, args: string[]) => { stdout: string } | Promise<{ stdout: string }>
+}))
+
+vi.mock('child_process', async () => {
+ const { promisify } = await import('util')
+ 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, input: undefined })
+ Promise.resolve()
+ .then(() => script.answer(file, args))
+ .then(
+ (r) => cb?.(null, { stdout: r.stdout, stderr: '' }),
+ (e) => cb?.(e as Error)
+ )
+ return {}
+ }
+ ;(execFile as unknown as Record<symbol, unknown>)[promisify.custom] = (file: string, args: string[]) => {
+ const call = { file, args, input: undefined as string | undefined }
+ calls.push(call)
+ let answer: { stdout: string } | Promise<{ stdout: string }>
+ try {
+ answer = script.answer(file, args)
+ } catch (e) {
+ answer = Promise.reject(e)
+ }
+ const p = Promise.resolve(answer).then((r) => ({ stdout: r.stdout, stderr: '' }))
+ const child = { stdin: { on: () => undefined, end: (input: string) => void (call.input = input) } }
+ return Object.assign(p, { child })
+ }
+ 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: () => ({}) }))
+
+const CONN = { host: 'h', user: 'u' }
+const REMOTE_OWNER = { projectId: 'p', hostKey: 'u@h', remote: { conn: CONN, controlPath: '/cp' } }
+
+type Mgr = {
+ tmuxPath: string | null
+ sessions: Map<string, Record<string, unknown>>
+ byPersistKey: Map<string, string>
+ zellijKeys: Set<string>
+ getSettings: () => typeof DEFAULT_SETTINGS
+ setRemoteNodeOwner(r: (id: string) => unknown): void
+ sendPaneKeys(k: string, d: string): Promise<unknown>
+ paneCommand(k: string, o?: { resolveUnmounted?: boolean }): Promise<string | null>
+ paneOwner(k: string, o?: { resolveUnmounted?: boolean }): Promise<unknown>
+}
+async function makeManager(tmux: string | null = '/usr/bin/tmux') {
+ const { PtyManager } = await import('./pty-manager')
+ const pm = new PtyManager() as unknown as Mgr
+ pm.tmuxPath = tmux
+ return pm
+}
+
+function live(pm: Mgr, extra: Record<string, unknown>) {
+ pm.sessions.set('sess-1', { persistKey: 'n1', indexKey: 'n1', nodeId: 'n1', tmuxBacked: true, proc: { write: vi.fn() }, ...extra })
+ pm.byPersistKey.set('n1', 'sess-1')
+}
+
+beforeEach(() => {
+ calls.length = 0
+ script.answer = () => ({ stdout: '' })
+ ssh.path = '/usr/bin/ssh'
+ vi.resetModules()
+ initPlatform(fakePlatform())
+})
+afterEach(() => resetPlatformForTests())
+
+describe('sendPaneKeys', () => {
+ it('types into the local pane over stdin with an exact target', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => null)
+ await expect(pm.sendPaneKeys('n1', '\x03')).resolves.toEqual({ ok: true })
+ const c = calls[0]
+ expect(c.file).toBe('/usr/bin/tmux')
+ expect(c.args).toContain('source-file')
+ expect(c.input).toContain('=nt-n1:')
+ expect(c.args.join(' ')).not.toContain('\x03')
+ })
+
+ it('routes an unmounted SSH node over its project master', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: true })
+ expect(calls[0].file).toMatch(/ssh$/)
+ })
+
+ it('refuses an SSH node whose project is not connected and never touches local tmux', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => ({ projectId: 'p', hostKey: 'u@h' }))
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: false, reason: 'not-connected' })
+ expect(calls).toHaveLength(0)
+ })
+
+ it('refuses when there is no tmux', async () => {
+ const pm = await makeManager(null)
+ pm.setRemoteNodeOwner(() => null)
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: false, reason: 'unsupported-backend' })
+ })
+
+ it('refuses empty data', async () => {
+ const pm = await makeManager()
+ await expect(pm.sendPaneKeys('n1', '')).resolves.toEqual({ ok: false, reason: 'failed' })
+ })
+})
+
+describe('sendPaneKeys refusals', () => {
+ it.each([
+ ['session host', { sessionHost: true }],
+ ['native windows pane', { nativeWindowsPane: {} }],
+ ['not tmux-backed', { tmuxBacked: false }]
+ ])('refuses a live %s session', async (_n, extra) => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => null)
+ live(pm, extra)
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: false, reason: 'unsupported-backend' })
+ expect(calls).toHaveLength(0)
+ })
+ it('refuses a Zellij node', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => null)
+ pm.zellijKeys.add('n1')
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: false, reason: 'unsupported-backend' })
+ expect(calls).toHaveLength(0)
+ })
+ it('refuses with no-ssh when ssh is missing', async () => {
+ ssh.path = null
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: false, reason: 'no-ssh' })
+ expect(calls).toHaveLength(0)
+ })
+ it('a live LOCAL session for an SSH-project node is not-connected, never the local socket', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ live(pm, {})
+ await expect(pm.sendPaneKeys('n1', 'x')).resolves.toEqual({ ok: false, reason: 'not-connected' })
+ expect(calls).toHaveLength(0)
+ })
+})
+
+describe('paneCommand / paneOwner: legacy default vs resolveUnmounted', () => {
+ it('default: an unmounted SSH node is still asked on the LOCAL socket (pre-task behaviour)', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ script.answer = () => ({ stdout: 'zsh\n' })
+ await expect(pm.paneCommand('n1')).resolves.toBe('zsh')
+ expect(calls[0].file).toBe('/usr/bin/tmux')
+ })
+ it('default: paneOwner of an unmounted SSH node also stays local', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ await pm.paneOwner('n1')
+ expect(calls[0].file).toBe('/usr/bin/tmux')
+ })
+ it('resolveUnmounted: asks the host, not the local socket', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ script.answer = () => ({ stdout: 'zsh\n' })
+ await expect(pm.paneCommand('n1', { resolveUnmounted: true })).resolves.toBe('zsh')
+ expect(calls[0].file).toMatch(/ssh$/)
+ })
+ it('resolveUnmounted: null when the owning project is disconnected', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => ({ projectId: 'p', hostKey: 'u@h' }))
+ await expect(pm.paneCommand('n1', { resolveUnmounted: true })).resolves.toBeNull()
+ await expect(pm.paneOwner('n1', { resolveUnmounted: true })).resolves.toBeNull()
+ expect(calls).toHaveLength(0)
+ })
+ it('resolveUnmounted: paneOwner connected asks the host', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ await pm.paneOwner('n1', { resolveUnmounted: true })
+ expect(calls[0].file).toMatch(/ssh$/)
+ })
+ it('resolveUnmounted: a live local session of an SSH-project node answers null', async () => {
+ const pm = await makeManager()
+ pm.setRemoteNodeOwner(() => REMOTE_OWNER)
+ live(pm, {})
+ await expect(pm.paneCommand('n1', { resolveUnmounted: true })).resolves.toBeNull()
+ expect(calls).toHaveLength(0)
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index e9887505b..16978a072 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -14,6 +14,7 @@ import { xtermScrollback } from '../shared/scrollback'
import {
DEFAULT_SETTINGS,
type PaneCursor,
+ type PaneKeysResult,
type PtyCreateOptions,
type PtyCreateResult,
type PtyRecycleTarget,
@@ -2201,11 +2202,16 @@ export class PtyManager {
this.sendToEmptyPrompt(persistKey, text, typeof agentId === 'string' ? agentId : '')
)
platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())
- platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))
+ platform().handle(IPC.ptyPaneCommand, (persistKey: string, opts?: { resolveUnmounted?: boolean }) =>
+ this.paneCommand(persistKey, opts?.resolveUnmounted === true ? { resolveUnmounted: true } : undefined)
+ )
+ platform().handle(IPC.ptySendPaneKeys, (persistKey: string, data: string) => this.sendPaneKeys(persistKey, data))
platform().handle(IPC.ptyPaneCwd, (persistKey: string) => this.paneCwd(persistKey))
// Registered HERE, beside its name-only sibling, rather than in either shell: core owns both
// reads, so the desktop and the Server Edition are served by one line and cannot drift.
- platform().handle(IPC.ptyPaneOwner, (persistKey: string) => this.paneOwner(persistKey))
+ platform().handle(IPC.ptyPaneOwner, (persistKey: string, opts?: { resolveUnmounted?: boolean }) =>
+ this.paneOwner(persistKey, opts?.resolveUnmounted === true ? { resolveUnmounted: true } : undefined)
+ )
platform().handle(IPC.ptyTerminateForeground, (persistKey: string, expectedAgentId?: string) =>
this.terminateForeground(persistKey, expectedAgentId)
)
@@ -6527,6 +6533,66 @@ export class PtyManager {
return typesChatInput(agentId) ? this.sendText(persistKey, text, { typedFor: agentId }) : this.sendText(persistKey, text)
}
+ /**
+ * Where a node's pane lives when asked BY NODE ID. A live session's own master wins; with nothing
+ * attached, the persisted index decides (`setRemoteNodeOwner`). An SSH-project node whose project
+ * has no live master answers 'unreachable' — never the local socket, which is the wrong machine.
+ */
+ private paneRemoteRef(
+ persistKey: string,
+ live: Session | undefined
+ ): { kind: 'local' } | { kind: 'remote'; conn: SshConnection; controlPath: string } | { kind: 'unreachable' } {
+ if (live?.sshRemote) return { kind: 'remote', conn: live.sshRemote.conn, controlPath: live.sshRemote.controlPath }
+ const owner = this.remoteNodeOwner?.(persistKey) ?? null
+ // A node the persisted index places in an SSH project is NEVER local — not even when a live
+ // LOCAL session exists for its id (that is the stray the local-fallback bug leaves behind).
+ if (!owner) return { kind: 'local' }
+ if (live) return { kind: 'unreachable' }
+ return owner.remote
+ ? { kind: 'remote', conn: owner.remote.conn, controlPath: owner.remote.controlPath }
+ : { kind: 'unreachable' }
+ }
+
+ /**
+ * Type raw keys into a node's tmux pane by node id — no mounted terminal needed. Same stdin-only
+ * `source-file -` plan a live-link controller uses (bytes never ride argv; exact target
+ * `=nt-<id>:`), local or over the owning project's ControlMaster. Never rejects.
+ */
+ async sendPaneKeys(persistKey: string, data: string): Promise<PaneKeysResult> {
+ if (typeof persistKey !== 'string' || typeof data !== 'string' || data.length === 0) {
+ return { ok: false, reason: 'failed' }
+ }
+ const live = this.liveSessionForPersistKey(persistKey)
+ if (this.isZellij(persistKey, live)) return { ok: false, reason: 'unsupported-backend' }
+ if (live && (live.sessionHost || live.nativeWindowsPane || !live.tmuxBacked)) {
+ return { ok: false, reason: 'unsupported-backend' }
+ }
+ const ref = this.paneRemoteRef(persistKey, live)
+ if (ref.kind === 'unreachable') return { ok: false, reason: 'not-connected' }
+ const target = sessionName(persistKey)
+ const chunk = { kind: 'keys' as const, data }
+ try {
+ if (ref.kind === 'remote') {
+ const ssh = findSsh()
+ if (!ssh) return { ok: false, reason: 'no-ssh' }
+ const plan = remoteControlInputPlan(ref.conn, ref.controlPath, target, chunk)
+ if (!plan) return { ok: false, reason: 'failed' }
+ return (await runPasteDelivery(plan, (a, i) => runWithStdin(ssh, a, i)))
+ ? { ok: true }
+ : { ok: false, reason: 'failed' }
+ }
+ const tmuxPath = this.tmuxPath
+ if (!tmuxPath) return { ok: false, reason: 'unsupported-backend' }
+ const plan = controlInputPlan(TMUX_SOCKET, target, chunk)
+ if (!plan) return { ok: false, reason: 'failed' }
+ return (await runPasteDelivery(plan, (a, i) => runWithStdin(tmuxPath, a, i)))
+ ? { ok: true }
+ : { ok: false, reason: 'failed' }
+ } catch {
+ return { ok: false, reason: 'failed' }
+ }
+ }
+
/**
* Write `text` + Enter into an agent's composer ONLY when that composer is empty — the app's own
* unsolicited notes (the context-link discovery note, a sticky note pushed over a note link).
@@ -6576,11 +6642,20 @@ export class PtyManager {
* session registered with `sshRemote` is queried on the REMOTE tmux over the project's
* ControlMaster (`remotePaneCommandArgs`); everything else asks the local socket.
*/
- async paneCommand(persistKey: string): Promise<string | null> {
+ async paneCommand(persistKey: string, opts?: { resolveUnmounted?: boolean }): Promise<string | null> {
const target = sessionName(persistKey)
const live = this.liveSessionForPersistKey(persistKey)
if (this.isZellij(persistKey, live)) return this.zellijPaneCommand(target)
- const sshRemote = live?.sshRemote
+ // Legacy (default): the live session's own master, else local. `resolveUnmounted` (bulk pause)
+ // opts in to the persisted-index resolution; other callers (messaging, terminateForeground)
+ // still act on the live session's route only, so they must not be told a host owner they
+ // cannot then write to.
+ let sshRemote: { conn: SshConnection; controlPath: string } | undefined = live?.sshRemote
+ if (opts?.resolveUnmounted === true) {
+ const ref = this.paneRemoteRef(persistKey, live)
+ if (ref.kind === 'unreachable') return null
+ sshRemote = ref.kind === 'remote' ? { conn: ref.conn, controlPath: ref.controlPath } : undefined
+ }
if (sshRemote) {
const ssh = findSsh()
if (!ssh) return null
@@ -6869,14 +6944,23 @@ export class PtyManager {
* sibling builder does. That is safe only because `sessionName()` sanitises to `[A-Za-z0-9_-]`
* before it ever gets here — the guarantee lives THERE, not in this call.
*/
- async paneOwner(persistKey: string): Promise<PaneOwner | null> {
+ async paneOwner(persistKey: string, opts?: { resolveUnmounted?: boolean }): Promise<PaneOwner | null> {
const target = sessionName(persistKey)
const live = this.liveSessionForPersistKey(persistKey)
// Agent messaging is refused into a Zellij pane (ZELLIJ_BACKEND_GAPS): null = "could not
// prove the owner", which every messaging gate already reads as a refusal.
if (this.isZellij(persistKey, live)) return null
if (live?.nativeWindowsPane) return live.nativeWindowsPane.owner()
- const sshRemote = live?.sshRemote
+ // Legacy (default): the live session's own master, else local. `resolveUnmounted` (bulk pause)
+ // opts in to the persisted-index resolution; other callers (messaging, terminateForeground)
+ // still act on the live session's route only, so they must not be told a host owner they
+ // cannot then write to.
+ let sshRemote: { conn: SshConnection; controlPath: string } | undefined = live?.sshRemote
+ if (opts?.resolveUnmounted === true) {
+ const ref = this.paneRemoteRef(persistKey, live)
+ if (ref.kind === 'unreachable') return null
+ sshRemote = ref.kind === 'remote' ? { conn: ref.conn, controlPath: ref.controlPath } : undefined
+ }
try {
if (sshRemote) {
// ONE round-trip, not two (issue #460): under a saturated or dead ControlMaster every
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index 3a1c05635..0489f68b1 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -298,6 +298,8 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
// A host filesystem path, not a view of the terminal — a viewer's file links keep the node cwd.
IPC.ptyPaneCwd,
IPC.ptyTerminateForeground,
+ // Also HOST_ONLY (host-control.ts): refused for every relay peer before this table is read.
+ IPC.ptySendPaneKeys,
IPC.ptyReadSessionName,
// Executes an agent launch and reads a host-local prompt file. Also HOST-ONLY for every peer
// (shared/host-control.ts); a relay tab never sends it (its terminals are not `source: 'local'`).
diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.ts
index 1489221f9..a35be6cf9 100644
--- a/src/core/relay/scoped-guest-policy.ts
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -444,6 +444,8 @@ export const SCOPED_REFUSED: ReadonlySet<string> = new Set<string>([
// Host-only for every peer (shared/host-control.ts): it would type a launch on the host and read
// a host-local prompt file into it. A relay tab never sends it.
IPC.ptyExecuteLaunch,
+ // Types into a pane by node id; HOST_ONLY, and relay-api.ts stubs it.
+ IPC.ptySendPaneKeys,
// Project settings / setup / trust: relay-api.ts keeps these LOCAL; the setup ones are host-only.
IPC.projectSettingsRead,
IPC.projectSettingsWriteShared,
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 566d254de..60f3bdfce 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -116,10 +116,11 @@ const api: NodeTerminalApi = {
sendToEmptyPrompt: (persistKey, text, agentId) =>
ipcRenderer.invoke(IPC.ptySendToEmptyPrompt, persistKey, text, agentId),
tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),
- paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),
+ paneCommand: (persistKey, opts) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey, opts),
paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),
+ sendPaneKeys: (nodeId, data) => ipcRenderer.invoke(IPC.ptySendPaneKeys, nodeId, data),
launchHeadless: (req) => ipcRenderer.invoke(IPC.ptyLaunchHeadless, req),
- paneOwner: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneOwner, persistKey),
+ paneOwner: (persistKey, opts) => ipcRenderer.invoke(IPC.ptyPaneOwner, persistKey, opts),
executeLaunch: (persistKey, request) => ipcRenderer.invoke(IPC.ptyExecuteLaunch, persistKey, request),
terminateForeground: (persistKey, expectedAgentId) =>
ipcRenderer.invoke(IPC.ptyTerminateForeground, persistKey, expectedAgentId),
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 2f50f7fa6..d13da27fb 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -31,7 +31,7 @@
// calls `buildRelayApi` while the approval dialog is still open, THEN awaits `ready()`. Building
// it after approval already fired leaves `ready()` pending forever and the api never comes up.
-import type { HostedRole, NodeTerminalApi } from '../../shared/types'
+import type { HostedRole, NodeTerminalApi, PaneKeysResult } from '../../shared/types'
import { type FrameTransport, RelayFrameTransport } from './frame-transport'
import { RoleGatedRpcClient } from './hosted-gate'
import { emitLocalRelayClose } from './relay-local-close'
@@ -125,6 +125,8 @@ export function buildRelayApi(
// channel, so subscribe on the local preload, same shape as a local pty.
pty: {
...real.pty,
+ // Host-only: a relay tab never types into the host's panes by id.
+ sendPaneKeys: async () => ({ ok: false, reason: 'unsupported-backend' }) as PaneKeysResult,
// On the NAMESPACED key main delivers relay output on — never the bare host id, which is a
// LOCAL terminal's channel too (shared/relay-pty-channel.ts).
onData: (sessionId, listener) => local.pty.onData(relayPtyDataKey(connectionId, sessionId), listener)
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index c05a69aea..51f4019cf 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -59,6 +59,7 @@ import {
type GitApi,
type MemInfo,
type NodeTerminalApi,
+ type PaneKeysResult,
type PresenceApi,
type PtyApi,
type PtyCreateOptions,
@@ -303,20 +304,23 @@ export function buildRealApi(
.catch(() => ({ available: false, installCommand: null, installLabel: null, platform: null, persistence: null })) as Promise<TmuxStatus>,
// Unknown on failure (null), never a rejection: the restart poller reads null as "not a
// shell yet" and gives up on its own deadline.
- paneCommand: (persistKey) =>
- client.request(IPC.ptyPaneCommand, persistKey).catch(() => null) as Promise<string | null>,
+ paneCommand: (persistKey, opts) =>
+ client.request(IPC.ptyPaneCommand, persistKey, opts).catch(() => null) as Promise<string | null>,
// Real: core registers it. Unknown (null) on failure — a relay host refuses it to a non-editor
// (EDITOR_ONLY), which reads as "no live cwd" and file links keep the node's launch cwd.
paneCwd: (persistKey) =>
client.request(IPC.ptyPaneCwd, persistKey).catch(() => null) as Promise<string | null>,
+ // Real: core registers it (host-only; a relay host refuses it). Never rejects.
+ sendPaneKeys: (nodeId, data) =>
+ client.request(IPC.ptySendPaneKeys, nodeId, data).catch(() => ({ ok: false, reason: 'failed' })) as Promise<PaneKeysResult>,
// Documented degrade (#925): the Server Edition starts nodes through its HeadlessNodeFactory,
// never through the browser renderer, so there is nothing for this to call.
launchHeadless: () => unsupported('pty.launchHeadless'),
// A REAL implementation, not a stub: core registers the handler, so the server this browser is
// served from answers it. The hibernation exit fails CLOSED on a null, so a stub here would
// have silently switched Eco off for the whole Server Edition rather than degrade it.
- paneOwner: (persistKey) =>
- client.request(IPC.ptyPaneOwner, persistKey).catch(() => null) as Promise<PaneOwner | null>,
+ paneOwner: (persistKey, opts) =>
+ client.request(IPC.ptyPaneOwner, persistKey, opts).catch(() => null) as Promise<PaneOwner | null>,
terminateForeground: (persistKey, expectedAgentId) =>
client.request(IPC.ptyTerminateForeground, persistKey, expectedAgentId).catch(() => false) as Promise<boolean | 'unsupported'>,
// REAL: core registers it, so a server running on Windows answers with its own session host.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 749e698b0..ca90c049e 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -504,6 +504,22 @@ import {
} from '../lib/explorerPinHint'
import { sameSshEndpoint, setKanbanPublishHook, setStoredCanvasPublishHook, useProjects } from '../state/projects'
import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'
+import { usePendingPause, startPendingPauseWatcher } from '../state/pendingPause'
+import {
+ planBulkPause,
+ bulkPauseConfirmText,
+ bulkPauseResultText,
+ describeSkips,
+ paneRouteProjectId,
+ type BulkPauseTarget
+} from '../lib/bulkPause'
+import {
+ pauseNodeHeadless,
+ createHostLimiter,
+ BULK_PAUSE_HOST_CAP,
+ type HeadlessPauseDeps
+} from '../terminal/headless-pause'
+import { binariesFor } from '@shared/agents/pane-owner-predicate'
import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'
import { chatPaneRefusal } from '../lib/chatPaneGate'
import { runQueuedNotice } from '../lib/boardRunQueued'
@@ -519,6 +535,7 @@ import type { NormalizedAgentEvent } from '@shared/agents/normalize'
import {
computeWorktreePath,
resolveWorktreePath,
+ descendantIds,
displacedByWorktree,
effectiveWorktreeBaseRef,
effectiveWorktreeTemplate,
@@ -1017,6 +1034,11 @@ type LinkOpen = Extract<OpenLinkAcceptResult, { ok: true }>['open']
/** An accepted link waiting for its project to load is dropped after this (see pendingLinkRef). */
const PENDING_LINK_MAX_MS = 30_000
+/** The ONE bulk-pause limiter: the batch path and the pending-pause watcher both run their exits
+ * through it, so the per-host cap (BULK_PAUSE_HOST_CAP) holds across the two. Module-level
+ * because the canvas is mounted once. */
+const hostLimiter = createHostLimiter(BULK_PAUSE_HOST_CAP)
+
/** The confirm dialogs, named so their setters can be wrapped in a synchronous open-guard (see
* `confirmFlags`): ONE confirm at a time, decided at call time rather than at the next render. */
interface ConfirmState {
@@ -6967,7 +6989,10 @@ export function Canvas() {
// RECYCLE, not DESTROY: the node is NOT deleted — it stays on the canvas (here and on
// every co-viewer's) and respawns into the fallback cwd. `destroy` would cast "closed
// by <name>" to co-viewers, permanently bricking their still-present node.
- if (n.type === 'terminal') transport.recycle(n.id)
+ if (n.type === 'terminal') {
+ transport.recycle(n.id)
+ usePendingPause.getState().remove([n.id]) // the recycled session's CLI is gone with it
+ }
}
}
setNodes((ns) =>
@@ -7179,6 +7204,8 @@ export function Canvas() {
const deleteNodes = useCallback(
(ids: string[], opts?: { record?: boolean }) => {
const set = new Set(ids)
+ // A pending "pause after this turn" has nothing left to pause.
+ usePendingPause.getState().remove(ids)
if (opts?.record !== false) {
const deletedAt = Date.now()
// Keyed by node id, not by array position: `closedEntries` and `snapshots` below each run
@@ -8160,6 +8187,7 @@ export function Canvas() {
// would be bricked until they deleted and re-added it. `recycle` tells them to restart onto the
// replacement session instead, so they follow the node into its new cwd.
transport.recycle(id)
+ usePendingPause.getState().remove([id]) // the recycled session's CLI is gone with it
setNodes((ns) =>
ns.map((n) =>
n.id === id
@@ -8267,6 +8295,9 @@ export function Canvas() {
: targetAgentId
? 'Reopen'
: 'Restart'
+ // A restart (any variant: model switch, reopen as, fresh shell) replaces the CLI the pending
+ // "pause after this turn" mark was taken against.
+ usePendingPause.getState().remove([nodeId])
let outcome: RestartOutcome
try {
outcome = await fn(targetAgentId, targetModel, restartShell, clearEnv)
@@ -8453,12 +8484,295 @@ export function Canvas() {
})
return
}
+ // A Resume overrides a queued "pause after this turn" — the user wants it running.
+ usePendingPause.getState().remove([nodeId])
wakeHibernatedNode(nodeId)
// The trigger is fire-and-forget (it owns its own retries and clears `hibernated`/`paused` on
// a confirmed resume), so this is deliberately a status line, not a result.
setNotice({ kind: 'info', text: 'Resuming…' })
}, [])
+ // ---- Bulk pause (a project, a group frame, a multi-selection) ----
+ // One path for mounted AND unmounted nodes: `headless-pause.ts` drives the same
+ // `performExitPhase` the node menu and Eco use, over `pty.sendPaneKeys` by node id, under the
+ // same `guardConcurrentRestart` lock single Pause, Eco and wake hold. Shallow only — the tmux
+ // pane and its scrollback stay. Busy sessions are never typed into: they get a transient
+ // "pause after this turn" mark the watcher below fires on their next clean `done`.
+ /** The project that owns a node: the one React Flow holds when the node is on the live canvas
+ * (its stored copy lags), else the stored owner. */
+ const owningProjectOf = useCallback(
+ (id: string) => {
+ const projects = useProjects.getState().projects
+ const live = nodesRef.current.some((n) => n.id === id)
+ return live && nodesProjectIdRef.current
+ ? projects.find((x) => x.id === nodesProjectIdRef.current)
+ : nodeOwner(projects, id)
+ },
+ [nodesRef, nodesProjectIdRef]
+ )
+ // Core-bound `pty` comes from the node's OWNING project's session (grep gate), not the global.
+ // No owner, or a relay owner, means no route at all (`paneRouteProjectId`): never a guess at the
+ // active project, which could be a relay tab whose session types into another machine's pane.
+ const ptyFor = useCallback(
+ (id: string) => {
+ const projectId = paneRouteProjectId(owningProjectOf(id))
+ return projectId === null ? null : sessionForProject(projectId).api.pty
+ },
+ [owningProjectOf]
+ )
+ const headlessPauseDeps = useMemo<HeadlessPauseDeps>(
+ () => ({
+ sendPaneKeys: async (id, d) =>
+ (await ptyFor(id)?.sendPaneKeys(id, d)) ?? { ok: false, reason: 'not-connected' },
+ // `resolveUnmounted`: the default answers only for a node with a LIVE pty client, and most
+ // nodes a project-wide pause reaches are not mounted (another project, offscreen-released).
+ // No route answers null, which the runner reports as "couldn't verify the agent in its pane".
+ paneCommand: async (id) => (await ptyFor(id)?.paneCommand(id, { resolveUnmounted: true })) ?? null,
+ paneOwner: async (id) => (await ptyFor(id)?.paneOwner(id, { resolveUnmounted: true })) ?? null,
+ status: (id) => useAgentStatus.getState().byId[id],
+ binaries: (agentId) => binariesFor(agentId, useSettings.getState().settings.customAgents),
+ // Gone from BOTH the live canvas and the stored projects. For the project React Flow holds,
+ // the live array is the truth: its stored copy lags a delete until the next commit.
+ stillExists: (id) => {
+ if (nodesRef.current.some((n) => n.id === id)) return true
+ const owner = nodeOwner(useProjects.getState().projects, id)
+ return !!owner && owner.id !== nodesProjectIdRef.current
+ },
+ // Mirrors the mounted shallow-pause closure (TerminalNode `registerAgentPause`): an exit we
+ // performed records the wake context + `hibernated`; an already-exited (Eco) node only gains
+ // `paused` — its recorded wake context is already right and must survive.
+ markPaused: (id, { alreadyExited, wake }) => {
+ const s = useAgentStatus.getState()
+ if (!alreadyExited) {
+ s.setHibernatedContext(id, wake)
+ s.setHibernated(id, true)
+ }
+ s.setPaused(id, true)
+ }
+ }),
+ [nodesRef, nodesProjectIdRef, ptyFor]
+ )
+
+ /** Terminal nodes as bulk-pause targets, each with the project that owns it (relay tabs are
+ * refused by the planner; SSH projects get their own host-cap key). */
+ const bulkPauseTargets = useCallback(
+ (ids: readonly string[]): BulkPauseTarget[] => {
+ const byId = useAgentStatus.getState().byId
+ return ids.flatMap((id): BulkPauseTarget[] => {
+ const live = nodesRef.current.find((n) => n.id === id)
+ const p = owningProjectOf(id)
+ const stored = live ? undefined : p?.nodes.find((n) => n.id === id)
+ const isTerminal = live ? live.type === 'terminal' : stored?.kind === 'terminal'
+ if (!isTerminal) return []
+ const agentId =
+ (live ? (live.data?.agentId as string | undefined) : stored?.agentId) ?? byId[id]?.agentId
+ return [{ nodeId: id, agentId, relay: !!p?.remote, hostKey: p?.ssh ? p.id : 'local' }]
+ })
+ },
+ [nodesRef, owningProjectOf]
+ )
+
+ /** A promise over Canvas's one ConfirmDialog. A dialog already up (an agent's destructive
+ * verb, a removal) is never replaced: the bulk pause answers "not now" instead. */
+ const confirmBulkPause = useCallback(
+ (message: string): Promise<boolean> =>
+ new Promise((resolve) => {
+ if (confirmBusy()) {
+ setNotice({ kind: 'error', text: 'Another confirmation is open — answer it, then pause again.' })
+ resolve(false)
+ return
+ }
+ setConfirm({
+ message,
+ confirmLabel: 'Pause',
+ onConfirm: () => {
+ setConfirm(null)
+ resolve(true)
+ },
+ onCancel: () => resolve(false)
+ })
+ }),
+ [confirmBusy, setConfirm]
+ )
+
+ const pauseNodes = useCallback(
+ async (ids: readonly string[], scopeLabel: string): Promise<void> => {
+ const plan = planBulkPause(bulkPauseTargets(ids), (id) => useAgentStatus.getState().byId[id])
+ const actionable = plan.now.length + plan.alreadyExited.length + plan.whenDone.length
+ if (actionable === 0) {
+ setNotice({
+ kind: 'info',
+ text: plan.skip.length
+ ? `Nothing to pause in ${scopeLabel} (${describeSkips(plan.skip)}).`
+ : `Nothing to pause in ${scopeLabel}.`
+ })
+ return
+ }
+ const ok = await confirmBulkPause(bulkPauseConfirmText(scopeLabel, plan))
+ if (!ok) return
+ usePendingPause.getState().add(plan.whenDone)
+ // EVERY outcome is counted: a node that is neither paused nor pending must still reach the
+ // summary, or a batch against a disconnected SSH host reads as "Paused 0" and nothing else.
+ const counts = {
+ paused: 0, deferred: 0, unreachable: 0, unverified: 0, notEligible: 0, timeout: 0, failed: 0
+ }
+ await Promise.all(
+ [
+ ...plan.alreadyExited.map((t) => [t, true] as const),
+ ...plan.now.map((t) => [t, false] as const)
+ ].map(([t, exited]) =>
+ hostLimiter
+ .run(t.hostKey, () => pauseNodeHeadless(t, exited, headlessPauseDeps))
+ .then((o) => {
+ if (o === 'paused') counts.paused++
+ else if (o === 'exit-timeout') counts.timeout++
+ else if (o === 'unreachable') counts.unreachable++
+ else if (o === 'unverified') counts.unverified++
+ else if (o === 'not-eligible') counts.notEligible++
+ else if (o === 'deferred') {
+ // Became busy between the plan and its turn in the queue: pause after this turn.
+ counts.deferred++
+ usePendingPause.getState().add([t])
+ }
+ })
+ .catch(() => {
+ counts.failed++
+ })
+ )
+ )
+ setNotice(
+ bulkPauseResultText({
+ paused: counts.paused,
+ pending: plan.whenDone.length + counts.deferred,
+ unreachable: counts.unreachable,
+ unverified: counts.unverified,
+ notEligible: counts.notEligible,
+ timeout: counts.timeout,
+ failed: counts.failed,
+ skipped: plan.skip.length
+ })
+ )
+ },
+ [bulkPauseTargets, confirmBulkPause, headlessPauseDeps]
+ )
+
+ // The ONE watcher for "pause after this turn" marks, for the life of the canvas: a node whose
+ // turn ends cleanly is exited headlessly; one that turned busy again in between is re-queued.
+ useEffect(
+ () =>
+ startPendingPauseWatcher((t) => {
+ // Through the SAME limiter as the batch: a burst of turns ending together must not put
+ // more than BULK_PAUSE_HOST_CAP exits in flight on one host.
+ void hostLimiter
+ .run(t.hostKey, () => pauseNodeHeadless(t, false, headlessPauseDeps))
+ .then((o) => {
+ if (o === 'deferred') usePendingPause.getState().add([t])
+ })
+ .catch(() => {})
+ }),
+ [headlessPauseDeps]
+ )
+
+ /** A project's terminal node ids: the live array for the project React Flow holds, else the
+ * stored copy. */
+ const projectTerminalIds = useCallback(
+ (projectId: string): string[] =>
+ projectId === nodesProjectIdRef.current
+ ? nodesRef.current.filter((n) => n.type === 'terminal').map((n) => n.id)
+ : (useProjects.getState().getProject(projectId)?.nodes ?? [])
+ .filter((n) => n.kind === 'terminal')
+ .map((n) => n.id),
+ [nodesRef, nodesProjectIdRef]
+ )
+
+ const projectScopeLabel = (projectId: string): string =>
+ `project "${useProjects.getState().getProject(projectId)?.name ?? projectId}"`
+
+ const cancelPendingPauses = useCallback(
+ (projectId: string) => {
+ const ids = projectTerminalIds(projectId).filter((id) => id in usePendingPause.getState().byId)
+ usePendingPause.getState().remove(ids)
+ setNotice({
+ kind: 'info',
+ text: `Cancelled ${ids.length} pending ${ids.length === 1 ? 'pause' : 'pauses'}.`
+ })
+ },
+ [projectTerminalIds]
+ )
+
+ /** Resume every PAUSED session of the active project through the same `resumeAgentNode` a single
+ * Resume uses. Each wake is fire-and-forget (the trigger owns its retries and the
+ * guardConcurrentRestart lock), so this starts them all and does not wait. Only the active
+ * project: resume types into a MOUNTED terminal (echo-verified, input buffered), and only that
+ * project's nodes are mounted. Each call raises its own "Resuming…" line; the summary below is
+ * set after the loop, so it is the one left on screen. */
+ const resumeAllInActiveProject = useCallback(() => {
+ if (useProjects.getState().activeProjectId !== nodesProjectIdRef.current) {
+ // Mid-switch: the live array still holds the outgoing project's nodes.
+ setNotice({ kind: 'error', text: 'Resume all skipped: the project is still loading — try again.' })
+ return
+ }
+ const byId = useAgentStatus.getState().byId
+ const paused = nodesRef.current.filter((n) => n.type === 'terminal' && byId[n.id]?.paused)
+ let resumed = 0
+ let detached = 0
+ for (const n of paused) {
+ if (!agentHibernateFns(n.id)) {
+ detached++
+ continue
+ }
+ resumeAgentNode(n.id)
+ resumed++
+ }
+ setNotice({
+ kind: detached ? 'error' : 'info',
+ text:
+ paused.length === 0
+ ? 'Nothing is paused in this project.'
+ : `Resuming ${resumed}` +
+ (detached ? ` · ${detached} not attached (bring them into view, then Resume)` : '')
+ })
+ }, [nodesRef, nodesProjectIdRef, resumeAgentNode])
+
+ const resumeAllProject = useCallback(
+ (projectId: string) => {
+ if (projectId === useProjects.getState().activeProjectId) resumeAllInActiveProject()
+ },
+ [resumeAllInActiveProject]
+ )
+
+ /** The three project rows, for the sessions-sidebar project menu (the tab bar draws its own). */
+ const projectPauseItems = useCallback(
+ (projectId: string): MenuItem[] => {
+ const pending = projectTerminalIds(projectId).some((id) => id in usePendingPause.getState().byId)
+ const active = projectId === useProjects.getState().activeProjectId
+ return [
+ {
+ label: 'Pause project',
+ icon: <IconPower />,
+ onClick: () => void pauseNodes(projectTerminalIds(projectId), projectScopeLabel(projectId))
+ },
+ ...(pending
+ ? [
+ {
+ label: 'Cancel pending pauses',
+ icon: <IconPower />,
+ onClick: () => cancelPendingPauses(projectId)
+ } as MenuItem
+ ]
+ : []),
+ {
+ label: 'Resume all',
+ icon: <IconPower />,
+ disabled: !active,
+ ...(active ? {} : { hint: 'Open the project to resume' }),
+ onClick: () => resumeAllProject(projectId)
+ }
+ ]
+ },
+ [projectTerminalIds, pauseNodes, cancelPendingPauses, resumeAllProject]
+ )
+
// S6 §3.5 — originate an owner-authorized Codex account SWITCH for a running node, then recycle
// its pane onto the target account. The renderer is NOT the security boundary: PR 5's three-phase
// handler is owner-authorized (only the WebContents that reserved may commit/finish) and refuses a
@@ -8557,6 +8871,7 @@ export function Canvas() {
})
return
}
+ usePendingPause.getState().remove([nodeId]) // the switch restarts the CLI
const fn = agentRestartFn(nodeId)
// The rebind rides the closure's own node update (`beforeRecycle`), so the respawn is
// guaranteed to launch under the target account — a separate setNodes in the same tick can
@@ -8614,6 +8929,7 @@ export function Canvas() {
)
)
markDirty()
+ usePendingPause.getState().remove([nodeId]) // the switch restarts the CLI
const fn = agentRestartFn(nodeId)
const outcome = fn ? await settleRestart(() => fn(undefined, undefined, true)) : 'not-eligible'
await codexApi.finishSwitch(token)
@@ -8687,6 +9003,7 @@ export function Canvas() {
if (!projectId) return { kind: 'refused', reason: 'no-connection' }
ctx = { projectId }
}
+ usePendingPause.getState().remove([nodeId]) // the switch restarts the CLI
const fn = agentRestartFn(nodeId)
if (!fn) return { kind: 'refused', reason: 'not-attached' }
const { plan } = decision
@@ -8862,6 +9179,7 @@ export function Canvas() {
id,
hostKey: nodeHostKey,
run: async () => {
+ usePendingPause.getState().remove([id]) // a restart replaces the CLI a mark waited on
const fn = agentRestartFn(id)
return fn ? await settleRestart(fn) : 'not-eligible'
}
@@ -10551,6 +10869,7 @@ export function Canvas() {
transferConversation,
restartAgentNode,
pauseAgentNode,
+ pauseNodes: (ids) => void pauseNodes(ids, `${ids.length} sessions`),
resumeAgentNode,
switchClaudeAccountNode,
switchCodexAccountNode,
@@ -10577,6 +10896,7 @@ export function Canvas() {
transferConversation,
restartAgentNode,
pauseAgentNode,
+ pauseNodes,
resumeAgentNode,
switchClaudeAccountNode,
switchCodexAccountNode,
@@ -10934,6 +11254,18 @@ export function Canvas() {
hint: lineageRefusal ?? 'One row per level: who opened whom, top to bottom.',
onClick: () => arrangeGroupAction(groupId, 'lineage')
},
+ {
+ // Every agent session inside the frame, nested frames included (the planner skips
+ // non-agents and says so in the confirm).
+ label: 'Pause group',
+ icon: <IconPower />,
+ hint: 'Quits each agent CLI in this group; busy ones pause after their current turn.',
+ onClick: () =>
+ void pauseNodes(
+ [...descendantIds(nodesRef.current, groupId)],
+ `group "${String(nodesRef.current.find((n) => n.id === groupId)?.data?.title ?? 'group')}"`
+ )
+ },
{ type: 'separator' },
...(isHidden('colors', useSettings.getState().settings.hiddenNodeMenuItems)
? []
@@ -10973,7 +11305,8 @@ export function Canvas() {
addToExistingGroup,
groupSelection,
groupArrangeHint,
- arrangeGroupAction
+ arrangeGroupAction,
+ pauseNodes
]
)
@@ -15897,6 +16230,7 @@ export function Canvas() {
(projectId: string, ids: readonly string[]) => {
const store = useProjects.getState()
const nodes = store.getProject(projectId)?.nodes ?? []
+ usePendingPause.getState().remove([...ids])
for (const id of ids) {
// A deleted frame's children SURVIVE it (deleteNodes frees them to absolute positions).
// `moveNodeToGroup(…, null)` is the serialized twin of that conversion — without it the
@@ -17514,6 +17848,8 @@ export function Canvas() {
})()
: []),
{ type: 'separator' },
+ ...projectPauseItems(projectId),
+ { type: 'separator' },
{ type: 'colors', onPick: (color) => setProjectColor(projectId, color) },
{ type: 'separator' },
{
@@ -17534,7 +17870,8 @@ export function Canvas() {
closeProject,
openProjectSettings,
shareBlockedReason,
- openShareWithTeam
+ openShareWithTeam,
+ projectPauseItems
]
)
@@ -18831,6 +19168,9 @@ export function Canvas() {
onOpenProjectSettings={openProjectSettings}
onShareWithTeam={openShareWithTeam}
shareBlockedReason={shareBlockedReason}
+ onPauseProject={(id) => void pauseNodes(projectTerminalIds(id), projectScopeLabel(id))}
+ onCancelPendingPauses={cancelPendingPauses}
+ onResumeAllProject={resumeAllProject}
/>
<div className="top-banners">
diff --git a/src/renderer/canvas/bulk-pause-wiring.test.ts b/src/renderer/canvas/bulk-pause-wiring.test.ts
new file mode 100644
index 000000000..1c958d7c8
--- /dev/null
+++ b/src/renderer/canvas/bulk-pause-wiring.test.ts
@@ -0,0 +1,93 @@
+// Source pins for the bulk pause wiring: every entry point (tab menu, sessions-sidebar project
+// menu, group frame menu, multi-selection node menu) must route through Canvas's ONE `pauseNodes`,
+// and the pending-pause watcher must be started exactly once — a second watcher would fire every
+// pending pause twice.
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+const canvas = readFileSync('src/renderer/canvas/Canvas.tsx', 'utf8').replace(/\r\n/g, '\n')
+const tabbar = readFileSync('src/renderer/components/TabBar.tsx', 'utf8').replace(/\r\n/g, '\n')
+const actions = readFileSync('src/renderer/lib/nodeActionItems.tsx', 'utf8').replace(/\r\n/g, '\n')
+
+describe('bulk pause wiring', () => {
+ it('every entry point goes through pauseNodes', () => {
+ expect(canvas).toMatch(/onPauseProject=\{[^}]*pauseNodes/)
+ expect(canvas).toMatch(/label: 'Pause group'[\s\S]{0,300}pauseNodes\(/)
+ expect(actions).toMatch(/ctx\.pauseNodes\(/)
+ expect(canvas).toMatch(/pauseNodes: \(ids\) => void pauseNodes\(/)
+ })
+ it('the pending watcher is started once in Canvas', () => {
+ expect(canvas.match(/startPendingPauseWatcher\(/g)?.length).toBe(1)
+ })
+ it('tab menu offers the three rows', () => {
+ for (const s of ['Pause project', 'Cancel pending pauses', 'Resume all']) expect(tabbar).toContain(s)
+ })
+ it('resume all is limited to the active project', () => {
+ expect(tabbar).toContain('Open the project to resume')
+ })
+ it('the sessions-sidebar project menu carries the same three rows', () => {
+ // The sidebar's project-header menu is built in Canvas (`onProjectContextMenu`), so the rows
+ // come from the one builder the tab handlers also use.
+ const m = canvas.match(/const onProjectContextMenu = useCallback\([\s\S]*?\n {2}\)\n/)
+ expect(m?.[0]).toContain('projectPauseItems(')
+ expect(canvas).toMatch(/const projectPauseItems = useCallback/)
+ for (const s of ["'Pause project'", "'Cancel pending pauses'", "'Resume all'"]) expect(canvas).toContain(s)
+ })
+ it('node delete funnels and resume drop the pending mark', () => {
+ for (const fn of ['const deleteNodes = useCallback', 'const closeStoredNodes = useCallback', 'const resumeAgentNode = useCallback']) {
+ const i = canvas.indexOf(fn)
+ expect(i, fn).toBeGreaterThan(-1)
+ expect(canvas.slice(i, i + 4000), fn).toContain('usePendingPause.getState().remove(')
+ }
+ })
+ it('every funnel that restarts or replaces the CLI drops the pending mark', () => {
+ // A pending "pause after this turn" was taken against one CLI session; a restart, model switch,
+ // reopen-as, account switch or recycle replaces it, and a mark left behind would quit the NEW
+ // session on its first turn end.
+ for (const fn of [
+ 'const restartAgentNode = useCallback',
+ 'const switchCodexAccountNode = useCallback',
+ 'const runClaudeAccountSwitch = useCallback',
+ 'const restartIdleAgents = useCallback',
+ 'const resetDisplacedCwd = useCallback'
+ ]) {
+ const i = canvas.indexOf(fn)
+ expect(i, fn).toBeGreaterThan(-1)
+ expect(canvas.slice(i, i + 6000), fn).toContain('usePendingPause.getState().remove(')
+ }
+ // Every `transport.recycle(` site in Canvas is followed by the removal.
+ const sites = [...canvas.matchAll(/transport\.recycle\(([^)]+)\)/g)]
+ expect(sites.length).toBeGreaterThan(0)
+ for (const m of sites) {
+ expect(canvas.slice(m.index!, m.index! + 200), m[0]).toContain('usePendingPause.getState().remove(')
+ }
+ })
+ it('the batch summary counts every outcome through bulkPauseResultText', () => {
+ const i = canvas.indexOf('const pauseNodes = useCallback')
+ const body = canvas.slice(i, i + 5000)
+ expect(body).toContain('bulkPauseResultText(')
+ expect(body).toContain("o === 'unverified'")
+ expect(body).toContain("o === 'not-eligible'")
+ })
+ it('headless pane reads opt into resolving unmounted panes', () => {
+ expect(canvas).toMatch(/paneCommand\(id, \{ resolveUnmounted: true \}\)/)
+ expect(canvas).toMatch(/paneOwner\(id, \{ resolveUnmounted: true \}\)/)
+ })
+ it('batch and watcher share ONE host limiter (the 3-per-host cap holds across both)', () => {
+ expect(canvas.match(/createHostLimiter\(/g)?.length).toBe(1)
+ expect(canvas).toMatch(/createHostLimiter\(BULK_PAUSE_HOST_CAP\)/)
+ const w = canvas.indexOf('startPendingPauseWatcher((')
+ expect(canvas.slice(w, w + 600)).toMatch(/hostLimiter\s*\.run\(/)
+ expect(canvas).not.toMatch(/runWithHostCap\(/)
+ expect(readFileSync('src/renderer/terminal/headless-pause.ts', 'utf8')).not.toContain('runWithHostCap')
+ })
+ it('resume all says why when the canvas is mid-switch', () => {
+ expect(canvas).toContain('Resume all skipped: the project is still loading')
+ })
+ it('pane traffic is routed only through the owning project, never a guess at the active one', () => {
+ const start = canvas.indexOf('const ptyFor = useCallback(')
+ expect(start).toBeGreaterThan(-1)
+ const body = canvas.slice(start, canvas.indexOf('[owningProjectOf]', start))
+ expect(body).toContain('paneRouteProjectId(owningProjectOf(id))')
+ expect(body).not.toContain('activeProjectId')
+ })
+})
diff --git a/src/renderer/canvas/node-menu-golden.source.test.ts b/src/renderer/canvas/node-menu-golden.source.test.ts
index 2d914693e..db032acbb 100644
--- a/src/renderer/canvas/node-menu-golden.source.test.ts
+++ b/src/renderer/canvas/node-menu-golden.source.test.ts
@@ -52,6 +52,7 @@ const GOLDEN_STRINGS = [
'Pause & end session',
'Pause session',
'Quits Claude, moves this conversation to the account and resumes it there — no login needed.',
+ 'Quits each CLI; busy ones pause after their current turn. Resume brings each back.',
'Quits the CLI and ends its tmux session too, for a fuller memory reclaim. Resume starts a fresh session with the same conversation.',
'Quits the CLI and relaunches it with --resume (same conversation).',
'Quits the CLI, respawns a fresh shell (picks up env/profile changes), then resumes.',
@@ -87,6 +88,7 @@ const GOLDEN_STRINGS = [
const GOLDEN_TEMPLATES = [
"Add selection to ${targetGroup.data.title || 'group'}",
+ 'Pause ${agents.length} sessions',
'Quits this CLI and resumes the same session as ${variant.label}.',
'Restarts the terminal session and resumes this conversation with ${model.id}.',
'Switch model (${currentModel})',
diff --git a/src/renderer/components/TabBar.test.tsx b/src/renderer/components/TabBar.test.tsx
index 8cb8d694b..42f88f44e 100644
--- a/src/renderer/components/TabBar.test.tsx
+++ b/src/renderer/components/TabBar.test.tsx
@@ -69,6 +69,7 @@ describe('TabBar caret menu', () => {
let root: Root
let host: HTMLElement
let onOpenProjectSettings: ReturnType<typeof vi.fn<(id: string) => void>>
+ let onPauseProject: ReturnType<typeof vi.fn<(id: string) => void>>
const menuButton = (label: string): HTMLButtonElement | undefined =>
Array.from(document.querySelectorAll<HTMLButtonElement>('.tab-menu button')).find(
@@ -81,6 +82,7 @@ describe('TabBar caret menu', () => {
document.body.appendChild(host)
useProjects.setState({ projects: [project()], activeProjectId: 'p1' })
onOpenProjectSettings = vi.fn<(id: string) => void>()
+ onPauseProject = vi.fn<(id: string) => void>()
root = createRoot(host)
await act(async () => {
root.render(
@@ -96,6 +98,9 @@ describe('TabBar caret menu', () => {
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={onOpenProjectSettings}
+ onPauseProject={onPauseProject}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
/>
)
})
@@ -116,6 +121,25 @@ describe('TabBar caret menu', () => {
expect(document.querySelector('.tab-menu')).toBeNull()
})
+ it('offers "Pause project" for the project it was opened on, and Resume all on the active one', async () => {
+ expect(menuButton('Resume all')?.disabled).toBe(false)
+ // Nothing is pending, so there is nothing to cancel.
+ expect(menuButton('Cancel pending pauses')).toBeUndefined()
+ await click(menuButton('Pause project')!)
+ expect(onPauseProject).toHaveBeenCalledWith('p1')
+ })
+
+ it('a disabled Resume all carries its reason on a hoverable wrapper (a disabled button shows no title)', async () => {
+ const { useProjects } = await import('../state/projects')
+ await act(async () => {
+ useProjects.setState({ projects: [project(), project({ id: 'p2', name: 'Beta' })], activeProjectId: 'p2' })
+ })
+ const b = menuButton('Resume all')!
+ expect(b.disabled).toBe(true)
+ expect(b.getAttribute('title')).toBeNull()
+ expect(b.parentElement?.getAttribute('title')).toBe('Open the project to resume')
+ })
+
it('closes on a press anywhere outside it, including the bar the menu hangs from', async () => {
// The dismiss backdrop is below the bar so a click on another tab still switches projects,
// which leaves the bar itself unable to close the menu without this.
@@ -172,6 +196,9 @@ describe('TabBar New-project pin', () => {
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={vi.fn()}
+ onPauseProject={vi.fn()}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
/>
)
})
@@ -244,6 +271,9 @@ describe('TabBar drag-reorder', () => {
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={vi.fn()}
+ onPauseProject={vi.fn()}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
/>
)
})
@@ -345,6 +375,9 @@ describe('TabBar options button', () => {
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={vi.fn()}
+ onPauseProject={vi.fn()}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
/>
)
})
@@ -401,6 +434,9 @@ describe('TabBar Share with team', () => {
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={vi.fn()}
+ onPauseProject={vi.fn()}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
{...(props.share === false ? {} : { onShareWithTeam })}
shareBlockedReason={props.blocked}
/>
@@ -514,6 +550,9 @@ describe('TabBar location tooltip', () => {
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={vi.fn()}
+ onPauseProject={vi.fn()}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
/>
)
})
@@ -606,6 +645,9 @@ describe('TabBar caret menu — "Agents may, without asking" (per-project confir
onSetDefaultAccount={vi.fn()}
onSetDefaultPermissionMode={vi.fn()}
onOpenProjectSettings={vi.fn()}
+ onPauseProject={vi.fn()}
+ onCancelPendingPauses={vi.fn()}
+ onResumeAllProject={vi.fn()}
/>
)
})
diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsx
index 08007bf14..eb55e1033 100644
--- a/src/renderer/components/TabBar.tsx
+++ b/src/renderer/components/TabBar.tsx
@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'
import { useProjects } from '../state/projects'
import { isOmniKanbanEnabled, toggleBoardView, useViewMode, viewFor } from '../state/viewMode'
import { useAgentStatus } from '../state/agentStatus'
+import { usePauseCounts } from '../state/pauseCounts'
import { useSettings } from '../state/settings'
import { accountsForProject, sshAccountsHint, systemAccountDisplay } from '../state/workspace'
import { useSshConn } from '../state/sshConn'
@@ -59,6 +60,13 @@ interface TabBarProps {
/** Why the share cannot start for this project right now (the row is then disabled with it as
* its tooltip), or null when it can. */
shareBlockedReason?: (projectId: string) => string | null
+ /** Pause every agent session in the project (Canvas `pauseNodes`: one confirm, busy ones after
+ * their current turn). */
+ onPauseProject: (id: string) => void
+ /** Drop the project's "pause after the current turn" marks. */
+ onCancelPendingPauses: (id: string) => void
+ /** Resume every PAUSED session of the ACTIVE project (offered only there). */
+ onResumeAllProject: (id: string) => void
}
/**
@@ -96,7 +104,10 @@ export function TabBar({
onSetDefaultPermissionMode,
onOpenProjectSettings,
onShareWithTeam,
- shareBlockedReason
+ shareBlockedReason,
+ onPauseProject,
+ onCancelPendingPauses,
+ onResumeAllProject
}: TabBarProps) {
// Select the raw array and filter in a memo, a `.filter()` inside the selector returns a
// fresh array every store snapshot, which re-rendered the TabBar on EVERY projects change.
@@ -118,6 +129,10 @@ export function TabBar({
return ids
})
const unreadSet = useMemo(() => new Set(unreadIds.split('|').filter(Boolean)), [unreadIds])
+ // ⏸ badge + the "Cancel pending pauses" row. Computed HERE, not in Canvas: this component
+ // already holds the projects array, and Canvas subscribing to it would re-render the whole canvas
+ // on every node serialization.
+ const pauseCounts = usePauseCounts(projects)
const [menuId, setMenuId] = useState<string | null>(null)
// `flipBase` is the ANCHOR's top edge: when the menu would overflow the bottom of the window,
// it opens upward from the caret button instead (see useMenuFlip below).
@@ -454,6 +469,16 @@ export function TabBar({
{multiSession && <TabSessionLabel projectId={p.id} />}
+ {pauseCounts[p.id] && (
+ <span
+ className="tab__paused"
+ title={`${pauseCounts[p.id].paused} paused${pauseCounts[p.id].pending ? `, ${pauseCounts[p.id].pending} pausing after their current turn` : ''}`}
+ >
+ ⏸ {pauseCounts[p.id].paused}
+ {pauseCounts[p.id].pending ? ` · ${pauseCounts[p.id].pending} pending` : ''}
+ </span>
+ )}
+
{unreadCount > 0 && (
<span className="tab__badge" title={`${unreadCount} unread`}>
{unreadCount}
@@ -752,6 +777,43 @@ export function TabBar({
Copy project id
</button>
)}
+ <button
+ onClick={() => {
+ onPauseProject(menuProject.id)
+ closeMenu()
+ }}
+ >
+ Pause project
+ </button>
+ {(pauseCounts[menuProject.id]?.pending ?? 0) > 0 && (
+ <button
+ onClick={() => {
+ onCancelPendingPauses(menuProject.id)
+ closeMenu()
+ }}
+ >
+ Cancel pending pauses
+ </button>
+ )}
+ {/* Chromium shows no `title` for a DISABLED button (it receives no pointer events), so
+ the reason sits on a wrapper the pointer can reach; the disabled button lets the
+ pointer through to it (`.tab-menu__reason > button:disabled`). */}
+ <span
+ className="tab-menu__reason"
+ title={menuProject.id !== activeId ? 'Open the project to resume' : undefined}
+ >
+ <button
+ // Resume needs each node's mounted terminal (it re-launches the CLI into the pane
+ // and guards the typing), and only the active project's nodes are mounted.
+ disabled={menuProject.id !== activeId}
+ onClick={() => {
+ onResumeAllProject(menuProject.id)
+ closeMenu()
+ }}
+ >
+ Resume all
+ </button>
+ </span>
<button
onClick={() => {
onCloseProject(menuProject.id)
diff --git a/src/renderer/lib/bulkPause.test.ts b/src/renderer/lib/bulkPause.test.ts
new file mode 100644
index 000000000..b44301079
--- /dev/null
+++ b/src/renderer/lib/bulkPause.test.ts
@@ -0,0 +1,157 @@
+import { describe, it, expect } from 'vitest'
+import {
+ planBulkPause, isBusyForPause, bulkPauseSummary, describeSkips, bulkPauseResultText, bulkPauseConfirmText,
+ paneRouteProjectId, type BulkPauseTarget
+} from './bulkPause'
+
+const t = (nodeId: string, agentId: string | undefined = 'claude', relay = false): BulkPauseTarget =>
+ ({ nodeId, agentId, relay, hostKey: 'local' })
+const SID = '11111111-2222-3333-4444-555555555555'
+
+describe('planBulkPause', () => {
+ it('a node whose CLI announced its exit is skipped as ended', () => {
+ const p = planBulkPause([t('a')], () => ({ state: undefined, sessionId: SID, sessionEnded: true }) as never)
+ expect(p.skip.map((x) => x.reason)).toEqual(['ended'])
+ expect(p.now).toHaveLength(0)
+ })
+ it('idle done agent → now', () => {
+ const p = planBulkPause([t('a')], () => ({ state: 'done', sessionId: SID }) as never)
+ expect(p.now.map((x) => x.nodeId)).toEqual(['a'])
+ })
+ it.each(['working', 'waiting', 'blocked'] as const)('%s → whenDone', (state) => {
+ const p = planBulkPause([t('a')], () => ({ state, sessionId: SID }) as never)
+ expect(p.whenDone.map((x) => x.nodeId)).toEqual(['a'])
+ })
+ it('a held ticket on a done node is busy', () => {
+ const p = planBulkPause([t('a')], () => ({ state: 'done', sessionId: SID, held: { pendingId: 'x' } }) as never)
+ expect(p.whenDone).toHaveLength(1)
+ })
+ it('hibernated → alreadyExited, never now', () => {
+ const p = planBulkPause([t('a')], () => ({ state: 'done', sessionId: SID, hibernated: true }) as never)
+ expect(p.alreadyExited).toHaveLength(1)
+ expect(p.now).toHaveLength(0)
+ })
+ it('skip reasons', () => {
+ const p = planBulkPause(
+ [{ ...t('plain'), agentId: undefined }, t('nosid'), t('paused'), t('relay', 'claude', true), t('dropped')],
+ (id) => ({
+ plain: undefined,
+ nosid: { state: 'done' },
+ paused: { state: 'done', sessionId: SID, paused: true },
+ relay: { state: 'done', sessionId: SID },
+ dropped: { state: 'done', sessionId: SID, dropped: true }
+ })[id] as never
+ )
+ expect(Object.fromEntries(p.skip.map((s) => [s.target.nodeId, s.reason]))).toEqual({
+ plain: 'not-agent', nosid: 'no-session-id', paused: 'already-paused', relay: 'relay', dropped: 'dropped'
+ })
+ })
+ it('an agent that cannot be resumed is skipped', () => {
+ const p = planBulkPause([t('x', 'some-unknown-agent')], () => ({ state: 'done', sessionId: SID }) as never)
+ expect(p.skip[0].reason).toBe('not-resumable')
+ })
+})
+
+describe('planBulkPause: no exit sequence', () => {
+ it('an agent we can resume but cannot quit (antigravity) is skipped as not-resumable', () => {
+ const p = planBulkPause([t('x', 'antigravity')], () => ({ state: 'done', sessionId: SID }) as never)
+ expect(p.skip.map((s) => s.reason)).toEqual(['not-resumable'])
+ expect(p.now).toHaveLength(0)
+ })
+})
+
+describe('planBulkPause: unknown state (after a restart)', () => {
+ it('unknown + lastSeen done → now', () => {
+ const p = planBulkPause([t('a')], () => ({ sessionId: SID, lastSeen: { at: 1, state: 'done' } }) as never)
+ expect(p.now.map((x) => x.nodeId)).toEqual(['a'])
+ })
+ it('unknown + lastSeen working → skip state-unknown', () => {
+ const p = planBulkPause([t('a')], () => ({ sessionId: SID, lastSeen: { at: 1, state: 'working' } }) as never)
+ expect(p.skip.map((s) => s.reason)).toEqual(['state-unknown'])
+ })
+ it('unknown + no lastSeen → skip state-unknown', () => {
+ const p = planBulkPause([t('a')], () => ({ sessionId: SID }) as never)
+ expect(p.skip.map((s) => s.reason)).toEqual(['state-unknown'])
+ expect(describeSkips(p.skip)).toBe('1 state unknown since restart')
+ })
+})
+
+describe('planBulkPause: session binding', () => {
+ it('records the session id a target was planned against', () => {
+ const p = planBulkPause([t('a'), t('b')], (id) => (id === 'a'
+ ? { state: 'done', sessionId: SID } : { state: 'working', sessionId: 'sid-b' }) as never)
+ expect(p.now[0].sessionId).toBe(SID)
+ expect(p.whenDone[0].sessionId).toBe('sid-b')
+ })
+})
+
+describe('bulkPauseConfirmText', () => {
+ it('names the skipped count once', () => {
+ const p = planBulkPause([t('a'), { ...t('b'), agentId: undefined }, { ...t('c'), agentId: undefined }],
+ () => ({ state: 'done', sessionId: SID }) as never)
+ const text = bulkPauseConfirmText('project "x"', p)
+ expect(text).toContain('Skipped: 2 not an agent.')
+ expect(text).not.toMatch(/skip 2/)
+ })
+})
+
+describe('bulkPauseResultText', () => {
+ const zero = { paused: 0, pending: 0, unreachable: 0, unverified: 0, notEligible: 0, timeout: 0, failed: 0, skipped: 0 }
+ it('all paused is info', () =>
+ expect(bulkPauseResultText({ ...zero, paused: 3 })).toEqual({ kind: 'info', text: 'Paused 3' }))
+ it('pending and skipped stay info', () =>
+ expect(bulkPauseResultText({ ...zero, paused: 1, pending: 2, skipped: 1 })).toEqual({
+ kind: 'info', text: 'Paused 1 · 2 after their current turn · 1 skipped'
+ }))
+ it('every outcome is counted, and any failure is an error', () =>
+ expect(bulkPauseResultText({ paused: 3, pending: 2, unreachable: 1, unverified: 2, notEligible: 1, timeout: 1, failed: 1, skipped: 4 })).toEqual({
+ kind: 'error',
+ text:
+ "Paused 3 · 2 after their current turn · 2 unreachable · 2 couldn't verify the agent in its pane · " +
+ '1 not eligible · 1 still running (nothing killed — check the pane) · 4 skipped'
+ }))
+ it('a disconnected-only batch is not "Paused 0" silently', () => {
+ const r = bulkPauseResultText({ ...zero, unverified: 2 })
+ expect(r.kind).toBe('error')
+ expect(r.text).toContain("2 couldn't verify the agent in its pane")
+ })
+})
+
+describe('isBusyForPause', () => {
+ it('unknown state is not busy', () => expect(isBusyForPause({} as never)).toBe(false))
+})
+
+describe('bulkPauseSummary', () => {
+ it('names each non-empty bucket', () => {
+ const p = planBulkPause([t('a'), t('b')], (id) => (id === 'a'
+ ? { state: 'done', sessionId: SID } : { state: 'working', sessionId: SID }) as never)
+ expect(bulkPauseSummary(p)).toBe('Pause 1 now, 1 after its current turn')
+ })
+})
+
+describe('describeSkips', () => {
+ const t = (nodeId: string): BulkPauseTarget => ({ nodeId, agentId: 'claude', relay: false, hostKey: 'local' })
+ it('groups by reason, in first-seen order', () =>
+ expect(
+ describeSkips([
+ { target: t('a'), reason: 'not-agent' },
+ { target: t('b'), reason: 'already-paused' },
+ { target: t('c'), reason: 'not-agent' },
+ { target: t('d'), reason: 'ended' }
+ ])
+ ).toBe('2 not an agent, 1 already paused, 1 CLI already exited'))
+ it('empty → empty string', () => expect(describeSkips([])).toBe(''))
+})
+
+describe('paneRouteProjectId', () => {
+ it('routes through the owning local or SSH project', () => {
+ expect(paneRouteProjectId({ id: 'p1' })).toBe('p1')
+ expect(paneRouteProjectId({ id: 'p2', remote: false })).toBe('p2')
+ })
+ it('refuses a node with no known owner — never the active project as a guess', () => {
+ expect(paneRouteProjectId(undefined)).toBeNull()
+ })
+ it('refuses a relay-owned node — its pane is on another machine', () => {
+ expect(paneRouteProjectId({ id: 'r1', remote: true })).toBeNull()
+ })
+})
diff --git a/src/renderer/lib/bulkPause.ts b/src/renderer/lib/bulkPause.ts
new file mode 100644
index 000000000..53be9271b
--- /dev/null
+++ b/src/renderer/lib/bulkPause.ts
@@ -0,0 +1,166 @@
+// Pure planner for "Pause all": sorts terminal nodes into pause-now / pause-after-the-current-turn /
+// already-exited / skipped. No React, no store access — the caller injects the status lookup, so
+// the same rules serve the menu, the palette and the tests.
+import { canResumeWith } from '../../shared/agents/config'
+import type { AgentNodeStatus } from '../state/agentStatus'
+import { exitSequence } from '../terminal/agent-restart'
+
+export type BulkPauseSkip =
+ | 'not-agent' | 'no-session-id' | 'not-resumable' | 'already-paused' | 'relay' | 'dropped' | 'ended'
+ | 'state-unknown'
+
+export interface BulkPauseTarget {
+ nodeId: string
+ agentId: string | undefined
+ relay: boolean
+ hostKey: string
+ /** The session the target was planned against (set by the planner for every actionable target).
+ * A pending mark or a queued exit for it is void once the node runs another session — a
+ * restart, a model or account switch, `/clear` — because the turn it was waiting on is gone. */
+ sessionId?: string
+}
+
+export interface BulkPausePlan {
+ now: BulkPauseTarget[]
+ whenDone: BulkPauseTarget[]
+ alreadyExited: BulkPauseTarget[]
+ skip: { target: BulkPauseTarget; reason: BulkPauseSkip }[]
+}
+
+/**
+ * Typing an exit into a working/waiting/blocked session, or one holding a question/approval
+ * ticket, would abandon the turn or ANSWER the dialog — those wait for their turn to end.
+ * An unknown state is not busy, but it is not idle either: see `idleForPause`.
+ */
+export function isBusyForPause(st: AgentNodeStatus | undefined): boolean {
+ if (!st) return false
+ if (st.state === 'working' || st.state === 'waiting' || st.state === 'blocked') return true
+ return !!(st.held || st.pendingId)
+}
+
+/**
+ * Idle enough to type an exit into: a known `done`, or — when the live state is unknown, as after
+ * an app restart (state is transient; nothing has reported yet) — a persisted last-seen clock that
+ * says the last hook event was a `done`. Without either we cannot tell an idle CLI from one that is
+ * mid-turn, and an exit typed into a running turn abandons it: such a node is skipped, never
+ * guessed at. Busy is decided first by `isBusyForPause`; this is the other half.
+ */
+export function idleForPause(st: AgentNodeStatus | undefined): boolean {
+ if (!st) return false
+ if (st.state === 'done') return true
+ return st.state === undefined && st.lastSeen?.state === 'done'
+}
+
+export function planBulkPause(
+ targets: BulkPauseTarget[],
+ statusOf: (id: string) => AgentNodeStatus | undefined
+): BulkPausePlan {
+ const plan: BulkPausePlan = { now: [], whenDone: [], alreadyExited: [], skip: [] }
+ for (const target of targets) {
+ const st = statusOf(target.nodeId)
+ const skip = (reason: BulkPauseSkip): void => void plan.skip.push({ target, reason })
+ // A relay tab's pane belongs to another machine: never typed into from here.
+ if (target.relay) { skip('relay'); continue }
+ if (!target.agentId) { skip('not-agent'); continue }
+ if (st?.paused) { skip('already-paused'); continue }
+ if (!st?.sessionId) { skip('no-session-id'); continue }
+ // Resumable AND quittable: an agent with no exit sequence (antigravity resumes but has no
+ // in-band quit) is refused by `performExitPhase` at fire time, so it is never planned at all.
+ if (!canResumeWith(target.agentId, st.sessionId) || !exitSequence(target.agentId)) {
+ skip('not-resumable')
+ continue
+ }
+ const bound: BulkPauseTarget = { ...target, sessionId: st.sessionId }
+ // Already exited by Eco: nothing to type; the caller only marks it paused.
+ if (st.hibernated) { plan.alreadyExited.push(bound); continue }
+ if (st.dropped) { skip('dropped'); continue }
+ // The CLI announced its exit: nothing to type an exit into (a shell owns the pane).
+ if (st.sessionEnded) { skip('ended'); continue }
+ if (isBusyForPause(st)) plan.whenDone.push(bound)
+ else if (idleForPause(st)) plan.now.push(bound)
+ else skip('state-unknown')
+ }
+ return plan
+}
+
+export function bulkPauseSummary(plan: BulkPausePlan): string {
+ const parts: string[] = []
+ const n = plan.now.length + plan.alreadyExited.length
+ if (n) parts.push(`Pause ${n} now`)
+ const w = plan.whenDone.length
+ if (w) parts.push(`${w} after ${w === 1 ? 'its' : 'their'} current turn`)
+ // The skipped count is not repeated here: the confirm appends the grouped reasons.
+ return parts.join(', ') || 'Nothing to pause'
+}
+
+/** The confirm dialog's whole message. Skips are named once, with their reasons. */
+export function bulkPauseConfirmText(scopeLabel: string, plan: BulkPausePlan): string {
+ return (
+ `Pause ${scopeLabel}? ${bulkPauseSummary(plan)}. Agents exit; their panes stay, and each ` +
+ 'comes back with Resume.' +
+ (plan.skip.length ? ` Skipped: ${describeSkips(plan.skip)}.` : '')
+ )
+}
+
+/** What a finished batch did, every outcome counted: a node that is neither paused nor pending
+ * must still show up, or a batch against a disconnected host reads as "Paused 0" and nothing. */
+export interface BulkPauseCounts {
+ paused: number
+ /** Marked "pause after this turn" (planned busy, or turned busy before its exit ran). */
+ pending: number
+ /** A key write did not reach the pane. */
+ unreachable: number
+ /** The pane owner could not be read (host unreachable, no ControlMaster): nothing was typed. */
+ unverified: number
+ /** Re-asked at fire time and refused (another process owns the pane, the state went unknown…). */
+ notEligible: number
+ /** The exit was typed and the CLI is still there. Nothing is killed. */
+ timeout: number
+ /** The runner itself threw. */
+ failed: number
+ skipped: number
+}
+
+export function bulkPauseResultText(c: BulkPauseCounts): { kind: 'info' | 'error'; text: string } {
+ const parts = [`Paused ${c.paused}`]
+ if (c.pending) parts.push(`${c.pending} after their current turn`)
+ const unreachable = c.unreachable + c.failed
+ if (unreachable) parts.push(`${unreachable} unreachable`)
+ if (c.unverified) parts.push(`${c.unverified} couldn't verify the agent in its pane`)
+ if (c.notEligible) parts.push(`${c.notEligible} not eligible`)
+ if (c.timeout) parts.push(`${c.timeout} still running (nothing killed — check the pane)`)
+ if (c.skipped) parts.push(`${c.skipped} skipped`)
+ const bad = unreachable + c.unverified + c.notEligible + c.timeout
+ return { kind: bad ? 'error' : 'info', text: parts.join(' · ') }
+}
+
+const SKIP_TEXT: Record<BulkPauseSkip, string> = {
+ 'not-agent': 'not an agent',
+ 'no-session-id': 'no session yet',
+ 'not-resumable': 'cannot be resumed',
+ 'already-paused': 'already paused',
+ relay: 'on another machine',
+ dropped: 'CLI already gone',
+ ended: 'CLI already exited',
+ 'state-unknown': 'state unknown since restart'
+}
+
+/** "2 not an agent, 1 already paused" — the skipped half of the confirm, grouped by reason. */
+export function describeSkips(skip: BulkPausePlan['skip']): string {
+ const n = new Map<BulkPauseSkip, number>()
+ for (const s of skip) n.set(s.reason, (n.get(s.reason) ?? 0) + 1)
+ return [...n].map(([r, c]) => `${c} ${SKIP_TEXT[r]}`).join(', ')
+}
+
+/**
+ * Which project's session may carry a node's pane traffic (keys, pane-command and pane-owner reads)
+ * during a bulk pause. `null` = refuse, and the runner then reports the node unverified/unreachable:
+ * - no known owner: a node read while its project is still loading has none, and falling back to
+ * the ACTIVE project would route its keys through whatever session that is — a relay tab's
+ * included, i.e. into a pane on another machine;
+ * - a relay-owned node: the planner already skips it, this keeps the route refusing on its own.
+ */
+export function paneRouteProjectId(owner: { id: string; remote?: boolean } | undefined): string | null {
+ if (!owner || owner.remote) return null
+ return owner.id
+}
diff --git a/src/renderer/lib/nodeActionItems.test.tsx b/src/renderer/lib/nodeActionItems.test.tsx
index 92b01c6a0..77f259ddf 100644
--- a/src/renderer/lib/nodeActionItems.test.tsx
+++ b/src/renderer/lib/nodeActionItems.test.tsx
@@ -45,6 +45,7 @@ function fakeCtx(nodes: CanvasNode[], over: Partial<NodeActionCtx> = {}): NodeAc
transferConversation: noop,
restartAgentNode: async () => {},
pauseAgentNode: async () => {},
+ pauseNodes: noop,
resumeAgentNode: noop,
switchClaudeAccountNode: async () => {},
switchCodexAccountNode: async () => {},
@@ -248,6 +249,51 @@ describe('buildNodeActionItems — filters', () => {
})
})
+describe('bulk pause from a multi-selection', () => {
+ it('several agents selected → one "Pause N sessions" row that hands every agent to pauseNodes', () => {
+ const pauseNodes = vi.fn()
+ const nodes = ['a1', 'a2', 'a3'].map((id) => term(id, { agentId: 'claude' }))
+ const items = buildNodeActionItems(['a1', 'a2', 'a3'], undefined, fakeCtx(nodes, { pauseNodes }))
+ const r = row(items, 'Pause 3 sessions')
+ expect(r).toBeDefined()
+ expect(top(items)).not.toContain('Pause session ▸')
+ ;(r as { onClick: () => void }).onClick()
+ expect(pauseNodes).toHaveBeenCalledWith(['a1', 'a2', 'a3'])
+ })
+
+ it('counts only agent sessions in a mixed selection', () => {
+ const pauseNodes = vi.fn()
+ const nodes = [term('a1', { agentId: 'claude' }), term('a2', { agentId: 'codex' }), term('t1')]
+ const items = buildNodeActionItems(['a1', 'a2', 't1'], undefined, fakeCtx(nodes, { pauseNodes }))
+ ;(row(items, 'Pause 2 sessions') as { onClick: () => void }).onClick()
+ expect(pauseNodes).toHaveBeenCalledWith(['a1', 'a2'])
+ })
+
+ it('one agent in a mixed selection keeps the single Pause session submenu (with Pause & end session)', () => {
+ useAgentStatus.setState({ byId: { a1: { state: 'done', sessionId: 's1' } } } as never)
+ const pauseAgentNode = vi.fn(async () => {})
+ const nodes = [term('a1', { agentId: 'claude' }), term('t1'), term('t2')]
+ const items = buildNodeActionItems(['a1', 't1', 't2'], undefined, fakeCtx(nodes, { pauseAgentNode }))
+ expect(top(items)).toContain('Pause session ▸')
+ expect(row(items, 'Pause 1 session')).toBeUndefined()
+ expect(row(items, 'Pause & end session')).toBeDefined()
+ ;(row(items, 'Pause') as { onClick: () => void }).onClick()
+ expect(pauseAgentNode).toHaveBeenCalledWith('a1', false)
+ })
+
+ it('no agent in the selection → no bulk pause row', () => {
+ const items = buildNodeActionItems(['t1', 't2'], undefined, fakeCtx([term('t1'), term('t2')]))
+ expect(top(items).some((r) => r.startsWith('Pause'))).toBe(false)
+ })
+
+ it('one agent keeps the single Pause session submenu', () => {
+ useAgentStatus.setState({ byId: { a1: { state: 'done', sessionId: 's1' } } } as never)
+ const items = buildNodeActionItems(['a1'], undefined, fakeCtx([term('a1', { agentId: 'claude' })]))
+ expect(top(items)).toContain('Pause session ▸')
+ expect(row(items, 'Pause 1 sessions')).toBeUndefined()
+ })
+})
+
describe('session rows when the terminal is not attached', () => {
const NOT_ATTACHED = 'This terminal is not attached right now.'
const claude = term('a', { agentId: 'claude', agentSessionId: 'sess-1' })
diff --git a/src/renderer/lib/nodeActionItems.tsx b/src/renderer/lib/nodeActionItems.tsx
index 133dcdff3..4788fb394 100644
--- a/src/renderer/lib/nodeActionItems.tsx
+++ b/src/renderer/lib/nodeActionItems.tsx
@@ -217,6 +217,8 @@ export interface NodeActionCtx {
clearEnv?: boolean
) => Promise<unknown>
pauseAgentNode: (nodeId: string, deep: boolean) => Promise<unknown>
+ /** Bulk pause for a multi-selection (Canvas `pauseNodes`): one confirm, the plan, the summary. */
+ pauseNodes: (ids: string[]) => void
resumeAgentNode: (nodeId: string) => unknown
switchClaudeAccountNode: (
nodeId: string,
@@ -502,7 +504,7 @@ export function buildNodeActionSections(
{ id: 'restart', items: session.restart },
{ id: 'switch-model', items: session.switchModel },
{ id: 'switch-account', items: session.switchAccount },
- { id: 'pause', items: session.pause },
+ { id: 'pause', items: ids.length > 1 ? bulkPauseRows(ids, ctx, hidden) : session.pause },
SEPARATOR,
{
id: 'delete',
@@ -511,6 +513,34 @@ export function buildNodeActionSections(
]
}
+/**
+ * A multi-selection's pause row: the selected AGENT sessions go to Canvas's one bulk path, which
+ * plans now / after-their-turn / skipped and asks once. Only agents are counted and handed over —
+ * "Pause 3 sessions" over two agents and a sticky would promise a pause that never happens. No
+ * agent selected ⇒ no row (there is nothing to pause), never a disabled one.
+ */
+function bulkPauseRows(
+ ids: string[],
+ ctx: NodeActionCtx,
+ hidden: Parameters<typeof sessionRows>[2]
+): MenuItem[] {
+ const agents = ids.filter(
+ (id) => ctx.nodes.find((n) => n.id === id)?.type === 'terminal' && !!ctx.agentIdOf(id)
+ )
+ if (agents.length === 0) return []
+ // One agent among other nodes: that agent's own Pause submenu (eligibility gate, "Pause & end
+ // session" included) — the bulk row would be a one-node bulk with fewer choices.
+ if (agents.length === 1) return sessionRows(agents[0], ctx, hidden).pause
+ return [
+ {
+ label: `Pause ${agents.length} sessions`,
+ icon: <IconPower />,
+ hint: 'Quits each CLI; busy ones pause after their current turn. Resume brings each back.',
+ onClick: () => ctx.pauseNodes(agents)
+ }
+ ]
+}
+
interface SessionRows {
restart: MenuItem[]
switchModel: MenuItem[]
@@ -946,6 +976,7 @@ export function offCanvasNodeActionCtx(o: OffCanvasCtxInput): NodeActionCtx {
transferConversation: refuse,
restartAgentNode: refuseLater,
pauseAgentNode: refuseLater,
+ pauseNodes: refuse,
resumeAgentNode: refuse,
switchClaudeAccountNode: refuseLater,
switchCodexAccountNode: refuseLater,
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index f863f94ad..ee1c3fc8e 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -77,14 +77,18 @@ export interface AgentNodeStatus {
* It is a record of the PAST, restored as nothing else:
* - NOT as `state`: after a relaunch nothing has reported, a turn may have started or ended while
* the app was down (the hook server was down with it), so the state stays unknown until the
- * next hook event. `lastSeen.state` is shown as "what it was last seen doing", never acted on.
+ * next hook event. `lastSeen.state` is shown as "what it was last seen doing", and acted on in
+ * exactly ONE place: a user-confirmed bulk pause (`idleForPause`, lib/bulkPause.ts) treats an
+ * unknown-state session as pausable only when it was last seen `done`. That is weak evidence
+ * on purpose: the user asked for the pause, the runner still proves the agent owns its pane,
+ * and without it every session after a restart would be unpausable. Nothing AUTOMATIC reads it.
* - NOT as `lastEventAt`: that field is the Eco idle clock AND the `idleKnown` signal for the
* offscreen release deferral, and a restored stamp read as "idle since before the restart"
* would make a session with an unknown state look hours idle. Eco stays inert for a session
* with no hook event in this run, deliberately — see `hibernation-policy.ts` ("A restored clock
* is not an idle proof").
* Its readers are the sessions sidebar's order and age label (`sessionList.ts`), which use it only
- * while `lastEventAt` is unset. `lastSeen.restored` (set on load, never written) is what says the
+ * while `lastEventAt` is unset, and the bulk-pause gate above. `lastSeen.restored` (set on load, never written) is what says the
* clock is from BEFORE the restart; any hook event in this run replaces the object without it.
*
* Written on EVERY hook event, same-state ones included (in place, no re-render — the fast path's
diff --git a/src/renderer/state/pauseCounts.test.ts b/src/renderer/state/pauseCounts.test.ts
new file mode 100644
index 000000000..c28f46c9f
--- /dev/null
+++ b/src/renderer/state/pauseCounts.test.ts
@@ -0,0 +1,13 @@
+import { describe, it, expect } from 'vitest'
+import { pauseCountsFor } from './pauseCounts'
+
+const P = [
+ { id: 'A', nodes: [{ id: 'a1' }, { id: 'a2' }, { id: 'a3' }] },
+ { id: 'B', nodes: [{ id: 'b1' }] }
+]
+
+describe('pauseCountsFor', () => {
+ it('counts paused and pending per project, omitting projects with neither', () =>
+ expect(pauseCountsFor(P, new Set(['a1', 'a2']), new Set(['a3']))).toEqual({ A: { paused: 2, pending: 1 } }))
+ it('nothing paused or pending → empty', () => expect(pauseCountsFor(P, new Set(), new Set())).toEqual({}))
+})
diff --git a/src/renderer/state/pauseCounts.ts b/src/renderer/state/pauseCounts.ts
new file mode 100644
index 000000000..2dd0f3c66
--- /dev/null
+++ b/src/renderer/state/pauseCounts.ts
@@ -0,0 +1,51 @@
+import { useMemo } from 'react'
+import { useAgentStatus } from './agentStatus'
+import { usePendingPause } from './pendingPause'
+
+export interface PauseCount {
+ paused: number
+ pending: number
+}
+
+/** Per-project PAUSED and pending-pause counts, for the tab badge and the "Cancel pending pauses"
+ * row. A project with neither is absent, so the caller's `?? 0` reads as "nothing to show". */
+export function pauseCountsFor(
+ projects: readonly { id: string; nodes: readonly { id: string }[] }[],
+ pausedIds: ReadonlySet<string>,
+ pendingIds: ReadonlySet<string>
+): Record<string, PauseCount> {
+ const out: Record<string, PauseCount> = {}
+ if (pausedIds.size === 0 && pendingIds.size === 0) return out
+ for (const p of projects) {
+ let paused = 0
+ let pending = 0
+ for (const n of p.nodes) {
+ if (pausedIds.has(n.id)) paused++
+ if (pendingIds.has(n.id)) pending++
+ }
+ if (paused || pending) out[p.id] = { paused, pending }
+ }
+ return out
+}
+
+const split = (sig: string): Set<string> => new Set(sig.split('|').filter(Boolean))
+
+/**
+ * The counts, subscribed through two PRIMITIVE signatures (the paused id set, the pending id set)
+ * rather than the whole status map: a hook event that changes nothing here re-renders nothing.
+ * The caller supplies the projects it already holds.
+ */
+export function usePauseCounts(
+ projects: readonly { id: string; nodes: readonly { id: string }[] }[]
+): Record<string, PauseCount> {
+ const pausedSig = useAgentStatus((s) => {
+ let ids = ''
+ for (const [id, st] of Object.entries(s.byId)) if (st?.paused) ids += `${id}|`
+ return ids
+ })
+ const pendingSig = usePendingPause((s) => Object.keys(s.byId).join('|'))
+ return useMemo(
+ () => pauseCountsFor(projects, split(pausedSig), split(pendingSig)),
+ [projects, pausedSig, pendingSig]
+ )
+}
diff --git a/src/renderer/state/pendingPause.test.ts b/src/renderer/state/pendingPause.test.ts
new file mode 100644
index 000000000..c008d19cb
--- /dev/null
+++ b/src/renderer/state/pendingPause.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { usePendingPause, shouldFirePendingPause, startPendingPauseWatcher } from './pendingPause'
+import { useAgentStatus } from './agentStatus'
+
+const T = { nodeId: 'n1', agentId: 'claude', relay: false, hostKey: 'local' }
+
+describe('shouldFirePendingPause', () => {
+ it('fires on working → done', () =>
+ expect(shouldFirePendingPause({ state: 'working' } as never, { state: 'done' } as never)).toBe(true))
+ it('not on an errored done', () =>
+ expect(shouldFirePendingPause({ state: 'working' } as never, { state: 'done', lastTurnError: { at: 1 } } as never)).toBe(false))
+ it('not on an interrupted done', () =>
+ expect(shouldFirePendingPause({ state: 'working' } as never, { state: 'done', lastTurnInterrupted: { at: 1 } } as never)).toBe(false))
+ it('not while a ticket is held', () =>
+ expect(shouldFirePendingPause({ state: 'working' } as never, { state: 'done', held: {} } as never)).toBe(false))
+ it('not on done → done', () =>
+ expect(shouldFirePendingPause({ state: 'done' } as never, { state: 'done' } as never)).toBe(false))
+})
+
+describe('watcher', () => {
+ beforeEach(() => {
+ usePendingPause.setState({ byId: {} })
+ useAgentStatus.setState({ byId: {} })
+ })
+ it('fires once and removes the entry', () => {
+ const fire = vi.fn()
+ const stop = startPendingPauseWatcher(fire)
+ usePendingPause.getState().add([T])
+ useAgentStatus.getState().setState('n1', 'working')
+ useAgentStatus.getState().setState('n1', 'done')
+ useAgentStatus.getState().setState('n1', 'working')
+ useAgentStatus.getState().setState('n1', 'done')
+ expect(fire).toHaveBeenCalledTimes(1)
+ expect(usePendingPause.getState().byId.n1).toBeUndefined()
+ stop()
+ })
+ it('a node removed from the agent table drops its pending pause', () => {
+ const stop = startPendingPauseWatcher(vi.fn())
+ usePendingPause.getState().add([T])
+ useAgentStatus.getState().setState('n1', 'working')
+ useAgentStatus.getState().remove('n1')
+ expect(usePendingPause.getState().byId.n1).toBeUndefined()
+ stop()
+ })
+ it('drops the mark BEFORE firing, so a fire that re-queues (deferred) is not wiped', () => {
+ const seen: (string | undefined)[] = []
+ const stop = startPendingPauseWatcher((t) => {
+ seen.push(usePendingPause.getState().byId[t.nodeId]?.nodeId)
+ usePendingPause.getState().add([t]) // a synchronous re-queue, as a deferred outcome does
+ })
+ usePendingPause.getState().add([T])
+ useAgentStatus.getState().setState('n1', 'working')
+ useAgentStatus.getState().setState('n1', 'done')
+ expect(seen).toEqual([undefined])
+ expect(usePendingPause.getState().byId.n1).toBeDefined()
+ stop()
+ })
+ it('a mark bound to session A is dropped, unfired, when the node moves to session B', () => {
+ const fire = vi.fn()
+ const stop = startPendingPauseWatcher(fire)
+ useAgentStatus.getState().setSessionId('n1', 'sid-a')
+ useAgentStatus.getState().setState('n1', 'working')
+ usePendingPause.getState().add([{ ...T, sessionId: 'sid-a' }])
+ useAgentStatus.getState().setSessionId('n1', 'sid-b')
+ useAgentStatus.getState().setState('n1', 'done')
+ expect(fire).not.toHaveBeenCalled()
+ expect(usePendingPause.getState().byId.n1).toBeUndefined()
+ stop()
+ })
+ it('a mark bound to the current session still fires', () => {
+ const fire = vi.fn()
+ const stop = startPendingPauseWatcher(fire)
+ useAgentStatus.getState().setSessionId('n1', 'sid-a')
+ useAgentStatus.getState().setState('n1', 'working')
+ usePendingPause.getState().add([{ ...T, sessionId: 'sid-a' }])
+ useAgentStatus.getState().setState('n1', 'done')
+ expect(fire).toHaveBeenCalledTimes(1)
+ stop()
+ })
+})
diff --git a/src/renderer/state/pendingPause.ts b/src/renderer/state/pendingPause.ts
new file mode 100644
index 000000000..1b79398db
--- /dev/null
+++ b/src/renderer/state/pendingPause.ts
@@ -0,0 +1,69 @@
+import { create } from 'zustand'
+import { useAgentStatus, type AgentNodeStatus } from './agentStatus'
+import type { BulkPauseTarget } from '../lib/bulkPause'
+
+/** Nodes asked to pause once their current turn ends. TRANSIENT on purpose: after a restart the
+ * agent state is unknown and a mark firing hours later would surprise. */
+export const usePendingPause = create<{
+ byId: Record<string, BulkPauseTarget>
+ add(targets: BulkPauseTarget[]): void
+ remove(nodeIds: string[]): void
+}>((set) => ({
+ byId: {},
+ add: (targets) =>
+ set((s) => ({ byId: { ...s.byId, ...Object.fromEntries(targets.map((t) => [t.nodeId, t])) } })),
+ remove: (ids) =>
+ set((s) => {
+ if (!ids.some((id) => id in s.byId)) return s
+ const byId = { ...s.byId }
+ for (const id of ids) delete byId[id]
+ return { byId }
+ })
+}))
+
+/** A turn that ended cleanly: errored and interrupted turns stay pending (the next clean `done`
+ * fires), and a held question/approval ticket means the CLI is still waiting on a person. */
+export function shouldFirePendingPause(
+ prev: AgentNodeStatus | undefined,
+ next: AgentNodeStatus | undefined
+): boolean {
+ if (!next || next.state !== 'done' || prev?.state === 'done') return false
+ if (next.lastTurnError || next.lastTurnInterrupted) return false
+ return !(next.held || next.pendingId)
+}
+
+/** Fires each pending target once on its done edge and drops marks whose node is gone or paused,
+ * or now runs a different session than the one the mark was taken against (a restart, a model or
+ * account switch, `/clear`): the turn it was waiting on is over, and so is the request. */
+export function startPendingPauseWatcher(fire: (t: BulkPauseTarget) => void): () => void {
+ return useAgentStatus.subscribe((s, prev) => {
+ const pending = usePendingPause.getState().byId
+ const ids = Object.keys(pending)
+ if (ids.length === 0) return
+ const gone: string[] = []
+ for (const id of ids) {
+ const next = s.byId[id]
+ if (!next && prev.byId[id]) {
+ gone.push(id)
+ continue
+ }
+ if (next?.paused) {
+ gone.push(id) // paused elsewhere
+ continue
+ }
+ const bound = pending[id].sessionId
+ if (bound && next?.sessionId && next.sessionId !== bound) {
+ gone.push(id)
+ continue
+ }
+ if (shouldFirePendingPause(prev.byId[id], next)) {
+ // Drop the mark BEFORE firing: `fire` may re-queue the same node (a fire-time re-ask that
+ // finds it busy again answers 'deferred'), and a batch removal after the loop would wipe
+ // that fresh mark.
+ usePendingPause.getState().remove([id])
+ fire(pending[id])
+ }
+ }
+ if (gone.length) usePendingPause.getState().remove(gone)
+ })
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 12f9e2420..657eb3e36 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -636,6 +636,16 @@ body,
background: none;
}
+/* Bulk pause: "⏸ 3 · 1 pending" after the tab name. Muted text, no fill — a paused project is a
+ resting state, not something asking for attention like the unread badge beside it. */
+.tab__paused {
+ flex-shrink: 0;
+ color: var(--muted);
+ font-size: 10.5px;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
/* Unread-completion count badge on a project tab. */
.tab__badge {
display: inline-flex;
@@ -801,6 +811,17 @@ body,
cursor: not-allowed;
}
+/* A menu row whose disabled reason lives on a wrapper: a disabled button takes no pointer events
+ in Chromium, so neither its own `title` nor the cursor would ever show. */
+.tab-menu__reason {
+ display: block;
+ cursor: not-allowed;
+}
+
+.tab-menu__reason > button:disabled {
+ pointer-events: none;
+}
+
.tab-menu button.danger:hover:not(:disabled) {
background: color-mix(in srgb, var(--state-error) 15%, transparent);
}
diff --git a/src/renderer/terminal/headless-pause.test.ts b/src/renderer/terminal/headless-pause.test.ts
new file mode 100644
index 000000000..26d81c622
--- /dev/null
+++ b/src/renderer/terminal/headless-pause.test.ts
@@ -0,0 +1,169 @@
+import { describe, it, expect, vi } from 'vitest'
+import { pauseNodeHeadless, createHostLimiter } from './headless-pause'
+
+const SID = '11111111-2222-3333-4444-555555555555'
+const OWNER = { panePid: 100, tty: 'pts/1', command: 'claude', argv: ['claude'], paneId: '%1' }
+const TIMING = { pollMs: 1, timeoutMs: 200 }
+function deps(over: Partial<Record<string, unknown>> = {}) {
+ let pane = 'claude'
+ return {
+ sendPaneKeys: vi.fn(async () => { pane = 'zsh'; return { ok: true } as const }),
+ paneCommand: vi.fn(async () => pane),
+ paneOwner: vi.fn(async () => OWNER as never),
+ status: vi.fn(() => ({ state: 'done', sessionId: SID }) as never),
+ binaries: vi.fn(() => ['claude']),
+ stillExists: vi.fn(() => true),
+ markPaused: vi.fn(),
+ ...over
+ }
+}
+const T = { nodeId: 'n1', agentId: 'claude', relay: false, hostKey: 'local' }
+
+describe('pauseNodeHeadless', () => {
+ it('exits and marks paused', async () => {
+ const d = deps()
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('paused')
+ expect(d.markPaused).toHaveBeenCalledWith('n1', expect.objectContaining({ alreadyExited: false }))
+ })
+ it('defers a node that turned busy before the first key', async () => {
+ const d = deps({ status: vi.fn(() => ({ state: 'working', sessionId: SID })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('deferred')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('alreadyExited writes nothing and marks', async () => {
+ const d = deps()
+ await expect(pauseNodeHeadless(T, true, d as never, TIMING)).resolves.toBe('paused')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ expect(d.markPaused).toHaveBeenCalled()
+ })
+ it('an unreadable pane owner (null: host unreachable) is unverified, no keys', async () => {
+ const d = deps({ paneOwner: vi.fn(async () => null) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('unverified')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('refuses when a shell, not the agent, owns the pane (not-in-this-pane)', async () => {
+ const d = deps({ paneOwner: vi.fn(async () => ({ ...OWNER, command: 'zsh', argv: ['zsh'] })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('not-eligible')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('pre-exit paneOwner rejection is unverified, no keys', async () => {
+ const d = deps({ paneOwner: vi.fn(async () => { throw new Error('x') }) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('unverified')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('post-exit paneOwner rejection still marks paused with wake null', async () => {
+ let n = 0
+ const d = deps({ paneOwner: vi.fn(async () => { if (n++) throw new Error('x'); return OWNER as never }) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('paused')
+ expect(d.markPaused).toHaveBeenCalledWith('n1', { alreadyExited: false, wake: null })
+ })
+ it('a hung paneOwner does not hang the pause', async () => {
+ const d = deps({ paneOwner: vi.fn(() => new Promise(() => {})) })
+ await expect(
+ pauseNodeHeadless(T, false, d as never, { ...TIMING, ownerTimeoutMs: 10 })
+ ).resolves.toBe('unverified')
+ })
+ it('refuses a node whose CLI announced its exit, before any key', async () => {
+ const d = deps({ status: vi.fn(() => ({ state: undefined, sessionId: SID, sessionEnded: true })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('not-eligible')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('reports unreachable when keys cannot be sent, marks nothing', async () => {
+ const d = deps({ sendPaneKeys: vi.fn(async () => ({ ok: false, reason: 'not-connected' })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('unreachable')
+ expect(d.markPaused).not.toHaveBeenCalled()
+ })
+ it('a second concurrent pause of the same node is not-eligible (shared guard)', async () => {
+ const d = deps()
+ const [a, b] = await Promise.all([
+ pauseNodeHeadless(T, false, d as never, TIMING),
+ pauseNodeHeadless(T, false, d as never, TIMING)
+ ])
+ expect([a, b].sort()).toEqual(['not-eligible', 'paused'])
+ })
+})
+
+describe('pauseNodeHeadless: unknown state and session binding', () => {
+ it('unknown state without a last-seen done is not-eligible, no keys', async () => {
+ const d = deps({ status: vi.fn(() => ({ sessionId: SID, lastSeen: { at: 1, state: 'working' } })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('not-eligible')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('unknown state with no last-seen is not-eligible, no keys', async () => {
+ const d = deps({ status: vi.fn(() => ({ sessionId: SID })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('not-eligible')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('unknown state with a last-seen done exits', async () => {
+ const d = deps({ status: vi.fn(() => ({ sessionId: SID, lastSeen: { at: 1, state: 'done' } })) })
+ await expect(pauseNodeHeadless(T, false, d as never, TIMING)).resolves.toBe('paused')
+ })
+ it('a target bound to another session is not-eligible, no keys', async () => {
+ const d = deps()
+ await expect(pauseNodeHeadless({ ...T, sessionId: 'other' }, false, d as never, TIMING)).resolves.toBe('not-eligible')
+ expect(d.sendPaneKeys).not.toHaveBeenCalled()
+ })
+ it('a target bound to its current session exits', async () => {
+ const d = deps()
+ await expect(pauseNodeHeadless({ ...T, sessionId: SID }, false, d as never, TIMING)).resolves.toBe('paused')
+ })
+ it('waits through the late-exit window by default (a CLI that quits after the base window is paused)', async () => {
+ let polls = 0
+ const d = deps({
+ sendPaneKeys: vi.fn(async () => ({ ok: true }) as const),
+ // Still the agent through the 20 ms base window, a shell afterwards.
+ paneCommand: vi.fn(async () => (polls++ > 40 ? 'zsh' : 'claude'))
+ })
+ await expect(
+ pauseNodeHeadless(T, false, d as never, { pollMs: 1, timeoutMs: 20 })
+ ).resolves.toBe('paused')
+ })
+ it('lateExitMs: 0 restores the bare base window', async () => {
+ const d = deps({
+ sendPaneKeys: vi.fn(async () => ({ ok: true }) as const),
+ paneCommand: vi.fn(async () => 'claude')
+ })
+ await expect(
+ pauseNodeHeadless(T, false, d as never, { pollMs: 1, timeoutMs: 20, lateExitMs: 0 })
+ ).resolves.toBe('exit-timeout')
+ })
+})
+
+describe('createHostLimiter', () => {
+ const tick = (): Promise<void> => new Promise((r) => setTimeout(r, 1))
+
+ it('two callers sharing one limiter never exceed the cap on a host', async () => {
+ const lim = createHostLimiter(3)
+ let inFlight = 0
+ let peak = 0
+ const job = async (): Promise<void> => {
+ inFlight++
+ peak = Math.max(peak, inFlight)
+ await tick()
+ inFlight--
+ }
+ // A batch and a stream of single fires (the pending watcher), both on host 'h'.
+ const batch = Promise.all(Array.from({ length: 6 }, () => lim.run('h', job)))
+ const singles = Promise.all(Array.from({ length: 4 }, () => lim.run('h', job)))
+ await Promise.all([batch, singles])
+ expect(peak).toBe(3)
+ })
+
+ it('a throwing fn rejects only its own promise and frees its slot', async () => {
+ const lim = createHostLimiter(1)
+ const bad = lim.run('h', async () => { throw new Error('x') })
+ const good = lim.run('h', async () => 'ok')
+ await expect(bad).rejects.toThrow('x')
+ await expect(good).resolves.toBe('ok')
+ })
+
+ it('different hosts are independent', async () => {
+ const lim = createHostLimiter(1)
+ let release: () => void = () => {}
+ const blockA = lim.run('a', () => new Promise<void>((r) => { release = r }))
+ const b = await lim.run('b', async () => 'b-done') // must not wait on host a
+ expect(b).toBe('b-done')
+ release()
+ await blockA
+ })
+})
diff --git a/src/renderer/terminal/headless-pause.ts b/src/renderer/terminal/headless-pause.ts
new file mode 100644
index 000000000..3ac513f3b
--- /dev/null
+++ b/src/renderer/terminal/headless-pause.ts
@@ -0,0 +1,182 @@
+// Exit an agent CLI by node id, with no mounted terminal: the bulk "Pause all" drives the same pure
+// `performExitPhase` the node menu and Eco use, against core primitives (pane keys by id, pane
+// command, pane owner) instead of a node's DeliveryIo. Shallow only: the tmux pane and its
+// scrollback stay; nothing here recycles a session.
+import type { DeliveryIo } from '@shared/command-delivery'
+import type { PaneKeysResult } from '@shared/types'
+import type { PaneOwner } from '@shared/agents/pane-owner-predicate'
+import type { AgentNodeStatus } from '../state/agentStatus'
+import { isBusyForPause, idleForPause, type BulkPauseTarget } from '../lib/bulkPause'
+import {
+ performExitPhase,
+ guardConcurrentRestart,
+ RESTART_EXIT_TIMEOUT_MS,
+ RESTART_LATE_EXIT_MS
+} from './agent-restart'
+import { decideHibernateExit, captureWakeContext, type WakeContext } from './wake-identity'
+
+export const BULK_PAUSE_HOST_CAP = 3
+
+/**
+ * - `unverified`: the pane owner could not be read before the exit (an SSH host with no live
+ * ControlMaster, a read that hung or failed). Nothing was typed. Distinct from `not-eligible`,
+ * which means the read SUCCEEDED and said no (or a gate refused): the summary must not fold an
+ * unreachable host into "not a target".
+ */
+export type HeadlessPauseOutcome =
+ | 'paused' | 'exit-timeout' | 'not-eligible' | 'deferred' | 'unreachable' | 'unverified'
+
+export interface HeadlessPauseDeps {
+ sendPaneKeys(nodeId: string, data: string): Promise<PaneKeysResult>
+ paneCommand(nodeId: string): Promise<string | null>
+ paneOwner(nodeId: string): Promise<PaneOwner | null>
+ status(nodeId: string): AgentNodeStatus | undefined
+ binaries(agentId: string): readonly string[] | null
+ stillExists(nodeId: string): boolean
+ markPaused(nodeId: string, ctx: { alreadyExited: boolean; wake: WakeContext | null }): void
+}
+
+/** Bounded, never-rejecting pane-owner read (mirrors TerminalNode's readPaneOwner): a hang or a
+ * rejection reads as "could not see the pane" (null), and the timer is always cleared. */
+async function readOwnerSafe(
+ nodeId: string, deps: HeadlessPauseDeps, ms: number
+): Promise<PaneOwner | null> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
+ deps.paneOwner(nodeId).catch(() => null),
+ new Promise<null>((r) => { timer = setTimeout(() => r(null), ms) })
+ ])
+ } catch {
+ return null
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+}
+
+/** A DeliveryIo whose writes go into the pane by node id, in order. `onData` is never used by the
+ * exit phase (it polls the pane command instead). The first failed write is remembered. */
+function paneKeysIo(
+ nodeId: string,
+ deps: HeadlessPauseDeps
+): { io: DeliveryIo; failed: () => Promise<boolean>; failedSoFar: () => boolean } {
+ let chain: Promise<unknown> = Promise.resolve()
+ let failed = false
+ const io: DeliveryIo = {
+ write: (d) => {
+ chain = chain.then(async () => {
+ if (failed) return
+ try {
+ const r = await deps.sendPaneKeys(nodeId, d)
+ if (!r.ok) failed = true
+ } catch {
+ failed = true
+ }
+ })
+ },
+ onData: () => () => {}
+ }
+ return { io, failed: async () => { await chain; return failed }, failedSoFar: () => failed }
+}
+
+export function pauseNodeHeadless(
+ target: BulkPauseTarget,
+ alreadyExited: boolean,
+ deps: HeadlessPauseDeps,
+ timing?: { pollMs?: number; timeoutMs?: number; ownerTimeoutMs?: number; lateExitMs?: number }
+): Promise<HeadlessPauseOutcome> {
+ return guardConcurrentRestart(target.nodeId, async (): Promise<HeadlessPauseOutcome> => {
+ const { nodeId, agentId } = target
+ // The late window (as the menu's Restart uses): a CLI that quits a moment after the base 6 s
+ // is paused, not reported "still running" with nobody left watching it.
+ const {
+ ownerTimeoutMs = RESTART_EXIT_TIMEOUT_MS,
+ lateExitMs = RESTART_LATE_EXIT_MS,
+ ...exitTiming
+ } = timing ?? {}
+ const st = deps.status(nodeId)
+ if (!agentId || !st?.sessionId || st.paused || st.sessionEnded || !deps.stillExists(nodeId)) {
+ return 'not-eligible'
+ }
+ // Bound to the session it was planned against: another session in that pane means the turn
+ // (and the user's intent) this exit was for is gone.
+ if (target.sessionId && target.sessionId !== st.sessionId) return 'not-eligible'
+ if (alreadyExited || st.hibernated) {
+ deps.markPaused(nodeId, { alreadyExited: true, wake: null })
+ return 'paused'
+ }
+ if (isBusyForPause(st)) return 'deferred' // fire-time re-ask: the plan-time verdict is stale
+ // Unknown state with no last-seen `done` (see `idleForPause`): never typed into on a guess.
+ if (!idleForPause(st)) return 'not-eligible'
+ const owner = await readOwnerSafe(nodeId, deps, ownerTimeoutMs)
+ if (owner === null) return 'unverified'
+ if (decideHibernateExit(owner, agentId, deps.binaries(agentId)) !== 'agent-owns-pane') return 'not-eligible'
+ if (isBusyForPause(deps.status(nodeId))) return 'deferred'
+ const keys = paneKeysIo(nodeId, deps)
+ const outcome = await performExitPhase({
+ agentId,
+ sessionId: st.sessionId,
+ io: keys.io,
+ paneCommand: () => deps.paneCommand(nodeId),
+ // A key write that did not reach the pane ends the wait at once: polling a pane we never
+ // typed into for the whole late window would only delay the "unreachable" answer by a minute.
+ isLive: () => deps.stillExists(nodeId) && !keys.failedSoFar(),
+ lateExitMs,
+ ...exitTiming
+ })
+ // A failed key write usually surfaces as an exit timeout; report it as unreachable so the
+ // summary does not claim "still running" for a node we never reached.
+ if (await keys.failed()) return 'unreachable'
+ if (outcome !== 'exited') return outcome === 'exit-timeout' ? 'exit-timeout' : 'not-eligible'
+ deps.markPaused(nodeId, { alreadyExited: false, wake: captureWakeContext(await readOwnerSafe(nodeId, deps, ownerTimeoutMs)) })
+ return 'paused'
+ })()
+}
+
+export interface HostLimiter {
+ run<T>(hostKey: string, fn: () => Promise<T>): Promise<T>
+}
+
+/**
+ * At most `cap` jobs in flight per host key, the rest queued FIFO. ONE instance must be shared by
+ * every caller that exits CLIs on a host — the batch AND the pending-pause watcher — or each
+ * caller gets its own cap and together they exceed it. A throwing `fn` rejects only its own
+ * promise and frees its slot.
+ */
+export function createHostLimiter(cap: number): HostLimiter {
+ const inFlight = new Map<string, number>()
+ const queues = new Map<string, (() => void)[]>()
+ const release = (key: string): void => {
+ const next = queues.get(key)?.shift()
+ if (next) {
+ next() // the slot passes straight to the next waiter
+ return
+ }
+ queues.delete(key)
+ const n = (inFlight.get(key) ?? 1) - 1
+ if (n > 0) inFlight.set(key, n)
+ else inFlight.delete(key)
+ }
+ const acquire = (key: string): Promise<void> => {
+ const n = inFlight.get(key) ?? 0
+ if (n < cap) {
+ inFlight.set(key, n + 1)
+ return Promise.resolve()
+ }
+ return new Promise<void>((resolve) => {
+ const q = queues.get(key) ?? []
+ q.push(resolve)
+ queues.set(key, q)
+ })
+ }
+ return {
+ async run<T>(hostKey: string, fn: () => Promise<T>): Promise<T> {
+ await acquire(hostKey)
+ try {
+ return await fn()
+ } finally {
+ release(hostKey)
+ }
+ }
+ }
+}
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 0e4308efc..12fbaba95 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -91,6 +91,8 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
// Executes an agent launch on the host and reads a host-local `--prompt-file` into it. A relay
// tab never sends it (its pty bridge omits the member); this holds the refusal host-side too.
IPC.ptyExecuteLaunch,
+ // Types into a pane of THIS machine (or its SSH host); a relay peer must never reach it.
+ IPC.ptySendPaneKeys,
// Prepare-for-update ends EVERY session on this machine's session host and quits the app. Only
// the host's own user may do that. Raw ipcMain handlers (no peer reaches them); listed here too
// so moving them onto the platform table later cannot quietly open them.
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index a48bd3aac..68e9c93dd 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -34,6 +34,8 @@ 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',
+ /** Type keys into a node's tmux pane by node id (no mounted terminal). Host-only. */
+ ptySendPaneKeys: 'pty:send-pane-keys',
/** The live working directory of a node's tmux pane (`#{pane_current_path}`) — where a relative
* path an agent printed actually lives when it is not the node's launch cwd (file links). */
ptyPaneCwd: 'pty:pane-cwd',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index c4f26f4d1..e7a440d1a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -243,6 +243,11 @@ export interface PaneCursor {
visible: boolean
}
+/** Outcome of typing keys into a node's pane by id (`PtyApi.sendPaneKeys`). Never a rejection. */
+export type PaneKeysResult =
+ | { ok: true }
+ | { ok: false; reason: 'not-connected' | 'unsupported-backend' | 'no-ssh' | 'failed' }
+
/**
* Result of creating a PTY session. `fresh` distinguishes a tmux session that had to be
* created anew (cold start — e.g. after a machine reboot killed the tmux server) from a
@@ -1381,11 +1386,13 @@ export interface PtyApi {
/** The command currently in the foreground of a node's tmux pane (e.g. 'claude', 'zsh'), by
* 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>
+ paneCommand(persistKey: string, opts?: { resolveUnmounted?: boolean }): Promise<string | null>
/** The live working directory of a node's pane (`#{pane_current_path}`). null when unknown —
* no session, no tmux, the session-host backend, a failed query, or a surface that does not
* serve it (relay tabs) — and never a rejection. Used as the second cwd for file links. */
paneCwd(persistKey: string): Promise<string | null>
+ /** Type raw keys into a node's tmux pane by node id; no mounted terminal needed. Never rejects. */
+ sendPaneKeys(nodeId: string, data: string): Promise<PaneKeysResult>
/**
* Desktop only (#925). Spawn-or-attach a node's session with no viewer and deliver `command`
* through the echo-verified writer, then release the synthetic client (the tmux session keeps
@@ -1400,7 +1407,7 @@ export interface PtyApi {
* foreground process group — so a caller can ask WHO owns the pane rather than what tmux calls
* it. `null` is "could not read", never evidence that the pane is free (see `isAgentPane`'s
* three-valued verdict, which is what consumers should decide on). */
- paneOwner(persistKey: string): Promise<PaneOwner | null>
+ paneOwner(persistKey: string, opts?: { resolveUnmounted?: boolean }): Promise<PaneOwner | null>
/**
* Execute a semantic agent launch in a node's live LOCAL Windows session-host pane: the core
* encodes it for the pane's own shell (pwsh / Windows PowerShell / cmd) and the host types it