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 auto-retry logic to agent pane registration to handle stale registry collisions

0xken15345e00fedcc7
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 7a2bc33fb..d5f97ff55 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -59,6 +59,7 @@ import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallbac
import { restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'
import { findLiveSession } from './lib/sessionRepair.js'
import { TmuxBackend } from './lib/tmuxBackend.js'
+import { createAndRegisterPane } from './lib/createAgentPane.js'
import { basename } from 'node:path'
import {
bypassPermissionActive,
@@ -3356,39 +3357,26 @@ async function runForeground(session: AuthSession): Promise<void> {
const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installIfMissing, clearEnv, cwd }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
- const spawned = await tmuxBackend.create({
- // The login shell starts somewhere stable; its argv enters the requested workspace after rc files.
- cwd: homedir(),
- label,
- command: argv,
- ...(gridLaunch ? { env: gridLaunch.env } : {}),
- })
- if (spawned.state !== 'succeeded') {
- console.warn(`[agent] create ${engine} failed · tmux could not open a pane · ${spawned.reason ?? ''}`)
- // `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary. So a
- // daemon that cannot resolve `tmux` at all (a login context whose PATH lacks Homebrew's bin,
- // the usual shape after a reboot) reported the same SPAWN_FAILED as a tmux that answered and
- // refused. They need different fixes, so they get different codes.
- const missing = spawned.reason === 'tmux is unavailable'
- return {
- ok: false,
- error: missing ? 'TMUX_UNAVAILABLE' : 'SPAWN_FAILED',
- detail: spawned.reason,
- }
- }
// 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({
+ // `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary, so a
+ // daemon that cannot resolve `tmux` at all (a login context whose PATH lacks Homebrew's bin, the
+ // usual shape after a reboot) is reported as `TMUX_UNAVAILABLE` too, distinctly from a tmux that
+ // answered and refused (`SPAWN_FAILED`) — see createAgentPane.ts. Registration itself is retried
+ // there: a stale registry entry from a previous tmux-server generation occasionally collides with
+ // a freshly-minted pane id, and that collision clears on its own on the very next pane.
+ const result = await createAndRegisterPane({
+ tmuxBackend,
+ registry,
engine,
- runtimes: [spawned.runtime],
- primaryRuntimeKey: terminalRouteKey(spawned.runtime),
cwd,
+ sessionLabel: label,
+ argv,
+ env: gridLaunch?.env,
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' }
- }
+ if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
+ const { spawned, pending } = result
announceSession(pending)
const watchCreatedPane = async (): Promise<void> => {
diff --git a/cli/src/lib/createAgentPane.spec.ts b/cli/src/lib/createAgentPane.spec.ts
new file mode 100644
index 000000000..4f9c04879
--- /dev/null
+++ b/cli/src/lib/createAgentPane.spec.ts
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import type { TerminalCreateResult, TmuxRuntimeRef } from './terminalTypes.js'
+import { createAndRegisterPane } from './createAgentPane.js'
+
+let dataDir = ''
+
+// Mirrors lib/registry.spec.ts's loadRegistryModule(): a fresh registry module per test, backed by
+// its own temp state dir, so pre-seeded runtimeIndex collisions never leak between tests.
+async function loadRegistryModule() {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ process.env.CLAUDE_PROJECTS_DIR = dataDir
+ process.env.CODEX_HOME = dataDir
+ process.env.CURSOR_HOME = dataDir
+ return import('./registry.js')
+}
+
+const succeeded = (paneId: string): TerminalCreateResult<TmuxRuntimeRef> =>
+ ({ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } })
+
+/** `results[N]` is what `create()` answers on its (N+1)th call; the last entry repeats past that. */
+function fakeTmux(results: Array<TerminalCreateResult<TmuxRuntimeRef>>) {
+ let call = 0
+ return {
+ create: vi.fn(async () => results[Math.min(call++, results.length - 1)]!),
+ kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })),
+ }
+}
+
+describe('createAndRegisterPane', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
+ })
+
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ it('registers on the first attempt when the pane is unclaimed', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const tmuxBackend = fakeTmux([succeeded('%1')])
+
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-1', argv: ['claude'],
+ })
+
+ expect(result.ok).toBe(true)
+ expect(tmuxBackend.create).toHaveBeenCalledTimes(1)
+ expect(tmuxBackend.create).toHaveBeenCalledWith(expect.objectContaining({ label: 'harness-claude-1' }))
+ expect(tmuxBackend.kill).not.toHaveBeenCalled()
+ })
+
+ it('retries past a stale registration collision and succeeds on the next pane', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ // Simulates a stale entry from a previous tmux-server generation already holding %1.
+ registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%1' }], cwd: '/tmp/other' })
+ const tmuxBackend = fakeTmux([succeeded('%1'), succeeded('%2')])
+
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-1', argv: ['claude'],
+ })
+
+ expect(result.ok).toBe(true)
+ if (result.ok) expect(result.spawned.runtime.paneId).toBe('%2')
+ expect(tmuxBackend.create).toHaveBeenCalledTimes(2)
+ expect(tmuxBackend.create).toHaveBeenNthCalledWith(2, expect.objectContaining({ label: 'harness-claude-1-r2' }))
+ expect(tmuxBackend.kill).toHaveBeenCalledTimes(1)
+ expect(tmuxBackend.kill).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' })
+ })
+
+ it('gives up with REGISTRATION_FAILED after 3 attempts when every pane collides', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ for (const paneId of ['%1', '%2', '%3']) {
+ registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId }], cwd: '/tmp/other' })
+ }
+ const tmuxBackend = fakeTmux([succeeded('%1'), succeeded('%2'), succeeded('%3')])
+
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-1', argv: ['claude'],
+ })
+
+ expect(result.ok).toBe(false)
+ if (!result.ok) {
+ expect(result.error).toBe('REGISTRATION_FAILED')
+ expect(result.detail).toContain('3 attempts')
+ }
+ expect(tmuxBackend.create).toHaveBeenCalledTimes(3)
+ expect(tmuxBackend.kill).toHaveBeenCalledTimes(3)
+ })
+
+ it('does not retry a tmux spawn failure', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const openPendingAgent = vi.spyOn(registry, 'openPendingAgent')
+ const tmuxBackend = fakeTmux([{ state: 'failed', dispatch: 'not_started', reason: 'tmux is unavailable' }])
+
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-1', argv: ['claude'],
+ })
+
+ expect(result.ok).toBe(false)
+ if (!result.ok) expect(result.error).toBe('TMUX_UNAVAILABLE')
+ expect(tmuxBackend.create).toHaveBeenCalledTimes(1)
+ expect(tmuxBackend.kill).not.toHaveBeenCalled()
+ expect(openPendingAgent).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
new file mode 100644
index 000000000..c980f6558
--- /dev/null
+++ b/cli/src/lib/createAgentPane.ts
@@ -0,0 +1,82 @@
+/**
+ * Open a tmux pane for a new agent and claim it in the registry, retrying the claim up to
+ * `maxAttempts` times.
+ *
+ * `registry.openPendingAgent` refuses a pane whose route is already in `runtimeIndex` — which
+ * happens for real, rarely, when a STALE entry from a previous tmux-server generation (the
+ * registry only clears its cache on a detected machine reboot, not a tmux-server-only restart)
+ * collides with the brand-new pane's id. That collision is transient: a fresh `tmuxBackend.create`
+ * call mints a never-before-used pane id from tmux's own monotonic counter, so a retry almost
+ * always lands on an unclaimed route without needing to wait for anything. A tmux spawn failure
+ * (`SPAWN_FAILED`/`TMUX_UNAVAILABLE`) is a different, not-obviously-transient problem and is
+ * returned immediately — only the registration race is retried.
+ */
+import { homedir } from 'node:os'
+import type { AgentEngine } from '../engines/types.js'
+import type { RegisteredSession } from './registry.js'
+import type { TerminalBackend } from './terminalBackend.js'
+import type { TerminalCreateResult, TmuxRuntimeRef } from './terminalTypes.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+
+const DEFAULT_MAX_ATTEMPTS = 3
+
+export interface CreateAgentPaneDeps {
+ tmuxBackend: Pick<TerminalBackend<TmuxRuntimeRef>, 'create' | 'kill'>
+ registry: { openPendingAgent: (input: {
+ engine: AgentEngine
+ runtimes: TmuxRuntimeRef[]
+ primaryRuntimeKey?: string
+ cwd?: string | null
+ grid?: { baseUrl: string; model: string | null } | null
+ }) => RegisteredSession | null }
+ engine: AgentEngine
+ cwd?: string | null
+ /** Base tmux session name (`-s`). Retries append `-r<attempt>` — see module doc. */
+ sessionLabel: string
+ argv: string[]
+ env?: Record<string, string>
+ grid?: { baseUrl: string; model: string | null } | null
+ maxAttempts?: number
+}
+
+export type CreateAgentPaneResult =
+ | { ok: true; spawned: TerminalCreateResult<TmuxRuntimeRef> & { state: 'succeeded' }; pending: RegisteredSession }
+ | { ok: false; error: 'TMUX_UNAVAILABLE' | 'SPAWN_FAILED' | 'REGISTRATION_FAILED'; detail: string }
+
+export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<CreateAgentPaneResult> {
+ const maxAttempts = deps.maxAttempts ?? DEFAULT_MAX_ATTEMPTS
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ const label = attempt === 1 ? deps.sessionLabel : `${deps.sessionLabel}-r${attempt}`
+ const spawned = await deps.tmuxBackend.create({
+ // The login shell starts somewhere stable; its argv enters the requested workspace after rc
+ // files. `deps.cwd` still travels below, into the registry entry — this is only about where
+ // the pane's OWN shell starts, not the workspace the agent ends up in.
+ cwd: homedir(),
+ label,
+ command: deps.argv,
+ ...(deps.env ? { env: deps.env } : {}),
+ })
+ if (spawned.state !== 'succeeded') {
+ console.warn(`[agent] create ${deps.engine} failed · tmux could not open a pane · ${spawned.reason ?? ''}`)
+ const missing = spawned.reason === 'tmux is unavailable'
+ return { ok: false, error: missing ? 'TMUX_UNAVAILABLE' : 'SPAWN_FAILED', detail: spawned.reason }
+ }
+ const pending = deps.registry.openPendingAgent({
+ engine: deps.engine,
+ runtimes: [spawned.runtime],
+ primaryRuntimeKey: terminalRouteKey(spawned.runtime),
+ cwd: deps.cwd,
+ grid: deps.grid,
+ })
+ if (pending) return { ok: true, spawned, pending }
+ console.warn(`[agent] create ${deps.engine} registration failed · pane ${spawned.runtime.paneId} · `
+ + `attempt ${attempt}/${maxAttempts}`)
+ await deps.tmuxBackend.kill(spawned.runtime)
+ }
+ console.warn(`[agent] create ${deps.engine} registration failed · giving up after ${maxAttempts} attempts`)
+ return {
+ ok: false,
+ error: 'REGISTRATION_FAILED',
+ detail: `tmux pane could not be registered after ${maxAttempts} attempts`,
+ }
+}