Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

CLI: an agent's engine exiting leaves a terminal, not a hole

0xken1574c924e9e9bd
diff --git a/cli/scripts/terminal-engine-e2e.mts b/cli/scripts/terminal-engine-e2e.mts
index 8393eec93..75c13cc93 100644
--- a/cli/scripts/terminal-engine-e2e.mts
+++ b/cli/scripts/terminal-engine-e2e.mts
@@ -9,6 +9,8 @@
// exit create → type `exit` → the pane goes and the row with it (agent_deleted).
// restart create → adopt claude → `harness stop; harness start` (LOCAL machine only). Then look:
// the row must still be claude on the same pane, not a second pane.
+// agent an ORDINARY agent (agent_create engine=claude) → /exit it → the row becomes `terminal`
+// and stays (the pane is a shell now) → type `claude` → adopted again → stop.
//
// Machine ids: `harness machines --json`. Needs `claude` on the target machine's PATH (the docker
// boxes route it through claude-code-router). Leaves nothing behind on a pass.
@@ -86,6 +88,51 @@ send('machine_select', { machineId, localProtocolVersion: 1 })
await waitFor((f) => f.type === 'connected', 15_000, 'connected')
log('connected')
+if (mode === 'agent') {
+ // An agent the app launched: `claude` exec'd by the daemon, not typed by a person.
+ const created = await rpc('agent_create', { engine: 'claude', cwd: process.env.E2E_CWD ?? '/tmp', bypassPermission: false }, 30_000)
+ if (created.error) fail(`agent_create → ${created.error} ${created.detail ?? ''}`)
+ const agentId: string = created.agent.id
+ log(`created claude agent ${agentId.slice(0, 8)} · launch=${created.agent.launch?.state}`)
+ await pollEngine(agentId, 'claude', 45_000)
+ const openId = randomUUID()
+ send('terminal_open', { requestId: openId, agentId, cols: 120, rows: 40, protocolVersion: 3 })
+ const ready = await waitFor((f) => (f.type === 'terminal_ready' || f.type === 'terminal_error') && f.payload?.requestId === openId, 15_000, 'terminal_ready')
+ if (ready.type === 'terminal_error') fail(`terminal_open → ${JSON.stringify(ready.payload)}`)
+ streamId = ready.payload.streamId
+ // Wait until the launch is confirmed ready (engine process seen), then leave claude.
+ const until = Date.now() + 45_000
+ while (Date.now() < until) {
+ const list = await rpc('agents_list', {})
+ const a = (list.agents as any[]).find((x) => x.id === agentId)
+ if (a?.launch?.state === 'ready') break
+ await sleep(1000)
+ }
+ await sleep(4000)
+ type('\r'); await sleep(2500); type('/exit\r'); await sleep(1500); type('\x03\x03')
+ await pollEngine(agentId, 'terminal', 40_000)
+ log('claude exited → engine=terminal, row kept')
+ await sleep(2000)
+ type('echo HARNESS_E2E_SHELL\r')
+ await sleep(1500)
+ if (!output.includes('HARNESS_E2E_SHELL')) fail(`no shell after the engine left; tail: ${JSON.stringify(output.slice(-300))}`)
+ log('shell answers in the same pane')
+ type('claude\r')
+ await pollEngine(agentId, 'claude', 45_000)
+ log('typed claude → adopted again')
+ await sleep(3000)
+ type('\r'); await sleep(2000); type('/exit\r'); await sleep(1500); type('\x03\x03')
+ await pollEngine(agentId, 'terminal', 40_000)
+ const deleted = await rpc('agent_delete', { agentId })
+ if (!deleted.deleted) fail(`agent_delete → ${JSON.stringify(deleted)}`)
+ await waitFor((f) => f.type === 'agent_deleted' && f.payload?.agentId === agentId, 15_000, 'agent_deleted')
+ await sleep(1500)
+ if (await engineOf(agentId) !== null) fail('agent still listed after delete')
+ log('deleted · gone')
+ console.log(`[${label}] PASS (agent)`)
+ process.exit(0)
+}
+
// 1. create
const created = await rpc('agent_create', { engine: 'terminal' }, 30_000)
if (created.error) fail(`agent_create → ${created.error} ${created.detail ?? ''}`)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index af6392d2e..bd6b8873f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -82,7 +82,7 @@ import { createAndRegisterPane } from './lib/createAgentPane.js'
import { restoreAgents } from './lib/restoreAgents.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
import { prepareCodexResume } from './engines/codex/portableHistory.js'
-import { buildHarnessSessionLabel, isHarnessSessionFor } from './lib/harnessSessionLabel.js'
+import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
import { listTmuxPanes } from './lib/tmuxAgentDiscovery.js'
import { installedDsh } from './dsh/installed.js'
import { dshVerdictPath, dshViewerName } from './dsh/manifest.js'
@@ -2738,11 +2738,15 @@ async function runForeground(session: AuthSession): Promise<void> {
questionWatcher.stop(agent.sessionId)
stopHeartbeat(agent.sessionId)
}
- // The engine somebody started inside a terminal has exited: the pane is a shell at its prompt
- // again, so the row goes back to being a terminal — live, not dormant — and the dial, which
- // only ever saw it as an agent, is told it is gone. The web/app side gets the same row with
- // its engine back to `terminal` and draws it as one.
- if (agent.terminalHost) {
+ // The engine has exited and its pane is a shell at its prompt (every launch runs the engine
+ // inside the pane's shell — engineLaunch.ts `harness_engine` — and so does a terminal somebody
+ // typed it into): the row becomes a terminal — live, not dormant — and the dial, which only
+ // ever knew it as an agent, is told it is gone. The app gets the same row with its engine
+ // now `terminal` and draws it as one. Not while the launch is still `starting`: a pane with
+ // no engine process yet is an install in progress, not an exit, and releasing it would wipe
+ // the grid/profile/DSH the launch is about to use. Not for a pane that is dead either — that
+ // one is on its way to `onRemoved`.
+ if (agent.launch?.state !== 'starting') {
const released = registry.releaseEngine(agent.agentId)
if (released) {
syncRecapPool()
@@ -3736,12 +3740,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// and a pane that outlived the daemon in a session discovery no longer lists still has its
// engine, which a second pane resuming the same session would collide with.
liveProcess: (entry, runtime) => resolvePaneEngineProcess(runtime.paneId, entry.engine),
- liveTerminalPane: async (runtime) => {
+ livePane: async (runtime) => {
const inventory = await listTmuxPanes()
- if (!inventory.ok) return false
- // Its OWN session, not just any harness pane: a new tmux server hands out `%N` from zero
- // again, and a stale id can name another agent's pane.
- return inventory.panes.some((pane) => pane.tmuxPane === runtime.paneId && isHarnessSessionFor(pane.tmuxSessionName, 'terminal'))
+ // Only a harness pane counts (the inventory is already that whitelist): a new tmux server
+ // hands out `%N` from zero again, and a stale id can name somebody's own shell.
+ return inventory.ok && inventory.panes.some((pane) => pane.tmuxPane === runtime.paneId)
},
buildLaunch: async (entry, opts) => {
// Mirrors `agent_create`: the same grid env/argv (and the same vendor variables cleared), or
@@ -4131,6 +4134,18 @@ async function runForeground(session: AuthSession): Promise<void> {
console.warn(`[agent] create failed · ${engine} · ${detail}`)
return
}
+ // The engine started and was gone again before it was ever seen (a flag it refused, a
+ // config it could not read): its wrapper has handed the pane to a shell with the engine's
+ // own words on screen. That pane is a terminal, and the row says so — the person reads
+ // the error where it was printed and types the command again, rather than being handed a
+ // "Start failed" tile they cannot type into.
+ if (paneState.engineExit !== null) {
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ const released = registry.releaseEngine(pending.agentId)
+ if (released) announceSession(released)
+ console.warn(`[agent] create · ${engine} exited (${paneState.engineExit}) before ready · agent ${pending.agentId} kept as a terminal`)
+ return
+ }
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, delayMs)
timer.unref?.()
@@ -4449,11 +4464,12 @@ async function runForeground(session: AuthSession): Promise<void> {
}
forgetSession(sessionId, { force: true })
if (!s) return
- // Stopping a terminal is closing it: there is no engine pid to signal, the shell IS the thing,
- // and a shell left running in a pane nobody can see any more is a leak. A terminal that adopted
- // an engine goes the same way — the person pressed Stop on the tile, not on the engine — so
- // the pane is killed alongside the engine's own termination below.
- if (s.terminalHost && tmuxBackend) {
+ // Stopping is closing the pane. Every pane is a shell with the engine inside it now, so signalling
+ // the engine alone would leave a shell running in a pane nobody can see any more — a leak, and
+ // for a bare terminal there is no engine pid to signal at all. The engine's own termination
+ // below stays as the belt to this: a pane kill that does not land must not leave a live engine
+ // the UI already calls gone.
+ if (tmuxBackend) {
const runtimes = s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
void Promise.all(runtimes.map((runtime) => tmuxBackend.kill(runtime))).then(() => {
console.log(`[delete] ${sid(sessionId)} terminal · pane closed`)
diff --git a/cli/src/lib/binaryOnPath.ts b/cli/src/lib/binaryOnPath.ts
index 75999ab0a..e1234616d 100644
--- a/cli/src/lib/binaryOnPath.ts
+++ b/cli/src/lib/binaryOnPath.ts
@@ -11,12 +11,20 @@ import { accessSync, constants } from 'node:fs'
import { delimiter, join } from 'node:path'
export function binaryOnPath(command: string, env: NodeJS.ProcessEnv = process.env): boolean {
- if (!command) return false
+ return resolveBinaryOnPath(command, env) !== null
+}
+
+/** The same lookup, answering WHERE — the first executable PATH entry that has it, or null. */
+export function resolveBinaryOnPath(command: string, env: NodeJS.ProcessEnv = process.env): string | null {
+ if (!command) return null
const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : ['']
const candidates = command.includes('/') || command.includes('\\')
? [command]
: (env.PATH ?? '').split(delimiter).filter(Boolean).map((dir) => join(dir, command))
- return candidates.some((candidate) => extensions.some((extension) => {
- try { accessSync(candidate + extension, constants.X_OK); return true } catch { return false }
- }))
+ for (const candidate of candidates) {
+ for (const extension of extensions) {
+ try { accessSync(candidate + extension, constants.X_OK); return candidate + extension } catch { /* next */ }
+ }
+ }
+ return null
}
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 541957bd5..a71df81d3 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -15,6 +15,7 @@ import {
buildEngineCommandArgv,
buildEngineLaunchArgv,
commandAvailableInInteractiveShell,
+ engineFallbackPrelude,
firstPromptArgs,
gridPanePrelude,
harnessNodePrelude,
@@ -23,7 +24,7 @@ import {
supportsNamedAgent,
unreadableCwdGuard,
} from './engineLaunch.js'
-import { ENGINES } from '../engines/types.js'
+import { ENGINES, type AgentEngine } from '../engines/types.js'
import { engineBin } from './engineBin.js'
import type { EngineInstallRecipe } from './engineInstall.js'
import { MIN_OPEN_FILES, RAISE_OPEN_FILES_SH } from './openFiles.js'
@@ -38,29 +39,68 @@ afterAll(() => { if (developersOwnGridBin !== undefined) process.env.HARNESS_GRI
/** The prelude every case below gets by default: no managed grid on this machine, so PATH is left
* alone and only grid's update check is turned off. */
const GRID_PRELUDE = gridPanePrelude('grid')
+/** The engine-in-a-shell wrapper every launch carries, for the shell each case names — see
+ * `engineFallbackPrelude`. `null` tmux: the suite must not depend on what this machine has. */
+const FALLBACK = (engine: AgentEngine, shell: string) => engineFallbackPrelude(engine, shell, null)
+const NO_TMUX = null
describe('buildEngineLaunchArgv', () => {
it('wraps zsh in its interactive login form and execs the resolved binary', () => {
- expect(buildEngineLaunchArgv('claude', {}, '/bin/zsh')).toEqual([
- '/bin/zsh', '-lic', `${RAISE_OPEN_FILES_SH}${GRID_PRELUDE}exec "$@"`, 'harness-engine', engineBin('claude'),
+ expect(buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, undefined, NO_TMUX)).toEqual([
+ '/bin/zsh', '-lic', `${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`, 'harness-engine', engineBin('claude'),
])
})
it('uses Ubuntu bash interactive startup files without making it a login shell', () => {
- expect(buildEngineLaunchArgv('claude', {}, '/bin/bash')).toEqual([
- '/bin/bash', '-ic', `${RAISE_OPEN_FILES_SH}${GRID_PRELUDE}exec "$@"`, 'harness-engine', engineBin('claude'),
+ expect(buildEngineLaunchArgv('claude', {}, '/bin/bash', undefined, undefined, NO_TMUX)).toEqual([
+ '/bin/bash', '-ic', `${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/bash')}${GRID_PRELUDE}harness_engine "$@"`, 'harness-engine', engineBin('claude'),
])
})
it('enters the workspace only after interactive startup has completed', () => {
- const argv = buildEngineLaunchArgv('claude', { cwd: '/work/project' }, '/bin/zsh')
+ const argv = buildEngineLaunchArgv('claude', { cwd: '/work/project' }, '/bin/zsh', undefined, undefined, NO_TMUX)
expect(argv).toEqual([
'/bin/zsh', '-lic',
- `${RAISE_OPEN_FILES_SH}${GRID_PRELUDE}if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; exit 1; fi\n${unreadableCwdGuard(process.platform)}shift\nexec "$@"`,
+ `${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; exit 1; fi\n${unreadableCwdGuard(process.platform)}shift\nharness_engine "$@"`,
'harness-engine', '/work/project', engineBin('claude'),
])
})
+ describe('the engine runs INSIDE the pane shell (`harness_engine`), never exec\'d over it', () => {
+ const run = (argv: string[]) => {
+ try {
+ return { status: 0, out: execFileSync(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'pipe'] }).toString() }
+ } catch (error) {
+ const failed = error as { status: number | null; stdout: Buffer; stderr: Buffer }
+ return { status: failed.status, out: `${failed.stdout}${failed.stderr}` }
+ }
+ }
+ it('hands the engine its argv untouched, and without a terminal on stdin reports its exit status', () => {
+ const argv = buildEngineLaunchArgv('claude', {}, '/bin/sh', undefined, undefined, NO_TMUX)
+ // The launcher's own argv, then the "engine": `sh -c 'echo …; exit 3'` stands in for one.
+ const script = [argv[0], argv[1], argv[2], 'harness-engine', '/bin/sh', '-c', 'printf "%s\\n" "args:$*"; exit 3', 'engine', 'a b', '--flag']
+ const result = run(script)
+ expect(result.out).toContain('args:a b --flag')
+ expect(result.status).toBe(3)
+ // No shell was handed over and no "this pane is a shell now" line was printed: no tty.
+ expect(result.out).not.toContain('This pane is a shell now')
+ })
+ it('a command that does not exist still ends the pane with 127, so "not installed" stays a launch failure', () => {
+ const argv = buildEngineLaunchArgv('claude', {}, '/bin/sh', undefined, undefined, NO_TMUX)
+ expect(run([argv[0], argv[1], argv[2], 'harness-engine', '/nowhere/claude-that-is-not-here']).status).toBe(127)
+ })
+ it('marks the pane with the exit status through the daemon\'s own tmux, and only then hands over a shell', () => {
+ const prelude = engineFallbackPrelude('codex', '/bin/bash', '/opt/homebrew/bin/tmux')
+ expect(prelude).toContain(`'/opt/homebrew/bin/tmux' set-option -p -t "$TMUX_PANE" @harness_engine_exit "$harness_status"`)
+ expect(prelude.indexOf('set-option')).toBeLessThan(prelude.indexOf("exec '/bin/bash'"))
+ expect(prelude).toContain('if [ "$harness_status" -eq 127 ]; then exit 127; fi')
+ // zsh is a login shell; bash keeps its interactive rc (same rule as a terminal).
+ expect(engineFallbackPrelude('codex', '/bin/zsh', null)).toContain("exec '/bin/zsh' -l\n")
+ expect(engineFallbackPrelude('codex', '/bin/bash', null)).toContain("exec '/bin/bash'\n")
+ expect(engineFallbackPrelude('codex', '/bin/bash', null)).not.toContain('set-option')
+ })
+ })
+
describe('a terminal (engine `terminal`)', () => {
it('is the login shell itself behind a non-interactive wrapper that only raises the limit and enters the folder', () => {
expect(buildEngineLaunchArgv('terminal', { cwd: '/work/project' }, '/bin/zsh')).toEqual([
@@ -211,13 +251,14 @@ describe('buildEngineLaunchArgv', () => {
})
it('a DSH agent gets Harness\'s Node at the end of a PATH that has none; a plain launch is unchanged', () => {
- const argv = buildEngineLaunchArgv('claude', { harnessNode: true }, '/bin/zsh', '/opt/harness runtime/bin/node')
- // On this branch every pane script opens with the open-files raise and the grid prelude; the Node
- // line lands after them, and a launch without `harnessNode` is exactly the baseline above.
- expect(argv[2]).toBe(`${RAISE_OPEN_FILES_SH}${GRID_PRELUDE}${harnessNodePrelude('/opt/harness runtime/bin/node')}exec "$@"`)
+ const argv = buildEngineLaunchArgv('claude', { harnessNode: true }, '/bin/zsh', '/opt/harness runtime/bin/node', undefined, NO_TMUX)
+ // On this branch every pane script opens with the open-files raise, the engine-in-a-shell
+ // wrapper and the grid prelude; the Node line lands after them, and a launch without
+ // `harnessNode` is exactly the baseline above.
+ expect(argv[2]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}${harnessNodePrelude('/opt/harness runtime/bin/node')}harness_engine "$@"`)
expect(harnessNodePrelude('/opt/harness runtime/bin/node')).toBe(
'if ! command -v node >/dev/null 2>&1; then PATH="${PATH:+$PATH:}"\'/opt/harness runtime/bin\'; export PATH; fi\n')
- expect(buildEngineLaunchArgv('claude', { harnessNode: false }, '/bin/zsh')[2]).toBe(`${RAISE_OPEN_FILES_SH}${GRID_PRELUDE}exec "$@"`)
+ expect(buildEngineLaunchArgv('claude', { harnessNode: false }, '/bin/zsh', undefined, undefined, NO_TMUX)[2]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`)
})
it('the DSH prelude, run by a real shell, reaches the engine\'s PATH only when node is missing', () => {
@@ -502,7 +543,7 @@ describe('buildEngineLaunchArgv — the grid the pane finds', () => {
expect(script).toContain(`PATH='/opt/harness/runtime/grid-0.3.47-darwin-arm64'"\${PATH:+:$PATH}"\nexport PATH\n`)
expect(script).toContain('GRID_NO_UPDATE_CHECK=1\nexport GRID_NO_UPDATE_CHECK\n')
- expect(script.indexOf('export GRID_NO_UPDATE_CHECK')).toBeLessThan(script.indexOf('exec "$@"'))
+ expect(script.indexOf('export GRID_NO_UPDATE_CHECK')).toBeLessThan(script.indexOf('harness_engine "$@"'))
})
it('leaves PATH alone when grid is only a name on it, but still turns the update check off', () => {
@@ -561,7 +602,7 @@ describe('buildEngineLaunchArgv with installFirst', () => {
buildEngineLaunchArgv('opencode', { installFirst: install }, '/bin/zsh')[2]
it('leaves the plain launch alone when nothing has to be installed', () => {
- expect(buildEngineLaunchArgv('opencode', {}, '/bin/zsh')[2]).toBe(`${RAISE_OPEN_FILES_SH}${GRID_PRELUDE}exec "$@"`)
+ expect(buildEngineLaunchArgv('opencode', {}, '/bin/zsh', undefined, undefined, NO_TMUX)[2]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('opencode', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`)
})
it('keeps the engine argv positional, so the shell never re-parses a path or a flag', () => {
@@ -571,7 +612,7 @@ describe('buildEngineLaunchArgv with installFirst', () => {
}, '/bin/zsh')
expect(argv.slice(0, 2)).toEqual(['/bin/zsh', '-lic'])
expect(argv.slice(3)).toEqual(['harness-engine', ...buildEngineCommandArgv('opencode', { bypassPermission: true })])
- expect(argv[2]).toContain('exec "$@"')
+ expect(argv[2]).toContain('harness_engine "$@"')
})
it('runs the engine only when the install succeeded', async () => {
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 9605b3896..a0d029274 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -2,12 +2,13 @@ import { execFile } from 'node:child_process'
import { homedir, userInfo } from 'node:os'
import { isAbsolute, basename, dirname, join } from 'node:path'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
-import { binaryOnPath } from './binaryOnPath.js'
+import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'
import { engineBin } from './engineBin.js'
import type { EngineInstallRecipe } from './engineInstall.js'
import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from './gridExec.js'
import { managedNodePath } from './nodeRuntime.js'
import { RAISE_OPEN_FILES_SH } from './openFiles.js'
+import { ENGINE_EXIT_PANE_OPTION } from './tmux.js'
/**
* Best-effort "skip permission prompts" flag per engine, confirmed against each vendor's own docs.
@@ -364,18 +365,20 @@ export function buildEngineLaunchArgv(
shell: string | undefined = undefined,
runtimeNode: string = managedNodePath(),
gridBinary: string = gridBinaryPath(),
+ tmuxBinary: string | null = resolveBinaryOnPath('tmux'),
): string[] {
if (isTerminalEngine(engine)) return buildTerminalLaunchArgv(opts, shell)
const command = buildEngineCommandArgv(engine, opts)
const interactive = interactiveEngineShell(shell)
if (!interactive) return command
+ const enginePrelude = engineFallbackPrelude(engine, interactive.path, tmuxBinary)
// The clear comes FIRST, before the install as well as before the engine. An installer is a child
// of this shell and inherits what it inherits: `npm` is not going to spend someone's Anthropic key,
// but an install script that probes for credentials to configure itself would, and the whole point
// of this launch is that the agent's environment is the one the user asked for.
// Then the grid's PATH entry at the FRONT (its dir holds only `grid`), and — for a DSH agent — Harness's
// Node at the END, only when the shell found none. The two never meet: one prepends, one appends.
- const prelude = clearEnvPrelude(opts.clearEnv) + gridPanePrelude(gridBinary) + (opts.harnessNode ? harnessNodePrelude(runtimeNode) : '')
+ const prelude = enginePrelude + clearEnvPrelude(opts.clearEnv) + gridPanePrelude(gridBinary) + (opts.harnessNode ? harnessNodePrelude(runtimeNode) : '')
// rc files (notably nvm) call getcwd() before running this command. Start the shell in a safe
// directory and enter the selected workspace only after those files have loaded: an IDE can replace
// a workspace inode between the desktop picker resolving it and tmux spawning the pane.
@@ -388,7 +391,7 @@ export function buildEngineLaunchArgv(
? installIfMissingThenExecScript(opts.installIfMissing, runtimeNode)
: opts.installFirst
? installThenExecScript(opts.installFirst)
- : 'exec "$@"'
+ : 'harness_engine "$@"'
// The open-files raise goes ahead of everything, the installer included: a pane inherits the tmux
// SERVER's soft limit, which is launchd's 256 whenever the desktop app started the daemon that
// started the server, and an engine (Claude Code refuses outright) or an npm install under 256 is
@@ -396,6 +399,46 @@ export function buildEngineLaunchArgv(
return [interactive.path, ...interactive.args, RAISE_OPEN_FILES_SH + prelude + cwdPrelude + body, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command]
}
+/**
+ * The shell function every engine launch runs its engine through, instead of a bare `exec`.
+ *
+ * The engine is a CHILD of the pane's shell, and when it exits — `/exit`, Ctrl-C, a crash — the
+ * pane does not die with it: the wrapper records the exit status on the pane (`ENGINE_EXIT_PANE_OPTION`,
+ * which is how the daemon tells "the engine left" from "the install is still running") and `exec`s
+ * the user's interactive shell in its place, exactly as a terminal opened with ⌘⇧T is. The daemon
+ * then turns the row back into a terminal (`registry.releaseEngine`) rather than deleting it, and
+ * typing the engine's name into that shell adopts it again (`adoptEngine`). A 127 is the one exit
+ * that still ends the pane: the command was not found at all, and "not installed" needs to stay
+ * a failure the app can name rather than a prompt with an error above it.
+ *
+ * `tmuxBinary` is the daemon's own tmux, quoted into the script, because the pane's shell may not
+ * have it on PATH (the managed runtime never is). Without one the marker is skipped and the fallback
+ * still happens — only a failure at launch then takes the daemon's full wait to notice.
+ *
+ * Without a terminal on stdin there is nobody to hand a shell to, so the function exits with the
+ * engine's status instead — which is also what keeps the specs that run these scripts honest.
+ *
+ * `"$@" || status=$?` rather than `"$@"; status=$?`: a rc file that turned on `set -e` would end
+ * the script on the engine's non-zero exit before the fallback ran (see RAISE_OPEN_FILES_SH).
+ */
+export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tmuxBinary: string | null): string {
+ const loginArgs = basename(shellPath).toLowerCase() === 'zsh' ? ' -l' : ''
+ const mark = tmuxBinary && isAbsolute(tmuxBinary)
+ ? ` [ -n "$TMUX_PANE" ] && ${shellSingleQuote(tmuxBinary)} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1 || true\n`
+ : ''
+ return 'harness_engine() {\n'
+ + ' harness_status=0\n'
+ + ' "$@" || harness_status=$?\n'
+ + ' if [ "$harness_status" -eq 127 ]; then exit 127; fi\n'
+ + mark
+ // Only a pane — something with a terminal on stdin — gets a shell to type into. Run without one
+ // (a spec exercising the script, a wrapper piped somewhere) the engine's own status is the answer.
+ + ' if ! [ -t 0 ]; then exit "$harness_status"; fi\n'
+ + ` printf '\\n%s\\n' ${shellSingleQuote(`harness: ${engine} exited ($harness_status). This pane is a shell now — run ${engine} again, or stop the pane.`).replace('($harness_status)', `('"$harness_status"')`)}\n`
+ + ` exec ${shellSingleQuote(shellPath)}${loginArgs}\n`
+ + '}\n'
+}
+
/**
* Full argv for a plain terminal pane: the user's login shell, nothing exec'd over it.
*
@@ -488,7 +531,7 @@ function clearEnvPrelude(names: readonly string[] | undefined): string {
function installThenExecScript(install: string): string {
return [
`printf '%s\\n' 'harness: installing the engine — this pane becomes the agent when it finishes' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
- `if eval ${JSON.stringify(install)}; then exec "$@"; fi`,
+ `if eval ${JSON.stringify(install)}; then harness_engine "$@"; fi`,
`printf '\\n%s\\n' 'harness: the install failed, so the agent was not started. The command is above; fix it and create the agent again.'`,
'exit 1',
].join('\n')
@@ -605,7 +648,7 @@ function installIfMissingThenExecScript(recipe: EngineInstallRecipe, runtimeNode
' shift',
' if ! resolve_engine "$candidate"; then return 1; fi',
' shift',
- ' exec "$resolved" "$@"',
+ ' harness_engine "$resolved" "$@"',
'}',
'try_engine "$1" "$@" || true',
tryCandidates,
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 39e3d450a..e63a6083c 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1650,10 +1650,12 @@ describe('a terminal: a pane that becomes an engine and back', () => {
expect(registry.byProcess('claude', processIdentity(912))).toBeUndefined()
expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
expect(registry.terminalAvailable(opened.agentId)).toBe(true)
- // Not a terminal any more? Nothing to release. A plain agent? Never.
+ // Already a terminal? Nothing to release. A plain agent whose engine exited? A terminal from now on.
expect(registry.releaseEngine(opened.agentId)).toBeNull()
const plain = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/x' })!
- expect(registry.releaseEngine(plain.agentId)).toBeNull()
+ expect(plain.terminalHost).toBeUndefined()
+ expect(registry.releaseEngine(plain.agentId)).toMatchObject({ engine: 'terminal', terminalHost: true, active: true })
+ expect(registry.byRuntimeTerminal({ backend: 'tmux', paneId: '%10' })?.agentId).toBe(plain.agentId)
// And the next engine typed into the same shell is adopted just the same.
expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(913))).toMatchObject({ engine: 'codex' })
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index c08878bb5..13057fcc0 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -1425,19 +1425,24 @@ class Registry {
}
/**
- * The engine that was started inside a terminal has exited: the row is a terminal again.
+ * The engine in this pane has exited and the pane is a shell now: the row is a terminal.
*
- * Everything that belonged to the engine goes — session, transcript, process, grid, profile,
- * model, permission choices — because the next thing typed into this shell may be a different
- * engine, and `unboundRouteOwner` only claims a route for a row with no session. The row itself,
- * its id, its pane and its name stay: this is the opposite of dormant, the terminal is live.
+ * For every agent, not only one that began as a terminal — an engine the app launched runs
+ * inside its pane's shell too (engineLaunch.ts `harness_engine`), and `/exit` or Ctrl-C leaves
+ * that shell at its prompt with the engine's last screen above it. Everything that belonged to
+ * the engine goes — session, transcript, process, grid, profile, model, permission choices —
+ * because the next thing typed into this shell may be a different engine, and `unboundRouteOwner`
+ * only claims a route for a row with no session. The row itself, its id, its pane and its name
+ * stay: this is the opposite of dormant, the terminal is live. `terminalHost` is set from here on,
+ * since that is what the pane now is.
*/
releaseEngine(agentId: string): RegisteredSession | null {
const entry = this.agents.get(agentId)
- if (!entry || !entry.terminalHost || isTerminalEngine(entry.engine)) return null
+ if (!entry || isTerminalEngine(entry.engine)) return null
this.drop(entry)
this.releaseBinding(entry)
entry.engine = 'terminal'
+ entry.terminalHost = true
entry.processIdentity = null
entry.launch = { state: 'ready' }
entry.active = true
diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.ts
index 892295600..840c1d6c8 100644
--- a/cli/src/lib/restoreAgents.spec.ts
+++ b/cli/src/lib/restoreAgents.spec.ts
@@ -50,7 +50,7 @@ interface Harness {
launched: Array<{ agentId: string; launch: RestoreLaunch }>
/** Per-pane scripted answers for probeProcess; shifted on each call. */
probes: Map<string, Array<ProcessIdentity | null>>
- states: Map<string, Array<{ dead: boolean } | null>>
+ states: Map<string, Array<{ dead: boolean; engineExit?: number | null } | null>>
nextPane: string[]
paneCreates: number
respawns: number
@@ -58,7 +58,7 @@ interface Harness {
released: string[]
}
-function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; liveTerminalPanes?: string[]; failCreate?: boolean; refuseLaunch?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {
+function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; alivePanes?: string[]; failCreate?: boolean; refuseLaunch?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {
const h: Harness = {
calls: [],
rows: new Map(rows.map((r) => [r.agentId, r])),
@@ -105,7 +105,7 @@ function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; liveTe
return r
},
},
- liveTerminalPane: async (runtime) => (opts.liveTerminalPanes ?? []).includes(runtime.paneId),
+ livePane: async (runtime) => (opts.alivePanes ?? []).includes(runtime.paneId),
liveProcess: async (_entry, runtime) => live.has(runtime.paneId) ? identity(1000 + Number(runtime.paneId.slice(1))) : null,
buildLaunch: async (entry, o) => {
h.launches.push({ agentId: entry.agentId, ...(o.resumeSessionId ? { resumeSessionId: o.resumeSessionId } : {}) })
@@ -389,7 +389,7 @@ describe('restoreAgents — terminals', () => {
row({ agentId: 'term-1', engine: 'terminal', terminalHost: true, sessionId: '', boundAt: null, ...overrides })
it('leaves a terminal whose pane is still there alone — a shell has no engine process to look for', async () => {
- const h = harness([terminal()], { liveTerminalPanes: ['%3'] })
+ const h = harness([terminal()], { alivePanes: ['%3'] })
const summary = await restoreAgents(h.deps)
expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
expect(h.paneCreates).toBe(0)
@@ -412,7 +412,7 @@ describe('restoreAgents — terminals', () => {
})
it('puts a terminal whose adopted engine exited while the daemon was down back to a shell, pane kept', async () => {
- const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1, processIdentity: identity(7) })], { liveTerminalPanes: ['%3'] })
+ const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1, processIdentity: identity(7) })], { alivePanes: ['%3'] })
const summary = await restoreAgents(h.deps)
expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
expect(h.calls).toEqual(['releaseEngine:term-1'])
@@ -420,13 +420,33 @@ describe('restoreAgents — terminals', () => {
})
it('keeps a terminal whose adopted engine is still running exactly as an agent', async () => {
- const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })], { liveTerminalPanes: ['%3'], livePanes: ['%3'] })
+ const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })], { alivePanes: ['%3'], livePanes: ['%3'] })
const summary = await restoreAgents(h.deps)
expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
expect(h.calls).toEqual(['updateIdentity:term-1:1003'])
expect(h.rows.get('term-1')?.engine).toBe('claude')
})
+ it('an ordinary agent whose engine exited while the daemon was down, pane alive, becomes a terminal — no second pane', async () => {
+ const h = harness([row({ agentId: 'agent-a', terminalHost: true })], { alivePanes: ['%3'] })
+ // `terminalHost` is what releaseEngine's stub keys on; the real registry sets it for any row.
+ const summary = await restoreAgents(h.deps)
+ expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
+ expect(h.paneCreates).toBe(0)
+ expect(h.calls).toEqual(['releaseEngine:agent-a'])
+ expect(h.rows.get('agent-a')).toMatchObject({ engine: 'terminal', sessionId: '' })
+ })
+
+ it('an engine that exits during a restore (its pane fell back to a shell) is relaunched fresh, like a dead pane', async () => {
+ const h = harness([row()], { settleMs: 20 })
+ h.probes.set('%0', [identity(500), identity(501)])
+ h.states.set('%0', [{ dead: false, engineExit: 1 }, { dead: false }, { dead: false }, { dead: false }])
+ await restoreAgents(h.deps)
+ await settled(h, 1, 1)
+ expect(h.respawns).toBe(1)
+ expect(h.launches).toEqual([{ agentId: 'agent-a', resumeSessionId: 'session-a' }, { agentId: 'agent-a' }])
+ })
+
it('brings a terminal whose adopted engine AND pane are gone back as a shell, never as the engine', async () => {
const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })])
const summary = await restoreAgents(h.deps)
diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.ts
index 575315bac..1ce28bafd 100644
--- a/cli/src/lib/restoreAgents.ts
+++ b/cli/src/lib/restoreAgents.ts
@@ -57,12 +57,12 @@ export interface RestoreAgentsDeps {
releaseEngine(agentId: string): RegisteredSession | null
}
/**
- * Whether a TERMINAL's pane is still there — a live pane in a session this daemon named for a
- * terminal. A terminal has no engine process to find (`liveProcess` answers null for one by
- * construction), so pane existence is its liveness. Optional so a caller without tmux inventory
- * (tests) treats every terminal pane as gone.
+ * Whether the row's PANE is still there — a live pane in a session this daemon created. Every
+ * pane is a shell with the engine inside it, so a pane can outlive its engine: that is a terminal
+ * (a bare one has no engine process to find at all), not a pane to rebuild. Optional so a caller
+ * without tmux inventory (tests) treats a pane with no engine process as gone.
*/
- liveTerminalPane?: (runtime: TmuxRuntimeRef) => Promise<boolean>
+ livePane?: (runtime: TmuxRuntimeRef) => Promise<boolean>
/** The engine process still running in this row's pane, or null when tmux does not know the pane
* at all — including when no tmux server is running — or the pane has become something else. */
liveProcess: (entry: RegisteredSession, runtime: TmuxRuntimeRef) => Promise<ProcessIdentity | null>
@@ -77,8 +77,9 @@ export interface RestoreAgentsDeps {
respawn: (runtime: TmuxRuntimeRef, launch: RestoreLaunch) => Promise<{ ok: boolean; reason?: string }>
/** One probe of the pane for a recognizable engine process. */
probeProcess: (runtime: TmuxRuntimeRef, engine: AgentEngine) => Promise<ProcessIdentity | null>
- /** Null when tmux no longer knows the pane. */
- paneState: (runtime: TmuxRuntimeRef) => Promise<{ dead: boolean } | null>
+ /** Null when tmux no longer knows the pane. `engineExit` set: the engine left and the pane is a
+ * shell now (`ENGINE_EXIT_PANE_OPTION`), which for a restore is the same news as `dead`. */
+ paneState: (runtime: TmuxRuntimeRef) => Promise<{ dead: boolean; engineExit?: number | null } | null>
clearRemainOnExit: (runtime: TmuxRuntimeRef) => Promise<void>
holdRoute: (routeKey: string, autoReleaseMs: number) => void
releaseRoute: (routeKey: string) => void
@@ -123,7 +124,7 @@ async function waitForSettle(deps: RestoreAgentsDeps, runtime: TmuxRuntimeRef, s
while (Date.now() < until) {
await sleep(Math.min(SETTLE_POLL_MS, until - Date.now()))
const state = await deps.paneState(runtime)
- if (!state || state.dead) return 'gone'
+ if (!state || state.dead || state.engineExit != null) return 'gone'
}
return 'settled'
}
@@ -140,23 +141,28 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum
const runtime = tmuxRuntime(entry)
if (!runtime) { summary.skipped.push({ agentId: entry.agentId, reason: 'no tmux pane' }); continue }
if (entry.launch?.state === 'failed') { summary.skipped.push({ agentId: entry.agentId, reason: 'last launch failed' }); continue }
- // A terminal — bare, or one that adopted an engine — is alive as long as its PANE is: the shell
- // is what the person opened, and it survives whatever was typed into it. An adopted engine that
- // exited while the daemon was down is exactly the exit the reconciler would have caught, so the
- // row is put back to a terminal here; a pane that is gone comes back below as a terminal, too,
- // never as the engine (its session is gone with the pane).
- if (entry.terminalHost) {
- const paneAlive = await deps.liveTerminalPane?.(runtime) ?? false
- if (paneAlive) {
- const engineLive = isTerminalEngine(entry.engine) ? null : await deps.liveProcess(entry, runtime)
- if (engineLive) {
- if (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, engineLive)
- } else if (!isTerminalEngine(entry.engine)) {
- deps.registry.releaseEngine(entry.agentId)
- deps.log(`[restore] ${entry.engine} → terminal · agent ${entry.agentId} · its engine exited while the daemon was down`)
- }
- continue
+ // A pane is alive as long as tmux has it, whatever runs in it: every pane is a shell with the
+ // engine inside, so an engine that exited while the daemon was down left a shell at its prompt
+ // — exactly the exit the reconciler would have caught — and the row is put back to a terminal
+ // here rather than a second pane being opened beside the first. A bare terminal has no engine
+ // process to look for at all.
+ const paneAlive = await deps.livePane?.(runtime) ?? false
+ if (paneAlive) {
+ const engineLive = isTerminalEngine(entry.engine) ? null : await deps.liveProcess(entry, runtime)
+ if (engineLive) {
+ // Still running. A row that lost its identity without losing its pane (a reboot the boot
+ // clock misread; a tmux server that outlived the daemon) is re-identified right here, so the
+ // reconciler adopts it by process instead of treating it as an unbound route.
+ if (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, engineLive)
+ } else if (!isTerminalEngine(entry.engine)) {
+ deps.registry.releaseEngine(entry.agentId)
+ deps.log(`[restore] ${entry.engine} → terminal · agent ${entry.agentId} · its engine exited while the daemon was down`)
}
+ continue
+ }
+ // A terminal whose pane is gone comes back as a terminal — never as the engine that was once
+ // typed into it: that engine's session went with the pane.
+ if (entry.terminalHost) {
if (!isTerminalEngine(entry.engine)) deps.registry.releaseEngine(entry.agentId)
missing.push({ entry: deps.registry.byAgent(entry.agentId) ?? entry, runtime })
continue
@@ -308,7 +314,7 @@ async function watchRestoredPane(
fail('ENGINE_DID_NOT_START', `${engine}'s restored pane disappeared before its engine process became ready.`)
return
}
- if (state.dead) {
+ if (state.dead || state.engineExit != null) {
if (!await relaunchFresh()) return
delayMs = 50
continue
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 5145f3686..77796c83b 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -835,11 +835,21 @@ export function setPaneWindowStyle(pane: string, style: string): Promise<boolean
}
/** What tmux knows about a pane right now. See `agentCreateDiagnosis.ts` for why this is read. */
+/**
+ * The pane option an engine's launch wrapper sets when the engine exits and the pane falls back to
+ * a shell (engineLaunch.ts, `harness_engine`): the engine's exit status. Empty/absent while the
+ * wrapper is still running the engine — and for the whole life of the fallback shell after that,
+ * once something reads it, so `respawn` clears it before every new launch in the same pane.
+ */
+export const ENGINE_EXIT_PANE_OPTION = '@harness_engine_exit'
+
export interface TmuxPaneState {
dead: boolean
/** Exit status once the process is gone; null while it is still running. */
exitStatus: number | null
command: string
+ /** The engine's exit status once its launch wrapper handed the pane to a shell; null before. */
+ engineExit: number | null
}
/**
@@ -850,18 +860,20 @@ export interface TmuxPaneState {
*/
export function tmuxPaneState(pane: string): Promise<TmuxPaneState | null> {
return new Promise((resolve) => {
- const format = '#{pane_dead}|#{pane_dead_status}|#{pane_current_command}'
+ const format = `#{pane_dead}|#{pane_dead_status}|#{${ENGINE_EXIT_PANE_OPTION}}|#{pane_current_command}`
execFile('tmux', ['display-message', '-p', '-t', pane, format], { timeout: 2_000 }, (err, stdout) => {
if (err) { resolve(null); return }
const fields = stdout.trim().split('|')
- if (fields.length < 3) { resolve(null); return }
+ if (fields.length < 4) { resolve(null); return }
const status = Number(fields[1])
+ const engineExit = Number(fields[2])
resolve({
dead: fields[0] === '1',
exitStatus: fields[1] !== '' && Number.isSafeInteger(status) ? status : null,
+ engineExit: fields[2] !== '' && Number.isSafeInteger(engineExit) ? engineExit : null,
// A command name cannot contain `|`, but rejoining costs nothing and keeps a surprising
// one from silently truncating the field.
- command: fields.slice(2).join('|'),
+ command: fields.slice(3).join('|'),
})
})
})
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 3d10ec79f..9b998abbf 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -189,8 +189,8 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"
.resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([
// The `;` inside an argv element is never shell-interpreted — it lands as one literal token.
- 'set-option -w -t %9 remain-on-exit on ; respawn-pane -k -c /tmp/work -t %9 claude --resume abc; rm -rf /',
- 'set-option -w -t %9 remain-on-exit on ; respawn-pane -k -t %9 claude',
+ 'set-option -w -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -c /tmp/work -t %9 claude --resume abc; rm -rf /',
+ 'set-option -w -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -t %9 claude',
])
})
@@ -269,7 +269,7 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"
// `remain-on-exit` is chained BEFORE the respawn, not after: an engine handed a rejected key can
// exit before a follow-up call lands, taking its own error message down with it.
expect(readFileSync(calls, 'utf8').trim()).toBe(
- 'set-option -w -t %42 remain-on-exit on ; respawn-pane -k -c /tmp/work'
+ 'set-option -w -t %42 remain-on-exit on ; set-option -p -t %42 @harness_engine_exit ; respawn-pane -k -c /tmp/work'
+ ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_MODEL=GLM-4.7-Flash'
+ ' -t %42 /bin/zsh -lic exec "$@" harness-engine claude --resume sess-1',
)
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 84776adb7..4256da728 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -22,6 +22,7 @@ import {
import { TmuxControlStream } from './tmuxStream.js'
import {
captureTmuxPane,
+ ENGINE_EXIT_PANE_OPTION,
listPaneTitles,
LSTART_MARKER_RE,
resolvePaneEngineProcess,
@@ -164,7 +165,13 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
* instead of taking the pane down with it. Whoever calls this owns turning it back off.
*/
async respawn(runtime: TmuxRuntimeRef, request: TerminalRespawnRequest): Promise<TerminalActionResult> {
- const args = ['set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on', ';', 'respawn-pane', '-k']
+ // The engine-exit marker is the pane's, and a respawned pane is a new launch: cleared here, in
+ // the same invocation, or the new engine would read as exited the moment it started.
+ const args = [
+ 'set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on', ';',
+ 'set-option', '-p', '-t', runtime.paneId, ENGINE_EXIT_PANE_OPTION, '', ';',
+ 'respawn-pane', '-k',
+ ]
if (request.cwd) args.push('-c', request.cwd)
for (const [key, value] of Object.entries(request.env ?? {})) args.push('-e', `${key}=${value}`)
args.push('-t', runtime.paneId, ...request.command)