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: implement adoptVerified to allow direct session binding for newly created agent processes

0xken154b446bd6c4a8
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 8976c34b9..0048699ad 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -292,7 +292,7 @@ export class BackendSocket {
* process and forgets the session. Keeps recap + agent name. */
onDeleteAgent: ((sessionId: string) => void) | null = null
/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the
- * requested folder and returns the registered session once discovery has picked it up. */
+ * requested folder and returns its process-agent. Session metadata may bind later through hooks. */
onCreateAgent: ((input: { engine: AgentEngine; cwd: string; bypassPermission: boolean }) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
/** Called when the web/device sends chat input to an agent terminal. */
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b3c90cb3f..95ddb2894 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2711,15 +2711,23 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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. A fresh,
- // authoritative process lookup makes that a valid sessionless process-agent instead of reporting
- // ENGINE_DID_NOT_START. It never sends input to the pane: folder trust remains the user's choice.
+ // 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) {
- await agentReconciler.triggerHint(spawned.runtime, engine)
- const session = registry.byRuntimeEngine(spawned.runtime, engine)
+ 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 }
@@ -2751,6 +2759,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index 4d732f0a0..b9bd70df4 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -121,3 +121,60 @@ describe('composite terminal reconciliation', () => {
expect(onDormant).not.toHaveBeenCalled()
})
})
+
+describe('verified process adoption', () => {
+ it('opens a sessionless agent through the normal discovery callback without another inventory scan', async () => {
+ let current: RegisteredSession[] = []
+ const candidate = observed([tmux])
+ const onDiscovered = vi.fn(async () => { current = [session([tmux])] })
+ const probeSnapshot = vi.fn(async () => {
+ throw new Error('verified adoption must not run the general probe')
+ })
+ let transactionCalls = 0
+ const transaction = async <T>(apply: () => T | Promise<T>): Promise<T> => {
+ transactionCalls += 1
+ return await apply()
+ }
+ const reconciler = new TerminalAgentReconciler({
+ current: () => current, backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: probeSnapshot, transaction,
+ })
+
+ const adopted = await reconciler.adoptVerified(candidate)
+
+ expect(adopted).toBe(current[0])
+ expect(adopted?.sessionId).toBe('')
+ expect(adopted?.processIdentity).toEqual(identity)
+ expect(onDiscovered).toHaveBeenCalledWith(candidate)
+ expect(transactionCalls).toBe(1)
+ expect(probeSnapshot).not.toHaveBeenCalled()
+ })
+
+ it('refreshes an already adopted process instead of opening a duplicate agent', async () => {
+ const existing = session([tmux])
+ const onDiscovered = vi.fn()
+ const onObserved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [existing], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),
+ })
+
+ const adopted = await reconciler.adoptVerified(observed([tmux]))
+
+ expect(adopted).toBe(existing)
+ expect(onObserved).toHaveBeenCalledWith(observed([tmux]), existing)
+ expect(onDiscovered).not.toHaveBeenCalled()
+ })
+
+ it('reports no adopted agent when the registry callback rejects the process', async () => {
+ const onDiscovered = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ })
+
+ expect(await reconciler.adoptVerified(observed([tmux]))).toBeUndefined()
+ expect(onDiscovered).toHaveBeenCalledOnce()
+ })
+})
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index 368f70047..ff434f6ee 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -59,6 +59,25 @@ export class TerminalAgentReconciler {
return this.trigger()
}
+ /**
+ * Adopt an engine process that a backend-specific, pane-scoped probe already verified.
+ *
+ * New-agent creation has stronger evidence than the periodic inventory scan: it owns the exact
+ * runtime it just created and resolves the requested engine beneath that runtime. Passing that
+ * observation through the same callbacks used by reconciliation keeps process-agent creation and
+ * later session binding on one path, while avoiding a second best-effort inventory snapshot.
+ */
+ async adoptVerified(observed: DiscoveredTerminalAgent): Promise<RegisteredSession | undefined> {
+ const apply = async (): Promise<RegisteredSession | undefined> => {
+ const key = processIdentityKey(observed.engine, observed.processIdentity)
+ const current = this.deps.current().find((candidate) => currentProcessKey(candidate) === key)
+ if (current) await this.deps.onObserved(observed, current)
+ else await this.deps.onDiscovered(observed)
+ return this.deps.current().find((candidate) => currentProcessKey(candidate) === key)
+ }
+ return this.deps.transaction ? this.deps.transaction(apply) : apply()
+ }
+
/** Hide an explicitly deleted process until an authoritative scan proves that process exited. */
suppress(session: Pick<RegisteredSession, 'engine' | 'processIdentity'>): void {
if (session.processIdentity) this.suppressed.add(processIdentityKey(session.engine, session.processIdentity))