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.

Recover newly installed tmux and name launch failure reasons (#1514)

tony496s87330029dfa8
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index d169dd5e9..c1a18b945 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -109,6 +109,28 @@ it('stores launch codes as day totals like any other counter', async () => {
.toEqual(Object.entries(counters).map(([metric, value]) => [metric, { $inc: { value } }]))
})
+it('accepts the Windows and Git helper refusals that older launch reports called unlisted', async () => {
+ const codes = ['engine_launch_refused', 'pty_host_unavailable', 'git_project_unavailable', 'branch_exists',
+ 'invalid_branch', 'branch_switch_failed', 'branch_in_use', 'worktree_failed']
+ const counters = Object.fromEntries(codes.map(code => [`launch_failed_code_${code}`, 1]))
+ expect(await ingestProductUsage('private-account', { ...report, counters }, now)).toEqual({ accepted: true })
+ expect(db.$runCommandRaw.mock.calls[0][0].updates.map((u: { q: { metric: string } }) => u.q.metric))
+ .toEqual(Object.keys(counters))
+})
+
+it('stores setup reasons in separate families without reinterpreting the other-failure totals', async () => {
+ const counters = {
+ launch_failed_setup: 2, launch_failed_setup_code_tmux_unavailable: 1, launch_failed_setup_code_native_launch_held: 1,
+ create_error_setup: 2, create_error_setup_code_tmux_unavailable: 1, create_error_setup_code_pty_host_unavailable: 1,
+ request_phone_create_error_setup: 1, phone_create_error_setup_code_tmux_unavailable: 1,
+ launch_failed_other: 1, launch_failed_code_worktree_failed: 1,
+ }
+ expect(await ingestProductUsage('private-account', { ...report, counters }, now)).toEqual({ accepted: true })
+ const stored = db.$runCommandRaw.mock.calls[0][0].updates.map((u: { q: { metric: string }; u: unknown }) => [u.q.metric, u.u])
+ expect(stored).toEqual(Object.entries(counters).map(([metric, value]) => [metric, { $inc: { value } }]))
+ expect(JSON.stringify(stored)).not.toContain('private-account')
+})
+
describe('preference', () => {
it('defaults on but preserves a prior off choice', async () => {
expect(await productUsageChoice('private-account')).toEqual({ enabled: true, revision: 0 })
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index 02867c28c..ef2a91380 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -128,9 +128,11 @@ export const LAUNCH_ERROR_CODES = [
'invalid_launch_model', 'launch_model_unsupported',
// A new project's folder (lib/projectFolder.ts) and the launch's durable receipt (lib/agentCreationReceipt.ts).
'project_exists', 'invalid_repository', 'clone_failed', 'clone_timeout', 'git_unavailable', 'project_preparation_failed',
+ 'git_project_unavailable', 'branch_exists', 'invalid_branch', 'branch_switch_failed', 'branch_in_use', 'worktree_failed',
'creation_conflict', 'creation_storage_failed', 'launch_authority_changed', 'internal',
// The engine itself: preparing it (engines/nativeLaunch.ts) and its start (core/agents/newPane.ts).
'engine_cannot_run', 'engine_install_failed', 'engine_did_not_start', 'engine_not_installed', 'start_timeout',
+ 'engine_launch_refused',
// A Store harness (core/agents/dshThrough.ts, services/storeLaunch.ts).
'dsh_not_installed', 'dsh_unavailable', 'dsh_runtime_failed',
// A conversation Harness did not start, opened in it (core/agents/adopt.ts, externalResume.ts, lib/registry.ts).
@@ -152,7 +154,7 @@ export const LAUNCH_ERROR_CODES = [
'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',
'guest_helper_not_authorized', 'guest_helper_failed',
// The `setup` kind's own codes, named for a delete or restart refusal (cli/src/lib/productUsageSignals.ts).
- 'tmux_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',
+ 'tmux_unavailable', 'pty_host_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',
'dsh_materialize_failed', 'spawn_failed', 'registration_failed', 'grid_config_failed',
'unlisted', 'none',
] as const
@@ -160,9 +162,11 @@ export type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]
/** The families counted by code: a launch's failure, its start failing after it was created, the create
* and resume requests' `other` refusals, and every delete and restart refusal — from any client, and again,
* apart, those the phone asked for (`phone_`), which a daemon's report otherwise carries mixed with the
- * Desktop's, the TUI's and tools'. */
+ * Desktop's, the TUI's and tools'. Setup reasons have their own families, adding up to `launch_failed_setup`,
+ * `create_error_setup` and `request_phone_create_error_setup`; existing `other` families keep their meaning. */
export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code',
- 'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code'] as const
+ 'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code',
+ 'launch_failed_setup_code', 'create_error_setup_code', 'phone_create_error_setup_code'] as const
/** The engine an installation's first launch asked for; any other engine is `other`. */
export const PRODUCT_USAGE_LAUNCH_ENGINES = ['opencode', 'claude', 'codex', 'other'] as const
export type ProductUsageLaunchEngine = typeof PRODUCT_USAGE_LAUNCH_ENGINES[number]
diff --git a/cli/e2e/creationPaths.e2e.ts b/cli/e2e/creationPaths.e2e.ts
new file mode 100644
index 000000000..30ecb3a88
--- /dev/null
+++ b/cli/e2e/creationPaths.e2e.ts
@@ -0,0 +1,107 @@
+/**
+ * New Harness's two project paths, investigated after the 2026-10-21 launch failure spike:
+ * the phone asks the computer to make a project; Desktop on that computer makes the folder first.
+ * Use the real daemon and private tmux server, with fake engines and homes owned by this test.
+ */
+import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+import { resolveBinaryOnPath } from '../src/lib/binaryOnPath.js'
+
+let daemon: IsolatedDaemon | undefined
+afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+for (const surface of ['phone', 'Desktop'] as const) {
+ it.each(['claude', 'codex'] as const)(`${surface}: a new %s harness starts in its project and takes its first message`, async engine => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(d.log().split('\n').slice(-150).join('\n')) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ try {
+ const folder = join(d.env.HOME!, 'harnesses', `${surface.toLowerCase()}-${engine}`)
+ if (surface === 'Desktop') mkdirSync(folder, { recursive: true })
+ const creationId = `creation-${surface}-${engine}-0001`
+ const payload = {
+ engine, creationId, bypassPermission: true,
+ ...(surface === 'phone'
+ ? { projectSource: 'new', projectName: `phone-${engine}`, usageSurface: 'phone' }
+ : { cwd: folder }),
+ }
+ // Loopback carries the phone's request shape here; relay/auth are covered by relay.e2e.ts.
+ let created = await client.request('agent_create', payload, 90_000)
+ if (created.state === 'pending') created = await until('the saved creation to finish', async () => {
+ const status = await client.request('agent_create_status', { creationId }, 30_000)
+ return status.state !== 'pending' ? status : null
+ }, 60_000, 250)
+ expect(created, JSON.stringify(created)).toMatchObject({ state: 'created', agent: { engine } })
+ const id = created.agent.id
+ const agent = await until('the new harness to bind its conversation', async () => {
+ const listed = await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)
+ return listed.agents.find(row => row.id === id && row.sessionId && row.status === 'active') ?? null
+ }, 60_000, 250)
+ expect(agent.project?.cwd ?? agent.cwd).toBe(folder)
+ const ended = client.next(frame => frame.type === 'turn_ended' && frame.agentId === id, 45_000, 'the first message to finish')
+ client.send('message', { agentId: id, content: 'Reply with pong' })
+ await ended
+ expect(d.coresStarted()).toBe(1)
+ } finally { client.close() }
+ })
+}
+
+it('starts phone and Desktop harnesses when managed tmux arrives after daemon startup, without a restart', async () => {
+ const tmux = resolveBinaryOnPath('tmux')!
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(d.log().split('\n').slice(-150).join('\n')) })
+ // Neither the daemon, its shell nor its known install locations can find the host's tmux.
+ // Linux installs tmux in /usr/bin, so even the system PATH must be a private tools directory.
+ const tools = join(d.root, 'tools-without-tmux')
+ mkdirSync(tools)
+ for (const name of ['ps', 'lsof', 'sleep', 'stty', 'clear', 'rm', 'mkdir', 'mv', 'chmod', 'cat', 'dirname', 'basename',
+ 'wc', 'dd', 'grep', 'stat', 'date', 'sort', 'head', 'tail', 'awk', 'sed', 'touch', 'uname', 'env', 'find', 'readlink', 'xargs', 'tty', 'id']) {
+ const binary = resolveBinaryOnPath(name)
+ if (binary) symlinkSync(binary, join(tools, name))
+ }
+ symlinkSync(process.execPath, join(tools, 'node'))
+ d.env.PATH = `${join(d.root, 'bin')}:${tools}`
+ d.env.SHELL = '/bin/zsh'
+ d.env.HARNESS_HOMEBREW_PREFIXES = join(d.root, 'no-homebrew')
+ writeFileSync(join(d.env.HOME!, '.zshrc'), `export PATH=${JSON.stringify(d.env.PATH)}\n`)
+ await d.start()
+ const client = await LocalClient.connect(d)
+ try {
+ const absent = await client.request('agent_create', { engine: 'claude', creationId: 'absent-tmux-00000001', cwd: d.projectsDir }, 90_000)
+ expect(absent).toMatchObject({ state: 'failed', failure: { code: 'TMUX_UNAVAILABLE' } })
+ // The installer's pointer, published only after an executable has been put in the managed runtime.
+ const bin = join(d.env.ADAPTER_RUNTIME_DIR!, 'tmux-fixture', 'bin')
+ mkdirSync(bin, { recursive: true })
+ symlinkSync(tmux, join(bin, 'tmux'))
+ writeFileSync(join(d.env.ADAPTER_RUNTIME_DIR!, 'current-tmux'), join(bin, 'tmux'))
+ for (const surface of ['phone', 'Desktop']) for (const engine of ['claude', 'codex']) {
+ const folder = join(d.env.HOME!, 'harnesses', `recovered-${surface}-${engine}`)
+ if (surface === 'Desktop') mkdirSync(folder, { recursive: true })
+ const creationId = `recovered-${surface}-${engine}-0001`
+ let created = await client.request('agent_create', { engine, creationId, bypassPermission: true,
+ ...(surface === 'phone' ? { projectSource: 'new', projectName: `recovered-${surface}-${engine}`, usageSurface: 'phone' } : { cwd: folder }),
+ }, 90_000)
+ if (created.state === 'pending') created = await until('the recovered creation to finish', async () => {
+ const status = await client.request('agent_create_status', { creationId }, 30_000)
+ return status.state === 'pending' ? null : status
+ }, 60_000, 250)
+ expect(created, JSON.stringify(created)).toMatchObject({ state: 'created', agent: { engine } })
+ const id = created.agent.id
+ await until('the recovered harness to bind', async () => {
+ const listed = await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)
+ return listed.agents.find(row => row.id === id && row.sessionId && row.status === 'active') ?? null
+ }, 60_000, 250)
+ const ended = client.next(frame => frame.type === 'turn_ended' && frame.agentId === id, 45_000, 'the recovered harness to answer')
+ client.send('message', { agentId: id, content: 'Reply with pong' })
+ await ended
+ }
+ expect(d.coresStarted()).toBe(1)
+ expect(d.log()).toContain('[terminal] tmux recovered')
+ } finally { client.close() }
+})
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index f55061aed..33386e4cd 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -3880,6 +3880,43 @@ describe('agent_recent replies', () => {
})
describe('request sources', () => {
+ it.each(['phone', 'Desktop'] as const)('%s: names a project preparation refusal for a Claude or Codex creation', async surface => {
+ const socket = relaySocket('token')
+ bindLaunchRequests(socket)
+ socket.connect()
+ const ws = wsMock.instances.at(-1)!
+ ws.open()
+ const counters: string[] = [], signals: unknown[] = []
+ vi.spyOn(gatewayOf(socket), 'usageCounter').mockImplementation(metric => { counters.push(metric) })
+ vi.spyOn(gatewayOf(socket), 'usageLaunch').mockImplementation(signal => { signals.push(signal) })
+ // The real creation handler translates this imported helper's refusal into a durable receipt.
+ vi.spyOn(projectFolder, 'prepareProjectFolder').mockRejectedValue(new projectFolder.ProjectFolderError('WORKTREE_FAILED', 'PRIVATE_CANARY'))
+ socket.onCreateAgent = vi.fn()
+ socket.registerLocalClient('local:creation-report', { sendFrame: () => true, sendBinary: () => true })
+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)
+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')
+ try {
+ for (const engine of ['claude', 'codex']) {
+ const creationId = randomUUID()
+ const frame = { type: 'agent_create', payload: { creationId, requestId: creationId, engine,
+ projectSource: 'worktree', gitSource: '/PRIVATE_FOLDER', ...(surface === 'phone' ? { usageSurface: 'phone' } : {}) } }
+ if (surface === 'phone') {
+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(frame)
+ ws.message({ t: 'down', connId: 'phone-creation-report', frame: { type: 'agent_create', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })
+ } else socket.handleLocalFrame('local:creation-report', frame)
+ await vi.waitFor(() => expect(signals).toContainEqual({ id: creationId, phase: 'failed', failure: 'other', code: 'worktree_failed' }))
+ }
+ expect(counters.filter(name => name === 'create_error_code_worktree_failed')).toHaveLength(2)
+ expect(counters.filter(name => name === `request_${surface === 'phone' ? 'phone' : 'app'}_create_failed`)).toHaveLength(2)
+ expect(socket.onCreateAgent).not.toHaveBeenCalled()
+ expect(JSON.stringify([counters, signals])).not.toContain('PRIVATE')
+ } finally {
+ await socket.unregisterLocalClient('local:creation-report')
+ await socket.stop()
+ vi.restoreAllMocks()
+ }
+ })
+
// The counter a request starts with, for a remote `web` client: the phone only by its own word.
async function startedFor(payload: Record<string, unknown>) {
const socket = relaySocket('token')
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index a419770ce..460a259e3 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -374,6 +374,27 @@ describe('creating an agent', () => {
})
describe('refusals before any pane opens', () => {
+ it('recovers a backend missing at boot, and rechecks launch authority after recovery', async () => {
+ const ready = setup().deps.createBackend!
+ const recoverBackend = vi.fn().mockResolvedValueOnce(null).mockResolvedValue(ready)
+ const run = setup({ createBackend: null, recoverBackend })
+ expect(await run.create(request())).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })
+ expect(await run.create(request())).toEqual({ ok: true, session: pending })
+ expect(createAndRegisterPane).toHaveBeenCalledWith(expect.objectContaining({ tmuxBackend: ready }))
+ vi.mocked(createAndRegisterPane).mockClear()
+ let current = true
+ const stale = setup({ createBackend: null, recoverBackend: async () => { current = false; return ready } })
+ expect(await stale.create.prepare(request(), { id: 'recovery', label: 'recovery', current: () => current, hold: () => {} }))
+ .toMatchObject({ ok: false, error: 'LAUNCH_AUTHORITY_CHANGED' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
+ it('does not ask for backend recovery on a healthy launch', async () => {
+ const recoverBackend = vi.fn()
+ expect(await setup({ recoverBackend }).create(request())).toEqual({ ok: true, session: pending })
+ expect(recoverBackend).not.toHaveBeenCalled()
+ })
+
it('a batch-file engine on Windows whose first message cmd.exe would read, by name; other errors are not refusals', async () => {
vi.mocked(buildEngineLaunchArgv).mockImplementationOnce(() => { throw new WindowsBatchLaunchRefused('claude', 'C:\\tools\\claude.cmd') })
expect(await setup().create(request({ prompt: 'fix&calc' }))).toEqual({
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index e18bf03ab..4f365f31e 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -63,6 +63,8 @@ export interface CreateAgentDeps {
native?: (engine: AgentEngine, source: NativeLaunchSource, authority: LaunchAuthority) => Promise<NativeLaunchResult>
/** The backend new panes are made on; null where none is configured or could be readied. */
createBackend: TerminalBackend | null
+ /** Recheck a backend missing at boot after its runtime has been installed. Healthy launches never call it. */
+ recoverBackend?: () => Promise<TerminalBackend | null>
/** What a launch answers when [createBackend] is null: the configured backend's own code (terminalBackend.ts
* `noBackendCode`); `TMUX_UNAVAILABLE`, as before, by default. */
noBackendCode?: string
@@ -95,7 +97,7 @@ export interface CreateAgentDeps {
}
export function createAgentCreator({
- native: inspectNative, publishConfig, createBackend, noBackendCode = 'TMUX_UNAVAILABLE', registry, externalResume, watchNewPane, announceSession, attachDsh,
+ native: inspectNative, publishConfig, createBackend: initialBackend, recoverBackend, noBackendCode = 'TMUX_UNAVAILABLE', registry, externalResume, watchNewPane, announceSession, attachDsh,
prepareApiTools, hookPort, hooksDisabled, installOpencodePlugin, gridLaunchMachine, buildGridLaunch, terminalHintMachineName, blocksFolder,
gridSetup, privateGridName, dshLaunch,
}: CreateAgentDeps) {
@@ -104,6 +106,11 @@ export function createAgentCreator({
const stale = () => ({ ok: false as const, error: 'LAUNCH_AUTHORITY_CHANGED', unavailable: 'launch', detail: 'Waiting for the original launch request’s authority.' })
if (!authority.current()) return stale()
let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId, launchModel } = input
+ let createBackend = initialBackend
+ if (!createBackend && recoverBackend) {
+ createBackend = await recoverBackend()
+ if (!authority.current()) return stale()
+ }
if (!createBackend) return { ok: false, error: noBackendCode }
if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }
const workspaceIdentity = () => { const info = statSync(cwd); return `${info.dev}:${info.ino}:${realpathSync(cwd)}` }
diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.ts
index bc96f238f..f78aba93c 100644
--- a/cli/src/core/engines/hooks.spec.ts
+++ b/cli/src/core/engines/hooks.spec.ts
@@ -92,6 +92,15 @@ describe('which agent a hook belongs to', () => {
expect(deps.registry.byRuntimeEngine).toHaveBeenCalledWith(pty, 'claude')
})
+ it('accepts tmux hints after the missing backend recovers in this daemon', async () => {
+ const a1 = agent('a1', 100)
+ const { deps, hooks } = setup({ '%1': a1 }, { tmuxBackend: null })
+ deps.tmuxBackend = {}
+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 200], [200, 100], [100, 1]) as never)
+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toEqual(a1)
+ expect(deps.agentReconciler.triggerHint).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' }, 'claude')
+ })
+
it.each([
['no pty host backend', {}, { instance: 'p1', paneId: '%1' }],
['an instance that is not one', { ptyHostBackend: {} }, { instance: 'p1\u0000x', paneId: '%1' }],
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index 81286eb44..ef3f504ce 100644
--- a/cli/src/core/engines/hooks.ts
+++ b/cli/src/core/engines/hooks.ts
@@ -53,7 +53,8 @@ type HookQuery = Parameters<ResolveHookAgent>[0]
const recordKey = (session: RegisteredSession | undefined): string =>
session ? `${session.agentId}\u0000${session.processIdentity?.pid ?? ''}\u0000${session.processIdentity?.startMarker ?? ''}` : ''
-export function createEngineHooks({ tmuxBackend, ptyHostBackend, agentReconciler, registry, panePending, syncSession }: EngineHookDeps) {
+export function createEngineHooks(deps: EngineHookDeps) {
+ const { ptyHostBackend, agentReconciler, registry, panePending, syncSession } = deps
/**
* The agents on the hinted panes: those whose recorded process the caller descends from, the rest,
* and of the rest those with no live process recorded at all (none yet, or one that has exited).
@@ -125,7 +126,7 @@ export function createEngineHooks({ tmuxBackend, ptyHostBackend, agentReconciler
const arrival = processRows().then(rows => rows?.map(row => ({ ...row })) ?? null)
const resolved: TerminalRuntimeRef[] = []
for (const hint of runtimeHints ?? []) {
- if (hint.backend === 'tmux') { if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId }) }
+ if (hint.backend === 'tmux') { if (deps.tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId }) }
else {
// Held to the registry's own rule for a ptyhost runtime (`p<n>` instance, `%<n>` pane): a hint that is
// not one is ignored, as a hint for a backend that is not configured is.
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 3aae46cec..9f763dd55 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -73,6 +73,8 @@ import { findLiveSession, findResumedTranscript } from '../lib/sessionRepair.js'
import { processSessionOf } from '../engines/sessionStores.js'
import { createHandoffDependencies } from './handoffDependencies.js'
import { TmuxBackend } from '../lib/tmuxBackend.js'
+import { tmuxAvailableNow } from '../lib/tmuxOnPath.js'
+import { createTerminalBackendRecovery } from '../lib/terminalBackendRecovery.js'
import { isDrainBackend, ptyHostBackends, PtyHostDrain, rowsOnInstance } from '../lib/ptyHost/drain.js'
import { removeUnusedPtyVersions } from '../lib/ptyHost/launch.js'
import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from '../lib/hostTheme.js'
@@ -570,7 +572,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// STATE the daemon runs on without, never a reason to refuse to start: it still serves its status, the
// local socket and the backend link, leaves for an update, and says what is missing.
const candidates: TerminalBackend[] = []
- if (terminalConfig.backends.includes('tmux')) candidates.push(new TmuxBackend(() => hostTheme))
+ const configuredTmux = terminalConfig.backends.includes('tmux') ? new TmuxBackend(() => hostTheme) : null
+ if (configuredTmux) candidates.push(configuredTmux)
// The Harness PTY host (pty/): reached, or started detached so its panes outlive this daemon. A host of the
// protocol before, still running from before an update, is a drain backend beside it (lib/ptyHost/drain.ts).
const ptyHosts = terminalConfig.backends.includes('ptyhost')
@@ -589,21 +592,33 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const prepared = await preparing
const terminalBackends = prepared.filter((p) => p.result.state === 'ready').map((p) => p.backend)
// The first backend that could not be readied, and why, for the status's `discoveryError`.
- const terminalUnavailable = prepared.flatMap(({ backend, result }) => result.state === 'unavailable'
+ let terminalUnavailable: { backend: TerminalBackend['name']; reason: string; code: string } | null = prepared.flatMap(({ backend, result }) => result.state === 'unavailable'
? [{ backend: backend.name, reason: result.reason, code: result.code }] : [])[0] ?? null
// The backend new panes are made on. Every other pane operation reaches the pane's own backend
// through the coordinator (`terminals.backendFor`).
- const createBackend: TerminalBackend | null = terminalBackends.find((backend) => !isDrainBackend(backend)) ?? null
+ let createBackend: TerminalBackend | null = terminalBackends.find((backend) => !isDrainBackend(backend)) ?? null
// What a create, fork or resume answers while there is none: the configured backend's code, not always tmux's.
const createUnavailable = noBackendCode(terminalConfig.backends)
// A hook's tmux runtime hint is taken only while tmux is the backend new panes are made on
// (core/engines/hooks.ts). Restart, retarget, restore and adoption reach each pane's own backend
// through the coordinator, gated on what it can do (`canRestart`, `isHeld`, `killHeld`).
- const tmuxBackend = createBackend instanceof TmuxBackend ? createBackend : null
+ let tmuxBackend = createBackend instanceof TmuxBackend ? createBackend : null
const terminals = new TerminalBackendCoordinator(
terminalBackends,
terminalConfig.backends,
)
+ const recoverBackend = createTerminalBackendRecovery({
+ backend: configuredTmux,
+ available: tmuxAvailableNow,
+ ownedPanes: () => ownedPanesOf(registry.list(), 'tmux'),
+ recovered: (backend) => {
+ terminalBackends.push(backend)
+ terminals.replaceBackends(terminalBackends)
+ createBackend = tmuxBackend = backend
+ if (terminalUnavailable?.backend === 'tmux') terminalUnavailable = null
+ console.log('[terminal] tmux recovered')
+ },
+ })
// Shut down a drained host once it has no pane, and take its backend out of `terminalBackends` (stepped after
// each reconcile pass, below).
const ptyDrain = ptyHosts?.drain.length
@@ -1949,7 +1964,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
dataDir: env.ADAPTER_DATA_DIR,
})
// Which agent a hook belongs to, and what a SessionEnd means (core/engines/hooks.ts).
- const engineHooks = createEngineHooks({ tmuxBackend, ptyHostBackend, agentReconciler, registry, panePending: restorePanes.pending, syncSession })
+ const engineHooks = createEngineHooks({ get tmuxBackend() { return tmuxBackend }, ptyHostBackend, agentReconciler, registry, panePending: restorePanes.pending, syncSession })
// What agents may do: the account's experiments, kept in this daemon's data folder for its launches
// (lib/agentSettings.ts, core/experiments.ts). Started once bound, below.
const agentSettings = createAgentSettingsSync({ dataDir: env.ADAPTER_DATA_DIR, backend: proxyBackend, session: readAuthSession,
@@ -2562,6 +2577,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
native: prepareNativeLaunch,
dshLaunch,
createBackend,
+ recoverBackend,
noBackendCode: createUnavailable,
registry,
externalResume: externalResumes.create,
diff --git a/cli/src/gateway/productUsage.spec.ts b/cli/src/gateway/productUsage.spec.ts
index d95754ea6..0fa72490b 100644
--- a/cli/src/gateway/productUsage.spec.ts
+++ b/cli/src/gateway/productUsage.spec.ts
@@ -342,7 +342,7 @@ it('tracks a durable launch through polls without persisting its receipt or coun
now += 65_000
usage.launch({ id, phase: 'failed', failure: 'setup' }); usage.launch({ id, phase: 'failed', failure: 'setup' })
await usage.sync()
- expect(totals()).toEqual({ measurement_v2_installation_days: 1, first_launch_installations: 1, first_launch_engine_other: 1, launch_started: 1, launch_wait_install: 1, launch_failed: 1, launch_failed_setup: 1, launch_1m_to_5m: 1 })
+ expect(totals()).toEqual({ measurement_v2_installation_days: 1, first_launch_installations: 1, first_launch_engine_other: 1, launch_started: 1, launch_wait_install: 1, launch_failed: 1, launch_failed_setup: 1, launch_failed_setup_code_unlisted: 1, launch_1m_to_5m: 1 })
expect(JSON.stringify(sent) + readFileSync(file, 'utf8')).not.toContain(id)
})
@@ -462,6 +462,22 @@ it('names the code of an `other` launch failure, so the codes add up to launch_f
expect(JSON.stringify(sent)).not.toContain('PRIVATE_CANARY')
})
+it('counts a setup launch reason once across polls, separately from other failures and without retaining identifiers', async () => {
+ await usage.sync()
+ for (const [index, code] of ['tmux_unavailable', 'native_launch_held', 'PRIVATE_CANARY' as never].entries()) {
+ const id = `PRIVATE_CREATION_${index}`
+ usage.launch({ id, phase: 'start' })
+ for (let poll = 0; poll < 2; poll++) usage.launch({ id, phase: 'failed', failure: 'setup', code: code as never })
+ }
+ await flush()
+ const t = totals()
+ expect(t).toMatchObject({ launch_started: 3, launch_failed: 3, launch_failed_setup: 3,
+ launch_failed_setup_code_tmux_unavailable: 1, launch_failed_setup_code_native_launch_held: 1, launch_failed_setup_code_unlisted: 1 })
+ expect(Object.entries(t).filter(([name]) => name.startsWith('launch_failed_setup_code_')).reduce((sum, [, count]) => sum + count, 0)).toBe(t.launch_failed_setup)
+ expect(Object.keys(t).some(name => name.startsWith('launch_failed_code_'))).toBe(false)
+ expect(JSON.stringify(sent) + readFileSync(file, 'utf8')).not.toContain('PRIVATE_')
+})
+
it('counts a created launch whose engine then did not start as a late failure, once, by its code', async () => {
await usage.sync()
usage.launch({ id: ID, phase: 'start' })
diff --git a/cli/src/gateway/productUsage.ts b/cli/src/gateway/productUsage.ts
index 26fd12f9c..b5245538c 100644
--- a/cli/src/gateway/productUsage.ts
+++ b/cli/src/gateway/productUsage.ts
@@ -457,6 +457,9 @@ export function createProductUsage(deps: ProductUsageDeps) {
add(`launch_failed_${kind}` as ProductUsageMetric)
// 23 of 25 launch failures were `other` on 2026-10-16 (production counters): the code says which.
if (kind === 'other') add(`launch_failed_code_${listed(signal.code)}`)
+ // Setup's 10 failures on 2026-10-21 could not say which prerequisite failed. A separate family
+ // keeps the existing `other` code totals comparable; the launch map still counts polls only once.
+ if (kind === 'setup') add(`launch_failed_setup_code_${listed(signal.code)}`)
}
if (signal.phase === 'created') {
// Its start had already failed by the reply that said created (a status poll), or it is still starting:
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index 02867c28c..ef2a91380 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -128,9 +128,11 @@ export const LAUNCH_ERROR_CODES = [
'invalid_launch_model', 'launch_model_unsupported',
// A new project's folder (lib/projectFolder.ts) and the launch's durable receipt (lib/agentCreationReceipt.ts).
'project_exists', 'invalid_repository', 'clone_failed', 'clone_timeout', 'git_unavailable', 'project_preparation_failed',
+ 'git_project_unavailable', 'branch_exists', 'invalid_branch', 'branch_switch_failed', 'branch_in_use', 'worktree_failed',
'creation_conflict', 'creation_storage_failed', 'launch_authority_changed', 'internal',
// The engine itself: preparing it (engines/nativeLaunch.ts) and its start (core/agents/newPane.ts).
'engine_cannot_run', 'engine_install_failed', 'engine_did_not_start', 'engine_not_installed', 'start_timeout',
+ 'engine_launch_refused',
// A Store harness (core/agents/dshThrough.ts, services/storeLaunch.ts).
'dsh_not_installed', 'dsh_unavailable', 'dsh_runtime_failed',
// A conversation Harness did not start, opened in it (core/agents/adopt.ts, externalResume.ts, lib/registry.ts).
@@ -152,7 +154,7 @@ export const LAUNCH_ERROR_CODES = [
'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',
'guest_helper_not_authorized', 'guest_helper_failed',
// The `setup` kind's own codes, named for a delete or restart refusal (cli/src/lib/productUsageSignals.ts).
- 'tmux_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',
+ 'tmux_unavailable', 'pty_host_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',
'dsh_materialize_failed', 'spawn_failed', 'registration_failed', 'grid_config_failed',
'unlisted', 'none',
] as const
@@ -160,9 +162,11 @@ export type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]
/** The families counted by code: a launch's failure, its start failing after it was created, the create
* and resume requests' `other` refusals, and every delete and restart refusal — from any client, and again,
* apart, those the phone asked for (`phone_`), which a daemon's report otherwise carries mixed with the
- * Desktop's, the TUI's and tools'. */
+ * Desktop's, the TUI's and tools'. Setup reasons have their own families, adding up to `launch_failed_setup`,
+ * `create_error_setup` and `request_phone_create_error_setup`; existing `other` families keep their meaning. */
export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code',
- 'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code'] as const
+ 'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code',
+ 'launch_failed_setup_code', 'create_error_setup_code', 'phone_create_error_setup_code'] as const
/** The engine an installation's first launch asked for; any other engine is `other`. */
export const PRODUCT_USAGE_LAUNCH_ENGINES = ['opencode', 'claude', 'codex', 'other'] as const
export type ProductUsageLaunchEngine = typeof PRODUCT_USAGE_LAUNCH_ENGINES[number]
diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.ts
index 60bbe9a7a..d34f8efef 100644
--- a/cli/src/lib/productUsageSignals.spec.ts
+++ b/cli/src/lib/productUsageSignals.spec.ts
@@ -101,10 +101,50 @@ it.each([
expect(emit).toHaveBeenCalledWith({ id: 'fixture-creation-one', phase: 'failed', failure: 'other', code })
expect(LAUNCH_ERROR_CODES).toContain(code)
})
-it('names no code for a failure of a fixed kind, which its kind already says', () => {
+it.each(['ENGINE_LAUNCH_REFUSED', 'PTY_HOST_UNAVAILABLE', 'GIT_PROJECT_UNAVAILABLE', 'BRANCH_EXISTS',
+ 'INVALID_BRANCH', 'BRANCH_SWITCH_FAILED', 'BRANCH_IN_USE', 'WORKTREE_FAILED'])('names the launch helper refusal %s', code => {
+ expect(launchErrorCode(code)).toBe(code.toLowerCase())
+})
+it('keeps a setup refusal\'s fixed code for the separate setup diagnostic, leaving other kinds alone', () => {
const emit = vi.fn()
productUsageLaunch('agent_create_status', 'fixture-creation-one', emit)('TMUX_UNAVAILABLE', 'failed', false, undefined)
- expect(emit).toHaveBeenCalledWith({ id: 'fixture-creation-one', phase: 'failed', failure: 'setup' })
+ expect(emit).toHaveBeenLastCalledWith({ id: 'fixture-creation-one', phase: 'failed', failure: 'setup', code: 'tmux_unavailable' })
+ for (const [error, failure] of [['AUTH_REQUIRED', 'auth'], ['TIMEOUT', 'unavailable'], ['INVALID_CWD', 'invalid']]) {
+ productUsageLaunch('agent_create_status', 'fixture-creation-one', emit)(error, 'failed', false, undefined)
+ expect(emit).toHaveBeenLastCalledWith({ id: 'fixture-creation-one', phase: 'failed', failure })
+ }
+})
+
+it('counts setup reasons once per create request, apart for the phone, without changing other-by-code totals', () => {
+ const emit = vi.fn()
+ const phone = productUsageRequest('agent_create', emit, () => 0, 'phone')
+ phone('TMUX_UNAVAILABLE', 'failed', false); phone('SPAWN_FAILED', 'failed', false)
+ productUsageRequest('agent_create', emit, () => 0, 'app')('NATIVE_LAUNCH_HELD', 'failed', false)
+ productUsageRequest('agent_create', emit, () => 0, 'tool')('PTY_HOST_UNAVAILABLE', 'failed', false)
+ productUsageRequest('agent_create', emit, () => 0, 'phone')('PRIVATE_CANARY', 'failed', false)
+ productUsageRequest('agent_create', emit, () => 0, 'phone')(undefined, 'pending', false)
+ productUsageRequest('agent_create_status', emit, () => 0, 'phone')('SPAWN_FAILED', 'failed', false)
+ const names: string[] = emit.mock.calls.flat()
+ expect(names.filter(name => name.startsWith('create_error_setup_code_')).sort()).toEqual([
+ 'create_error_setup_code_native_launch_held', 'create_error_setup_code_pty_host_unavailable', 'create_error_setup_code_tmux_unavailable',
+ ])
+ expect(names.filter(name => name.startsWith('phone_create_error_setup_code_'))).toEqual(['phone_create_error_setup_code_tmux_unavailable'])
+ expect(names.filter(name => name === 'create_error_setup')).toHaveLength(3)
+ expect(names.filter(name => name === 'request_phone_create_error_setup')).toHaveLength(1)
+ expect(names.filter(name => name.startsWith('create_error_code_'))).toEqual(['create_error_code_unlisted'])
+ for (const name of names) expect(PRODUCT_USAGE_METRICS).toContain(name)
+ expect(JSON.stringify(names)).not.toContain('PRIVATE_CANARY')
+})
+
+it('keeps a failed phone create measurable when the optional setup diagnostic cannot be recorded', () => {
+ const names: string[] = []
+ const measured = productUsageRequest('agent_create', metric => {
+ if (metric.startsWith('phone_create_error_setup_code_')) throw Error('reporting unavailable')
+ names.push(metric)
+ }, () => 0, 'phone')
+ expect(() => measured('TMUX_UNAVAILABLE', 'failed', false)).not.toThrow()
+ expect(names).toContain('request_phone_create_error_setup')
+ expect(names).toContain('create_error_setup_code_tmux_unavailable')
})
it('counts the code of an `other` create or resume refusal beside its kind, so each code family adds up to its `_other`', () => {
@@ -247,11 +287,22 @@ it('keeps every refusal core/agents can answer named: in a fixed kind, or in the
if (!name.endsWith('.ts') || name.endsWith('.spec.ts')) continue
for (const match of readFileSync(join(root, name), 'utf8').matchAll(/error: '([A-Z][A-Z0-9_]*)'/g)) codes.add(match[1])
}
+ // These helpers answer through core/agents too. Scanning only that directory missed Windows' new
+ // refusal and every Git worktree refusal (five unlisted launch failures on 2026-10-21).
+ for (const [path, pattern] of [
+ ['projectFolder.ts', /new (?:ProjectFolderError|RepositoryAccessError)\('([A-Z][A-Z0-9_]*)'/g],
+ ['gitProject.ts', /new GitProjectError\('([A-Z][A-Z0-9_]*)'/g],
+ ['windows/launch.ts', /error: '([A-Z][A-Z0-9_]*)'/g],
+ ] as const) {
+ for (const match of readFileSync(new URL(path, import.meta.url), 'utf8').matchAll(pattern)) codes.add(match[1])
+ }
expect(codes.size).toBeGreaterThan(40)
const unnamed = [...codes].filter(code => failureKind(code) === 'other' && launchErrorCode(code) === 'unlisted')
expect(unnamed, 'add each to LAUNCH_ERROR_CODES (lib/productUsageContract.ts and its backend copy)').toEqual([])
// The codes the new-pane watcher sets after a create replied, which no `error: '…'` literal names.
for (const code of ['ENGINE_DID_NOT_START', 'ENGINE_NOT_INSTALLED', 'START_TIMEOUT']) expect(launchErrorCode(code)).toBe(code.toLowerCase())
+ // A backend's code is selected dynamically (terminalBackend.ts), so it is not an error literal in core.
+ for (const code of ['TMUX_UNAVAILABLE', 'PTY_HOST_UNAVAILABLE']) expect(launchErrorCode(code)).toBe(code.toLowerCase())
})
diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.ts
index 50fe72018..a6c5e5a75 100644
--- a/cli/src/lib/productUsageSignals.ts
+++ b/cli/src/lib/productUsageSignals.ts
@@ -61,7 +61,7 @@ export interface ProductUsageLaunchSignal {
phase: 'start' | 'pending' | 'created' | 'failed' | 'cancelled' | 'unconfirmed' | 'work_requested'
origin?: 'interactive' | 'tool'
failure?: Failure
- /** The listed code of an `other` failure, or of a created launch's late one (`late`). */
+ /** The listed code of an `other` or setup failure, or of a created launch's late one (`late`). */
code?: LaunchErrorCode
wait?: 'install' | 'model' | 'native' | 'other'
/** The engine a new launch asked for (`start`), as a fixed name: an installation's first launch counts it. */
@@ -96,7 +96,7 @@ export function productUsageLaunch(type: string, id: unknown, emit: (signal: Pro
return (error: unknown, state: unknown, agent: unknown, held: unknown) => {
if (error != null || state === 'failed') {
const failure = failureKind(error)
- send({ phase: 'failed', failure, ...(failure === 'other' ? { code: launchErrorCode(error) } : {}) })
+ send({ phase: 'failed', failure, ...(failure === 'other' || failure === 'setup' ? { code: launchErrorCode(error) } : {}) })
}
else if (state === 'created' || agent) send(createdSignal(agent))
else if (state === 'pending') send({ phase: 'pending', wait: held === 'install' ? 'install' : held === 'models' ? 'model' : held === 'native' ? 'native' : 'other' })
@@ -161,6 +161,15 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet
// Which code an `other` refusal of a create or a resume had: 22 creates and 9 resumes were `other` on
// 2026-10-16 (production counters), with nothing to say why. A fixed name from the list, or unlisted.
if (kind === 'other' && (action === 'create' || action === 'resume')) count(`error_code_${launchErrorCode(error)}`)
+ // The 2026-10-21 setup spike (10 failed launches, 4 phone creates) named no prerequisite. These new
+ // families preserve the old `other`-by-code totals and keep the phone's creates apart from Desktop's.
+ if (kind === 'setup' && action === 'create') {
+ const code = launchErrorCode(error)
+ count(`error_setup_code_${code}`)
+ if (origin === 'phone') {
+ try { emit(`phone_create_error_setup_code_${code}` as ProductUsageMetric) } catch { /* Optional measurement. */ }
+ }
+ }
// A delete's or a restart's, whatever its kind: the phone's 3 delete refusals were `other` and its 2 restart
// refusals `setup` on 2026-10-19, a kind of nine codes, with nothing to say which.
if (action === 'delete' || action === 'restart') {
diff --git a/cli/src/lib/terminalBackendRecovery.spec.ts b/cli/src/lib/terminalBackendRecovery.spec.ts
new file mode 100644
index 000000000..fb688671b
--- /dev/null
+++ b/cli/src/lib/terminalBackendRecovery.spec.ts
@@ -0,0 +1,61 @@
+import { expect, it, vi } from 'vitest'
+import type { TerminalBackend } from './terminalBackend.js'
+import { createTerminalBackendRecovery } from './terminalBackendRecovery.js'
+
+function setup() {
+ const prepare = vi.fn<TerminalBackend['prepare']>().mockResolvedValue({ state: 'ready' })
+ const backend = { name: 'tmux', prepare } as unknown as TerminalBackend
+ const deps = { backend: backend as TerminalBackend | null, available: vi.fn(() => true),
+ ownedPanes: vi.fn(() => new Map()), recovered: vi.fn() }
+ return { deps, backend, prepare }
+}
+
+it('does no preparation without a configured backend or a newly discoverable executable', async () => {
+ const { deps, prepare } = setup()
+ deps.backend = null
+ expect(await createTerminalBackendRecovery(deps)()).toBeNull()
+ expect(deps.available).not.toHaveBeenCalled()
+ expect(prepare).not.toHaveBeenCalled()
+ const fixture = setup()
+ fixture.deps.available.mockReturnValue(false)
+ expect(await createTerminalBackendRecovery(fixture.deps)()).toBeNull()
+ expect(fixture.prepare).not.toHaveBeenCalled()
+})
+
+it('shares one recovery, registers before returning, and reuses the recovered backend', async () => {
+ const { deps, prepare, backend } = setup()
+ let finish!: (value: { state: 'ready' }) => void
+ prepare.mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const recover = createTerminalBackendRecovery(deps)
+ const first = recover(), second = recover()
+ expect(second).toBe(first)
+ expect(prepare).toHaveBeenCalledExactlyOnceWith({ ownedPanes: deps.ownedPanes.mock.results[0].value })
+ expect(deps.recovered).not.toHaveBeenCalled()
+ finish({ state: 'ready' })
+ expect(await first).toBe(backend)
+ expect(deps.recovered).toHaveBeenCalledExactlyOnceWith(backend)
+ expect(await recover()).toBe(backend)
+ expect(prepare).toHaveBeenCalledOnce()
+ expect(deps.available).toHaveBeenCalledOnce()
+})
+
+it('tries again after an unavailable result instead of caching another absence', async () => {
+ const { deps, prepare, backend } = setup()
+ prepare.mockResolvedValueOnce({ state: 'unavailable', code: 'TMUX_UNAVAILABLE', reason: 'not ready' })
+ const recover = createTerminalBackendRecovery(deps)
+ expect(await recover()).toBeNull()
+ expect(deps.recovered).not.toHaveBeenCalled()
+ expect(await recover()).toBe(backend)
+})
+
+it.each([new Error('not ready'), 'not ready'])('contains a preparation exception and permits a later retry: %s', async error => {
+ const { deps, prepare, backend } = setup()
+ const log = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ prepare.mockRejectedValueOnce(error)
+ try {
+ const recover = createTerminalBackendRecovery(deps)
+ expect(await recover()).toBeNull()
+ expect(log).toHaveBeenCalledWith('[terminal] tmux recovery failed: not ready')
+ expect(await recover()).toBe(backend)
+ } finally { log.mockRestore() }
+})
diff --git a/cli/src/lib/terminalBackendRecovery.ts b/cli/src/lib/terminalBackendRecovery.ts
new file mode 100644
index 000000000..bdd468d3e
--- /dev/null
+++ b/cli/src/lib/terminalBackendRecovery.ts
@@ -0,0 +1,34 @@
+import type { AgentEngine } from '../engines/types.js'
+import type { TerminalBackend } from './terminalBackend.js'
+
+/** Retry a backend missing at boot only when its executable has arrived. New installs can finish
+ * after the daemon starts; a cached absence otherwise refuses every launch until a restart. */
+export function createTerminalBackendRecovery<B extends TerminalBackend>(deps: {
+ backend: B | null
+ available(): boolean
+ ownedPanes(): ReadonlyMap<string, AgentEngine>
+ recovered(backend: B): void
+}) {
+ let ready: B | null = null
+ let pending: Promise<B | null> | null = null
+ return (): Promise<B | null> => {
+ if (ready) return Promise.resolve(ready)
+ if (pending) return pending
+ const backend = deps.backend
+ if (!backend || !deps.available()) return Promise.resolve(null)
+ pending = (async () => {
+ try {
+ const result = await backend.prepare({ ownedPanes: deps.ownedPanes() })
+ if (result.state !== 'ready') return null
+ // Install the route before any caller can spawn a pane or receive its hooks.
+ deps.recovered(backend)
+ ready = backend
+ return backend
+ } catch (error) {
+ console.warn(`[terminal] ${backend.name} recovery failed: ${error instanceof Error ? error.message : String(error)}`)
+ return null
+ }
+ })().finally(() => { pending = null })
+ return pending
+ }
+}
diff --git a/cli/src/lib/tmuxOnPath.spec.ts b/cli/src/lib/tmuxOnPath.spec.ts
index a6056a543..e98448a03 100644
--- a/cli/src/lib/tmuxOnPath.spec.ts
+++ b/cli/src/lib/tmuxOnPath.spec.ts
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { TmuxBackend } from './tmuxBackend.js'
-import { ensureTmuxOnPath, managedTmuxPath, requireTmuxAvailable, resolveViaLoginShell, tmuxInstallDirectories } from './tmuxOnPath.js'
+import { ensureTmuxOnPath, managedTmuxPath, requireTmuxAvailable, resolveViaLoginShell, tmuxAvailableNow, tmuxInstallDirectories } from './tmuxOnPath.js'
const dirs: string[] = []
const originalPath = process.env.PATH
@@ -61,6 +61,19 @@ function fakeTmux(): string {
return dir
}
+it('notices a tmux appearing on PATH, in the managed runtime or a known install folder without running it', () => {
+ const runtime = noManagedTmux(), home = scratch('tmux-recheck-home-')
+ const environment = { PATH: '/missing', HOME: home, HARNESS_HOMEBREW_PREFIXES: join(home, 'no-brew') }
+ expect(tmuxAvailableNow(environment, runtime)).toBe(false)
+ const bin = fakeTmux()
+ expect(tmuxAvailableNow({ ...environment, PATH: bin }, runtime)).toBe(true)
+ expect(tmuxAvailableNow({ ...environment, HARNESS_BIN_DIR: bin }, runtime)).toBe(true)
+ const managed = join(runtime, 'tmux')
+ writeFileSync(managed, '#!/bin/sh\nexit 99\n', { mode: 0o700 })
+ writeFileSync(join(runtime, 'current-tmux'), managed)
+ expect(tmuxAvailableNow(environment, runtime)).toBe(true)
+})
+
describe('ensureTmuxOnPath', () => {
it('adopts the directory the user\'s shell finds tmux in', async () => {
const binDir = fakeTmux()
diff --git a/cli/src/lib/tmuxOnPath.ts b/cli/src/lib/tmuxOnPath.ts
index 2588646a8..5689f8b1a 100644
--- a/cli/src/lib/tmuxOnPath.ts
+++ b/cli/src/lib/tmuxOnPath.ts
@@ -87,6 +87,16 @@ export function tmuxInstallDirectories(
return [userBin, ...brew].filter(isAbsolute)
}
+/** A launch-time hint after tmux was absent at boot: filesystem reads only, no shell or subprocess.
+ * The full preparation still verifies/adopts the discovered route before a pane is made. */
+export function tmuxAvailableNow(
+ environment: NodeJS.ProcessEnv = process.env,
+ runtimeDir: string = appEnv.ADAPTER_RUNTIME_DIR,
+): boolean {
+ return binaryOnPath('tmux', environment) || managedTmuxPath(runtimeDir) !== null
+ || tmuxInstallDirectories(environment).some(dir => binaryOnPath(join(dir, 'tmux'), environment))
+}
+
/** A known location is only a fallback when its tmux actually runs on this computer. */
function tmuxRuns(binary: string, env: NodeJS.ProcessEnv): Promise<boolean> {
return new Promise(resolve => {
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 9d58a518d..9624afe91 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -327,6 +327,19 @@ launch refusals and its engines that did not start after a create each name thei
codes; a large `unlisted` share means a code is missing from `LAUNCH_ERROR_CODES`. Feedback
is one source of evidence; a missing response does not identify why a person stopped using Harness.
+Launch codes include Windows launch and terminal-host refusals, and Git branch/worktree preparation
+refusals. Older CLI releases reported these as `unlisted`; an old total cannot recover which code it
+contained. Naming a refusal in a later release does not establish the cause of an earlier failure.
+
+Setup refusals are also counted by their fixed code in separate families: `launch_failed_setup_code_<code>`
+adds up to `launch_failed_setup`, `create_error_setup_code_<code>` to `create_error_setup`, and
+`phone_create_error_setup_code_<code>` to `request_phone_create_error_setup`. This distinguishes missing
+tmux/terminal hosts, native preparation, spawning and registration failures without sending their messages
+or paths. Existing failure-kind totals and the `other`-by-code families keep their meaning. A launch's
+status polls count its setup outcome once; request counters still count each create request. Older CLI
+releases send no setup-by-code counts, so compare coverage by release. Deploy the backend vocabulary before
+the CLI: an older backend refuses a whole report containing a new counter.
+
## Rollout and privacy controls
Deploy backend schema and the singleton worker first, including unique indexes and TTL indexes.