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.

feat: add optional engine installation, non-blocking engine probes, and persist agent launch states for UI synchronization

0xken154664ff51854e
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 04efc7538..7e7acc561 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -326,6 +326,42 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('does not let a slow engines_probe block agent_create on the same connection', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:create', {
+ sendFrame: (frame) => { frames.push(frame); return true },
+ sendBinary: () => true,
+ })
+ let finishProbe!: () => void
+ socket.engineProbeProvider = () => new Promise((resolve) => { finishProbe = () => resolve([]) })
+ const pending: RegisteredSession = {
+ schemaVersion: 2, active: true, launch: { state: 'starting' },
+ agentId: 'pending-1', sessionId: '', boundAt: null, engine: 'claude',
+ transcriptPath: null, projectDir: 'work', cwd: '/tmp/work',
+ runtimes: [{ backend: 'tmux', paneId: '%9' }], primaryRuntimeKey: 'tmux/%9', tmuxPane: '%9',
+ source: null, title: null, model: null, cliVersion: null, processIdentity: null,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+ socket.onCreateAgent = async () => ({ ok: true, session: pending })
+
+ socket.handleLocalFrame('local:create', {
+ type: 'engines_probe', payload: { requestId: 'probe-1', engines: ['claude'] },
+ })
+ socket.handleLocalFrame('local:create', {
+ type: 'agent_create', payload: { requestId: 'create-1', engine: 'claude', cwd: '/tmp/work' },
+ })
+
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_result', payload: expect.objectContaining({ requestId: 'create-1' }),
+ })))
+ expect(frames.some((frame) => frame.type === 'engines_probe_result')).toBe(false)
+ finishProbe()
+ await vi.waitFor(() => expect(frames.some((frame) => frame.type === 'engines_probe_result')).toBe(true))
+ await socket.unregisterLocalClient('local:create')
+ await socket.stop()
+ })
+
it('hands a blocked agent to the window without putting the question on the cloud leg', async () => {
const socket = new BackendSocket('token')
expect(socket.hasLocalClient()).toBe(false)
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index b67e7f644..cea7a3c4b 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -315,6 +315,8 @@ export class BackendSocket {
grid: GridLaunchOverride | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
+ /** Injectable for queue-isolation tests; production uses the machine-local probe. */
+ engineProbeProvider: typeof probeEngines = probeEngines
/**
* Called on `agent_retarget` — cli.ts re-execs an EXISTING agent's pane against a different grid,
* or, when `grid` is null, back onto its own login.
@@ -1352,19 +1354,20 @@ export class BackendSocket {
? payload.engines.filter((id): id is AgentEngine =>
typeof id === 'string' && (ENGINES as readonly string[]).includes(id))
: undefined
- const availability = await probeEngines(asked && asked.length > 0 ? asked : undefined)
- reply(type, requestId, {
- engines: availability.map((entry) => ({
- engine: entry.engine,
- installed: entry.installed,
- command: entry.command,
- installable: entry.installable,
- // The line the user is about to consent to. Sent with the probe so the dialog can name
- // it without a second round trip — and so the machine that will RUN it is the machine
- // that said what it is.
- installCommand: entry.installable ? engineInstallRecipe(entry.engine)?.command ?? null : null,
- })),
- })
+ // A full probe starts interactive login shells and is intentionally detached from this
+ // connection's ordered RPC chain. Request ids make its eventual reply safe to deliver out
+ // of order; keeping it awaited here made a Create click sit behind an unrelated sweep.
+ void this.engineProbeProvider(asked && asked.length > 0 ? asked : undefined)
+ .then((availability) => reply(type, requestId, {
+ engines: availability.map((entry) => ({
+ engine: entry.engine,
+ installed: entry.installed,
+ command: entry.command,
+ installable: entry.installable,
+ installCommand: entry.installable ? engineInstallRecipe(entry.engine)?.command ?? null : null,
+ })),
+ }))
+ .catch(() => reply(type, requestId, { error: 'ENGINE_PROBE_FAILED' }))
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index f25287096..5f77d5ebc 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -47,7 +47,7 @@ import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
import { ENGINE_CLI_COMMANDS, ENGINES, engineBin } from './lib/engineBin.js'
import type { AgentEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
-import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'
+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell } from './lib/engineLaunch.js'
import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames } from './lib/gridLaunch.js'
import { writeGridConfigDir } from './lib/gridConfigDir.js'
import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'
@@ -59,15 +59,10 @@ import { TmuxBackend } from './lib/tmuxBackend.js'
import { basename } from 'node:path'
import {
bypassPermissionActive,
- captureTmuxPane,
clearPaneRemainOnExit,
resolvePaneEngineProcess,
- resolvePaneRootProcess,
- tmuxPaneProcessTree,
tmuxPaneState,
- type TmuxPaneState,
} from './lib/tmux.js'
-import { describeAgentCreateFailure, summarizePaneOutput } from './lib/agentCreateDiagnosis.js'
import { HerdrBackend } from './lib/herdrBackend.js'
import {
discoverRunningHerdrSessions,
@@ -2274,6 +2269,9 @@ async function runForeground(session: AuthSession): Promise<void> {
beforeProbe: refreshHerdrTargets,
transaction: (apply) => registry.transaction(apply),
onDiscovered: async (observed) => {
+ const launching = observed.runtimes
+ .map((runtime) => registry.byRuntimeEngine(runtime, observed.engine))
+ .find((entry) => entry?.launch?.state !== 'ready')
const opened = registry.openProcessAgent({
engine: observed.engine,
runtimes: observed.runtimes,
@@ -2299,7 +2297,7 @@ async function runForeground(session: AuthSession): Promise<void> {
})
}
- if (opened.isNew) {
+ if (opened.isNew || launching) {
console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · terminal=${observed.primaryRuntimeKey}`)
announceSession(opened.entry)
}
@@ -2307,10 +2305,12 @@ async function runForeground(session: AuthSession): Promise<void> {
},
onObserved: async (observed, current) => {
const wasDormant = !current.active
+ const wasLaunching = current.launch?.state !== undefined && current.launch.state !== 'ready'
registry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)
registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway, observed.grid)
+ if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })
await bindObservedAgent(observed)
- if (wasDormant) {
+ if (wasDormant || wasLaunching) {
const active = registry.byAgent(current.agentId)
if (!active) return
if (active.sessionId && !await attachSession(active)) {
@@ -3059,34 +3059,19 @@ async function runForeground(session: AuthSession): Promise<void> {
// normally launched one. The key is never printed.
console.log(describeGridLaunch(engine, grid))
}
- // Is the engine even here? Asked BEFORE the pane opens, because the answer changes what the pane
- // is told to run. The New Agent dialog asked the same question through `engines_probe` and showed
- // the user the line below — but a dialog can sit open for minutes, and the machine is what
- // decides, so the check is repeated here rather than trusted from the wire. Nothing from the
- // request reaches `install`: it is looked up from our own table by engine id.
- const installFirst = await (async (): Promise<string | undefined> => {
- const recipe = engineInstallRecipe(engine)
- if (!recipe) return undefined
- try {
- if (await commandAvailableInInteractiveShell(engineBin(engine))) return undefined
- } catch {
- // The probe failing is not evidence the engine is missing. Launch as we always did and let
- // the existing diagnosis explain a real absence — prepending an install on a machine that
- // already has the engine would reinstall it behind the user's back.
- return undefined
- }
- return recipe.command
- })()
+ // Do not start a second interactive login shell merely to ask whether the engine is installed.
+ // The pane's own shell performs the same check before exec, and installs only when necessary.
+ // This removes ~1s of shell startup from the click-to-terminal critical path.
+ const installIfMissing = engineInstallRecipe(engine)?.command
// Clearing the vendor credentials this launch does NOT set is part of pointing an agent at a
// grid, not an extra. An engine chooses its provider from whatever it can see, and an inherited
// key wins on its own terms — OpenCode picked Anthropic over a grid it had been handed, and said
// only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login
// is supposed to use exactly these variables.
const clearEnv = gridLaunch ? gridConflictingEnvToClear(gridLaunch) : undefined
- const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installFirst, clearEnv }
+ const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installIfMissing, clearEnv }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
- if (installFirst) console.log(`[agent] create ${engine} · installing first · ${installFirst}`)
const spawned = await tmuxBackend.create({
cwd,
label,
@@ -3106,207 +3091,74 @@ async function runForeground(session: AuthSession): Promise<void> {
detail: spawned.reason,
}
}
- /**
- * Follow a pane through its install, for the one thing the early return leaves undone.
- *
- * `create` sets `remain-on-exit` so a pane that dies can still be read, and the discovery loop
- * clears it the moment a real agent appears. The install path returns before that loop runs, so
- * nothing would ever clear it — and an agent whose pane lingers as a corpse after the engine
- * quits behaves unlike every other agent on the machine.
- *
- * The asymmetry is deliberate and is the whole design: cleared on SUCCESS, left in place on
- * FAILURE. A failed install must keep its pane, because the npm output in it is the only
- * explanation the person will get, and this feature's answer to a failed install is to show them
- * the reason rather than retry on their behalf.
- *
- * Fire-and-forget, and it must never throw into the caller: this is bookkeeping, and an agent
- * that installed correctly is not made wrong by a tmux option that stayed set.
- */
- async function watchInstallingPane(
- runtime: TmuxRuntimeRef,
- installingEngine: AgentEngine,
- agentId: string,
- ): Promise<void> {
- // Generous, because it is bounded by the slowest thing a vendor's installer does on a cold
- // cache over a bad connection, not by anything the app is waiting for. Nothing blocks on it.
+ // A tmux route is enough to stream its screen. Register it before looking for a process so both
+ // loopback and relayed Desktop clients can attach while the login shell/installer is still busy.
+ const pending = registry.openPendingAgent({
+ engine,
+ runtimes: [spawned.runtime],
+ primaryRuntimeKey: terminalRouteKey(spawned.runtime),
+ cwd,
+ grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
+ })
+ if (!pending) {
+ await tmuxBackend.kill(spawned.runtime)
+ return { ok: false, error: 'REGISTRATION_FAILED', detail: 'tmux pane could not be registered' }
+ }
+ announceSession(pending)
+
+ const watchCreatedPane = async (): Promise<void> => {
const budgetMs = 10 * 60_000
const startedAt = Date.now()
+ let delayMs = 50
try {
while (Date.now() - startedAt < budgetMs) {
- await new Promise((resolve) => setTimeout(resolve, 3_000))
- const paneState = await tmuxPaneState(runtime.paneId)
- // Dead pane: either the install failed (keep remain-on-exit — the output IS the report) or
- // the agent was closed. Either way there is nothing left to clear.
- if (!paneState || paneState.dead) return
- // Registry entry gone — the agent was deleted while installing. Stop following it.
- if (!registry.byAgent(agentId)) return
- const live = await resolvePaneEngineProcess(runtime.paneId, installingEngine)
- if (!live) continue
- // The engine exists now. Discovery adopts the record on its own; this only returns the pane
- // to tmux's normal disposal, the same call the discovery loop makes.
- await clearPaneRemainOnExit(runtime.paneId)
- console.log(`[agent] install finished · ${installingEngine} · agent ${agentId}`)
- return
+ if (!registry.byAgent(pending.agentId)) return
+ const processIdentity = await resolvePaneEngineProcess(spawned.runtime.paneId, engine)
+ if (processIdentity) {
+ registry.updateProcessIdentity(pending.agentId, processIdentity)
+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' })
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ if (ready) announceSession(ready)
+ void agentReconciler.triggerHint(spawned.runtime, engine).catch((error) => {
+ console.warn(`[agent] background bind failed · ${engine} · ${error instanceof Error ? error.message : error}`)
+ })
+ console.log(`[agent] create ready · ${engine} · agent ${pending.agentId} · ${Date.now() - startedAt}ms`)
+ return
+ }
+ const paneState = await tmuxPaneState(spawned.runtime.paneId)
+ if (!paneState) {
+ registry.setTerminalAvailable(pending.agentId, false)
+ announceSession(pending)
+ return
+ }
+ if (paneState.dead) {
+ const installed = await commandAvailableInInteractiveShell(command[0])
+ const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'
+ const detail = installed
+ ? `${engine} exited before its engine process became ready. See the terminal output for details.`
+ : `${engine} is not installed, or its automatic install failed. See the terminal output for details.`
+ const failed = registry.setLaunch(pending.agentId, { state: 'failed', error, detail })
+ if (failed) announceSession(failed)
+ console.warn(`[agent] create failed · ${engine} · ${detail}`)
+ return
+ }
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, delayMs)
+ timer.unref?.()
+ })
+ delayMs = Math.min(delayMs * 2, 750)
}
- console.warn(`[agent] install watch gave up after ${Math.round(budgetMs / 60_000)}m · ${installingEngine} · agent ${agentId}`)
+ const detail = `${engine} did not expose an engine process within 10 minutes. The terminal remains available.`
+ const failed = registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT', detail })
+ if (failed) announceSession(failed)
+ console.warn(`[agent] create timed out · ${engine} · agent ${pending.agentId}`)
} catch (error) {
- console.warn(`[agent] install watch failed · ${installingEngine} · ${error instanceof Error ? error.message : error}`)
+ console.warn(`[agent] create watch failed · ${engine} · ${error instanceof Error ? error.message : error}`)
}
}
-
- const createdAt = Date.now()
- if (installFirst) {
- // An install runs for tens of seconds; the discovery budget below is eight, and the app gives
- // up on this reply at twenty. Waiting is therefore not on the table — the create would report
- // ENGINE_DID_NOT_START for a pane that is working perfectly.
- //
- // So the agent is registered NOW, against the process that actually owns the pane: the user's
- // shell, running the installer. That record is what the app opens a terminal onto, which is the
- // whole point — the install is watched, not waited out behind a spinner.
- //
- // It is a placeholder for seconds, not a second kind of agent. When the engine execs, discovery
- // registers it against this same pane and `openProcessAgent` ADOPTS this record in place — the
- // `routeAgent` branch in registry.ts, which matches on terminal route exactly while an agent has
- // no engine session bound. Same agentId, same tile, no flicker.
- const placeholder = await resolvePaneRootProcess(spawned.runtime.paneId)
- // The grid, READ off the shell that is about to become the engine — not declared.
- //
- // That shell already carries everything the launch set, because `tmux new-session -e` put it
- // there before anything ran: it is the same environment the engine will inherit, in a process
- // that exists now. So the ordinary probe answers, and it answers truthfully.
- //
- // Skipping this was a real bug, not a purity win. An install runs for a minute, and for that
- // whole minute the app said "own login" over an agent that had already been pointed at a grid
- // — the one moment the user is watching, and the one answer they were owed.
- const placeholderGrid = placeholder
- ? await probeGridAssignment(placeholder, engine, argv.join(' '))
- : undefined
- const opened = placeholder
- ? registry.openProcessAgent({
- engine,
- runtimes: [spawned.runtime],
- cwd,
- processIdentity: placeholder,
- ...(placeholderGrid !== undefined ? { grid: placeholderGrid } : {}),
- })
- : null
- if (opened) {
- registry.setTerminalAvailable(opened.entry.agentId, true)
- void watchInstallingPane(spawned.runtime, engine, opened.entry.agentId)
- console.log(`[agent] create ${engine} · pane open, installing · agent ${opened.entry.agentId}`)
- return { ok: true, session: opened.entry }
- }
- // No placeholder identity means `ps` or tmux could not be read — not that the pane is bad. Fall
- // through to the normal path: the install still runs, and the worst case is the reply the app
- // already knows how to show while the periodic reconcile picks the agent up behind it.
- console.warn(`[agent] create ${engine} · installing, but the pane's process could not be read; falling back to discovery`)
- }
- // The launch runs the user's INTERACTIVE login shell before `exec`ing the engine, and that shell
- // is the slow half: ~0.9s on a plain zsh, before the engine has even begun. Engine startup then
- // lands past 1.3s — measured on one machine, grok at 1.38s, codex at 1.41s, claude at 1.52s. The
- // ladder here used to total 1.35s, so all three lost the race by tens of milliseconds and a
- // perfectly good agent was reported as ENGINE_DID_NOT_START, while its pane kept running and the
- // periodic reconcile registered it seconds later. Dotfile-heavy setups (nvm, oh-my-zsh, asdf)
- // are slower still. The app waits 20s for this reply, so a budget several times the measured
- // worst case is free — and a pane that DIES is detected below, not waited out.
- const DISCOVERY_BUDGET_MS = 8_000
- let paneState: TmuxPaneState | null = null
- let delayMs = 150
- while (true) {
- await new Promise((resolve) => setTimeout(resolve, delayMs))
- await agentReconciler.triggerHint(spawned.runtime, engine)
- const session = registry.byRuntimeEngine(spawned.runtime, engine)
- if (session) {
- // A real agent now: give the pane back tmux's normal disposal so it vanishes when the engine
- // exits, like every organically started one does.
- await clearPaneRemainOnExit(spawned.runtime.paneId)
- return { ok: true, session }
- }
- // Read the pane BEFORE the availability probe further below — that probe spends up to 5s in
- // the user's login shell, long enough for a dying engine's pane to change under us.
- paneState = await tmuxPaneState(spawned.runtime.paneId)
- // An engine that has already exited will never be discovered. Report it now rather than
- // holding the dialog for the rest of the budget.
- if (!paneState || paneState.dead) break
- if (Date.now() - createdAt >= DISCOVERY_BUDGET_MS) break
- // Cheap fast probes first for an engine that starts instantly, then a steady poll rather than
- // hammering `ps` for eight seconds.
- delayMs = Math.min(delayMs * 2, 750)
- }
-
- // Close the race between the last scheduled discovery snapshot and the error snapshot below.
- // Claude's native launcher can still identify as its versioned install target during the former,
- // then become a matchable `claude` process while painting its first-run trust prompt. This lookup
- // owns the exact pane just created, so adopt that verified observation directly instead of asking
- // the best-effort all-terminal inventory to see it one more time. It never sends input to the pane:
- // folder trust remains the user's choice.
- let engineProcess = paneState && !paneState.dead
- ? await resolvePaneEngineProcess(spawned.runtime.paneId, engine)
- : null
- if (engineProcess) {
- const session = await agentReconciler.adoptVerified({
- engine,
- cwd,
- processIdentity: engineProcess,
- args: command.join(' '),
- resumeSessionId: null,
- runtimes: [spawned.runtime],
- primaryRuntimeKey: terminalRouteKey(spawned.runtime),
- })
- if (session) {
- await clearPaneRemainOnExit(spawned.runtime.paneId)
- return { ok: true, session }
- }
- // Keep the diagnosis tied to the latest pane state if registration itself failed.
- paneState = await tmuxPaneState(spawned.runtime.paneId)
- if (!paneState || paneState.dead) engineProcess = null
- }
- const diagnosis = describeAgentCreateFailure({
- state: paneState,
- output: summarizePaneOutput(
- await captureTmuxPane(spawned.runtime.paneId, 40, { ansi: false }) ?? '',
- ),
- engineBin: command[0],
- // A dead or vanished pane has no tree; every live failure includes one for remote diagnosis.
- processes: paneState && !paneState.dead
- ? await tmuxPaneProcessTree(spawned.runtime.paneId)
- : [],
- engineProcessFound: !!engineProcess,
- shellName: (() => {
- const path = interactiveEngineShell()?.path
- return path ? basename(path) : null
- })(),
- elapsedMs: Date.now() - createdAt,
- })
- // A dead pane exists only because `create` asked tmux to keep it, and its output has now been
- // read. Dispose of it so a failed create leaves nothing behind, as it did before. A pane that is
- // still ALIVE is deliberately left alone: it is usually a slow engine that the periodic
- // reconcile picks up seconds later, and killing it would destroy a working agent.
- if (paneState?.dead) await tmuxBackend.kill(spawned.runtime)
- else await clearPaneRemainOnExit(spawned.runtime.paneId)
- if (engineProcess) {
- const detail = `the verified ${engine} process is running, but the local registry rejected its process-agent · ${diagnosis}`
- console.warn(`[agent] create ${engine} failed · ${detail}`)
- return { ok: false, error: 'REGISTRATION_FAILED', detail }
- }
- // A detached daemon and an already-running tmux server do not necessarily have the user's terminal
- // PATH. The launch above therefore used the interactive shell; inspect that same context before
- // claiming a binary is absent. Checking process.env here was a false "not installed" report on
- // macOS and Ubuntu whenever the CLI lived in .zshrc/.bashrc (nvm, asdf, vendor installers).
- const bin = command[0]
- // `detail` rides back to the New Agent dialog, which already renders it. That is the whole point:
- // the machine that knows why is frequently not the machine the person is sitting at, and the
- // error code alone sent them to a log file they cannot open.
- if (!await commandAvailableInInteractiveShell(bin)) {
- const shell = interactiveEngineShell()
- const detail = `"${bin}" is not on PATH in the user's ${shell?.label ?? 'daemon PATH'} · ${diagnosis}`
- console.warn(`[agent] create ${engine} failed · ${detail}`)
- return { ok: false, error: 'ENGINE_NOT_INSTALLED', detail }
- }
- const shell = interactiveEngineShell()
- const detail = `"${bin}" resolves from the user's ${shell?.label ?? 'daemon PATH'} · ${diagnosis}`
- console.warn(`[agent] create ${engine} failed · ${detail}`)
- return { ok: false, error: 'ENGINE_DID_NOT_START', detail }
+ void watchCreatedPane()
+ console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)
+ return { ok: true, session: pending }
}
/**
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index c989ebe04..66bb1b993 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -35,4 +35,13 @@ describe('agentFrame', () => {
expect(await agentFrame(session(null), { selectedModel: 'opus', terminalAvailable: false }))
.toMatchObject({ selectedModel: 'opus', terminal: { available: false, primary: 'tmux/%1' } })
})
+
+ it('reports launch state and defaults legacy agents to ready', async () => {
+ const legacy = session(null)
+ expect(await agentFrame(legacy, { selectedModel: null, terminalAvailable: true }))
+ .toMatchObject({ launch: { state: 'ready' } })
+ legacy.launch = { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal.' }
+ expect(await agentFrame(legacy, { selectedModel: null, terminalAvailable: true }))
+ .toMatchObject({ launch: { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal.' } })
+ })
})
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 060e83e01..34e75f39c 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -34,6 +34,7 @@ export type AgentFrame = {
userId: string
name: string
status: string
+ launch: NonNullable<RegisteredSession['launch']>
createdAt: string
updatedAt: string
tmuxPane: string | null
@@ -69,6 +70,7 @@ export async function agentFrame(
userId: '',
name: projectDisplayName(s),
status: s.active ? 'active' : 'offline',
+ launch: s.launch ?? { state: 'ready' },
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
tmuxPane: s.tmuxPane || null,
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 9a5e2325e..51689e5d3 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -183,16 +183,33 @@ describe('buildEngineLaunchArgv with installFirst', () => {
})
})
+describe('buildEngineLaunchArgv with installIfMissing', () => {
+ const script = (install: string): string =>
+ buildEngineLaunchArgv('opencode', { installIfMissing: install }, '/bin/zsh')[2]
+
+ it('execs an installed engine without running the installer', async () => {
+ await expect(runPaneScript(script('false'))).resolves.toMatchObject({ code: 0, ranEngine: true })
+ })
+
+ it('runs the installer inside the pane when the engine is absent', async () => {
+ const result = await runPaneScript(script('false'), 'harness-no-such-engine')
+ expect(result.ranEngine).toBe(false)
+ expect(result.code).toBe(1)
+ expect(result.stdout).toContain('engine is missing')
+ })
+})
+
/** Run one generated pane script under /bin/sh and report what it did. */
async function runPaneScript(
paneScript: string,
+ command = '/usr/bin/printf',
): Promise<{ code: number; stdout: string; ranEngine: boolean }> {
const { execFile } = await import('node:child_process')
const marker = 'HARNESS-TEST-ENGINE-RAN'
return await new Promise((resolve) => {
execFile(
'/bin/sh',
- ['-c', paneScript, 'harness-engine', 'printf', `${marker}\n`],
+ ['-c', paneScript, 'harness-engine', command, `${marker}\n`],
{ timeout: 10_000 },
(error, stdout) => {
const code = error && typeof (error as { code?: unknown }).code === 'number'
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 1c8db6c63..99c61b2e7 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -55,6 +55,8 @@ export interface LaunchCommandOptions {
* is the case above.
*/
installFirst?: string
+ /** Install only when command[0] is absent, checked inside the pane's already-started shell. */
+ installIfMissing?: string
/**
* Environment variables to clear in the pane before the engine starts — the vendor credentials a
* grid launch must not leave lying around. See `gridConflictingEnvToClear` in `gridLaunch.ts`,
@@ -182,9 +184,11 @@ export function buildEngineLaunchArgv(
// 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.
const prelude = clearEnvPrelude(opts.clearEnv)
- const body = opts.installFirst
- ? installThenExecScript(opts.installFirst)
- : 'exec "$@"'
+ const body = opts.installIfMissing
+ ? installIfMissingThenExecScript(opts.installIfMissing)
+ : opts.installFirst
+ ? installThenExecScript(opts.installFirst)
+ : 'exec "$@"'
return [interactive.path, ...interactive.args, prelude + body, 'harness-engine', ...command]
}
@@ -228,6 +232,17 @@ function installThenExecScript(install: string): string {
].join('\n')
}
+function installIfMissingThenExecScript(install: string): string {
+ return [
+ 'resolved="$(command -v "$1" 2>/dev/null)" || true',
+ 'if [ -n "$resolved" ] && [ -f "$resolved" ] && [ -x "$resolved" ]; then exec "$@"; fi',
+ `printf '%s\\n' 'harness: engine is missing — installing it in this terminal' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
+ `if eval ${JSON.stringify(install)}; then exec "$@"; 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')
+}
+
const AVAILABILITY_SCRIPT = 'resolved="$(command -v "$1" 2>/dev/null)" || exit 1\n'
+ '[ -n "$resolved" ] && [ -f "$resolved" ] && [ -x "$resolved" ]'
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index f14dc76c2..fae5361b0 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -978,6 +978,44 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(reloaded.unbound()).toHaveLength(1)
})
+ it('opens a route-only pending agent and adopts the engine process without changing agentId', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({
+ engine: 'claude',
+ runtimes: [{ backend: 'tmux', paneId: '%7' }],
+ cwd: '/tmp/demo',
+ })
+ expect(pending).toMatchObject({ sessionId: '', processIdentity: null, launch: { state: 'starting' } })
+ expect(registry.terminalAvailable(pending!.agentId)).toBe(true)
+
+ const adopted = registry.openProcessAgent({
+ engine: 'claude', tmuxPane: '%7', cwd: '/tmp/demo', processIdentity: processIdentity(707),
+ })
+ expect(adopted?.entry.agentId).toBe(pending?.agentId)
+ expect(adopted?.entry.launch).toEqual({ state: 'ready' })
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('persists a failed launch for reconnect while keeping its terminal route', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({
+ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo',
+ })!
+ registry.setLaunch(pending.agentId, {
+ state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal output.',
+ })
+
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(pending.agentId)).toMatchObject({
+ active: false,
+ launch: { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal output.' },
+ tmuxPane: '%8',
+ })
+ })
+
it('keeps a name given before the agent had a session', async () => {
// Names live under the ENGINE session id — that is what survives the launcher and comes back on a
// resume, since the agent id is minted fresh each launch. An agent renamed while still unbound has
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index ef73f4354..f35415083 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -46,6 +46,11 @@ import type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './te
export type { ProcessIdentity } from './terminalTypes.js'
+export type AgentLaunch =
+ | { state: 'starting' }
+ | { state: 'ready' }
+ | { state: 'failed'; error: string; detail?: string }
+
/** Claude Code's hooks report `model` as {id, display_name}; Codex/Cursor report a plain string. This is
* the boundary where hook JSON becomes persisted state, so anything else is dropped rather than stored —
* a non-string here reaches runtimeProfile's `.toLowerCase()` and takes the daemon down AT STARTUP, which
@@ -61,11 +66,14 @@ export interface RegisteredSession {
schemaVersion: 2
/** Whether the supported engine process is currently identified; terminal liveness is tracked separately. */
active: boolean
+ /** Harness-created panes can be rendered before their engine process exists. Absent on legacy rows. */
+ launch?: AgentLaunch
/**
* THE AGENT. Public identity: this is what web tabs, device tiles and every inbound frame address.
*
- * It is minted when a top-level engine process is first discovered. The persisted process identity lets
- * the same UUID survive daemon restarts while the engine underneath rotates sessions (`/clear`, `/new`).
+ * It is normally minted when a top-level engine process is discovered. Harness-created panes mint it
+ * immediately so clients can render the terminal while the engine starts. Persisted route/process identity
+ * keeps the UUID stable across daemon restarts and engine session rotations (`/clear`, `/new`).
*/
agentId: string
/**
@@ -338,6 +346,7 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
const normalizedPrimary = selectedRuntimeKey(runtimes, primary)
const active = row.active === true
const projectedTmuxPane = tmuxProjection(runtimes)
+ const launch = normalizedLaunch(row.launch)
if (row.schemaVersion !== 2
|| typeof row.active !== 'boolean'
|| typeof row.agentId !== 'string' || !row.agentId
@@ -358,6 +367,7 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
...row,
schemaVersion: 2,
active,
+ ...(launch ? { launch } : {}),
agentId: row.agentId,
sessionId: row.sessionId,
boundAt: typeof row.boundAt === 'number' ? row.boundAt : null,
@@ -380,6 +390,18 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
}
}
+function normalizedLaunch(value: unknown): AgentLaunch | undefined {
+ if (!value || typeof value !== 'object') return undefined
+ const launch = value as { state?: unknown; error?: unknown; detail?: unknown }
+ if (launch.state === 'starting' || launch.state === 'ready') return { state: launch.state }
+ if (launch.state !== 'failed' || typeof launch.error !== 'string' || !launch.error) return undefined
+ const error = launch.error.slice(0, 80)
+ const detail = typeof launch.detail === 'string' && launch.detail
+ ? launch.detail.slice(0, 500)
+ : undefined
+ return { state: 'failed', error, ...(detail ? { detail } : {}) }
+}
+
function validatedRows(values: readonly unknown[]): RegisteredSession[] | null {
const rows: RegisteredSession[] = []
const agents = new Set<string>()
@@ -702,9 +724,11 @@ class Registry {
if (agentId !== raw.agentId) changed = true
const now = Date.now()
const active = raw.active !== false
+ const launch = normalizedLaunch(raw.launch)
const s: RegisteredSession = {
schemaVersion: 2,
active,
+ ...(launch ? { launch } : {}),
agentId,
boundAt: bound ? (typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now)) : null,
engine,
@@ -733,6 +757,7 @@ class Registry {
raw.engine !== engine
|| raw.schemaVersion !== 2
|| typeof raw.active !== 'boolean'
+ || JSON.stringify(raw.launch) !== JSON.stringify(s.launch)
|| raw.tmuxPane !== pane
|| JSON.stringify(raw.runtimes) !== JSON.stringify(runtimes)
|| raw.primaryRuntimeKey !== s.primaryRuntimeKey
@@ -839,6 +864,7 @@ class Registry {
existing.cwd = input.cwd ?? existing.cwd
existing.processIdentity = processIdentity
existing.active = true
+ if (existing.launch) existing.launch = { state: 'ready' }
// Only a successful read speaks: an undefined probe (ps failed, /proc unreadable) keeps whatever
// the last good one said rather than silently downgrading a gateway agent to a vendor one.
if (input.gateway !== undefined) existing.gateway = input.gateway
@@ -903,6 +929,52 @@ class Registry {
return { entry, isNew: true, evicted }
}
+ /** Register a terminal route before its engine process exists. */
+ openPendingAgent(input: {
+ engine: AgentEngine
+ runtimes: TerminalRuntimeRef[]
+ primaryRuntimeKey?: string
+ cwd?: string | null
+ grid?: GridAssignment | null
+ }): RegisteredSession | null {
+ if (this.writeBlocked) return null
+ const runtimes = normalizedRuntimes(input.runtimes)
+ if (!runtimes.length) return null
+ if (runtimes.some((runtime) => this.runtimeIndex.has(terminalRouteKey(runtime)))) return null
+ const now = Date.now()
+ const agentId = randomUUID()
+ const entry: RegisteredSession = {
+ schemaVersion: 2,
+ active: true,
+ launch: { state: 'starting' },
+ agentId,
+ sessionId: '',
+ boundAt: null,
+ engine: input.engine,
+ gateway: null,
+ grid: input.grid ?? null,
+ transcriptPath: null,
+ projectDir: basename(input.cwd ?? '') || agentId,
+ cwd: input.cwd ?? null,
+ runtimes,
+ primaryRuntimeKey: selectedRuntimeKey(runtimes, input.primaryRuntimeKey),
+ tmuxPane: tmuxProjection(runtimes),
+ source: null,
+ title: null,
+ model: null,
+ cliVersion: null,
+ processIdentity: null,
+ registeredAt: now,
+ updatedAt: now,
+ lastHookAt: now,
+ lastTranscriptAt: now,
+ }
+ this.index(entry)
+ this.terminalAvailableAgents.add(entry.agentId)
+ this.save()
+ return entry
+ }
+
/** Discovered process agents that have no engine session bound yet. */
unbound(): RegisteredSession[] {
return this.list().filter((s) => !s.sessionId)
@@ -1125,6 +1197,16 @@ class Registry {
return true
}
+ setLaunch(agentId: string, launch: AgentLaunch): RegisteredSession | null {
+ const entry = this.agents.get(agentId)
+ if (!entry) return null
+ entry.launch = normalizedLaunch(launch)
+ entry.active = launch.state !== 'failed'
+ entry.updatedAt = Date.now()
+ this.save()
+ return entry
+ }
+
/** Mark whether at least one backend placement was verified by this daemon process. */
setTerminalAvailable(agentId: string, available: boolean): boolean {
if (!this.agents.has(agentId)) return false