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.

refactor: allow sessionless agents to update their process identity in-place while keeping the same agent ID

0xken1515816b15d890
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index a53b6831c..42057699b 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -765,6 +765,48 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
})
+ it('keeps the agent id when an unbound launcher becomes a new process in the same pane', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/new-folder',
+ processIdentity: processIdentity(101),
+ })
+
+ const replaced = registry.openProcessAgent({
+ engine: 'claude', tmuxPane: '%1', cwd: '/tmp/new-folder', processIdentity: processIdentity(202),
+ })
+
+ expect(replaced?.entry.agentId).toBe('agent-1')
+ expect(replaced?.entry.sessionId).toBe('')
+ expect(replaced?.entry.processIdentity).toEqual(processIdentity(202))
+ expect(replaced?.isNew).toBe(false)
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('does not transfer a bound session to a replacement process in the same pane', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: processIdentity(101),
+ })
+ registerProcess(registry, {
+ launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'),
+ tmuxPane: '%1', cwd: '/tmp/demo',
+ })
+
+ const replacement = registry.openProcessAgent({
+ agentId: 'replacement-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: processIdentity(202),
+ })
+
+ expect(replacement?.entry.agentId).toBe('replacement-agent')
+ expect(replacement?.entry.sessionId).toBe('')
+ expect(replacement?.evicted).toBe('s1')
+ expect(registry.resolve('s1')).toBeUndefined()
+ })
+
it('re-observing the same runtime keeps the session it had already bound', async () => {
const { registry } = await loadRegistryModule()
registry.load()
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 2f607c9af..c03f6428e 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -787,9 +787,16 @@ class Registry {
const processAgent = processAgentId ? this.agents.get(processAgentId) : undefined
const routeAgent = runtimes
.map((runtime) => this.byRuntimeEngine(runtime, engine))
- .find((agent) => !agent?.processIdentity || (
- agent.processIdentity.pid === processIdentity.pid
- && agent.processIdentity.startMarker === processIdentity.startMarker
+ .find((agent) => agent && (
+ // Before its first engine session, a process-agent is owned by its terminal route. Native
+ // launchers can replace PID/image while showing setup or folder-trust UI; update that agent in
+ // place instead of deleting/recreating its tile. Once bound, process identity remains strict.
+ !agent.sessionId
+ || !agent.processIdentity
+ || (
+ agent.processIdentity.pid === processIdentity.pid
+ && agent.processIdentity.startMarker === processIdentity.startMarker
+ )
))
const existing = processAgent ?? routeAgent
if (existing) {
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index 2509e6533..907e3df47 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -211,6 +211,51 @@ describe('verified process adoption', () => {
expect(onDiscovered).not.toHaveBeenCalled()
})
+ it('keeps a sessionless agent when the engine replaces its process inside the same pane', async () => {
+ const existing = session([tmux])
+ const replacement = {
+ ...observed([tmux]),
+ processIdentity: { pid: 84, executable: 'claude', startMarker: 'Sat Aug 15 10:00:02 2026' },
+ }
+ let current = existing
+ const onObserved = vi.fn(async (candidate: DiscoveredTerminalAgent) => {
+ current = { ...current, processIdentity: candidate.processIdentity }
+ })
+ const onDiscovered = vi.fn()
+ const onRemoved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered, onObserved, onDormant: vi.fn(), onRemoved,
+ probe: async () => probe(
+ [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],
+ [replacement],
+ ),
+ })
+
+ await reconciler.trigger()
+
+ expect(onObserved).toHaveBeenCalledWith(replacement, existing)
+ expect(current.agentId).toBe(existing.agentId)
+ expect(current.processIdentity).toEqual(replacement.processIdentity)
+ expect(onDiscovered).not.toHaveBeenCalled()
+ expect(onRemoved).not.toHaveBeenCalled()
+ })
+
+ it('validates an unbound route by its live engine rather than its provisional process id', async () => {
+ const current = session([tmux])
+ const validate = vi.fn(async () => ({ state: 'alive' as const }))
+ const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackend
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),
+ })
+
+ await reconciler.trigger()
+
+ expect(validate).toHaveBeenCalledWith(tmux, { engine: 'claude', processIdentity: undefined })
+ })
+
it('reports no adopted agent when the registry callback rejects the process', async () => {
const onDiscovered = vi.fn()
const reconciler = new TerminalAgentReconciler({
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index 8e366a8c7..baf488138 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -32,6 +32,43 @@ function currentProcessKey(session: RegisteredSession): string | null {
return session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : null
}
+function sharesPlacement(
+ current: Pick<RegisteredSession, 'runtimes'>,
+ observed: Pick<DiscoveredTerminalAgent, 'runtimes'>,
+): boolean {
+ const placements = new Set(current.runtimes.map(terminalPlacementKey))
+ return observed.runtimes.some((runtime) => placements.has(terminalPlacementKey(runtime)))
+}
+
+/**
+ * A process-backed agent exists before an engine session does. During that interval the terminal route
+ * is its stable identity: launchers are allowed to exec/fork into the real native binary while painting
+ * a first-run prompt (Claude folder trust is the common case). Once a session binds, process identity is
+ * authoritative again so a different process in the same pane cannot inherit an existing transcript.
+ */
+function unboundRouteOwner(
+ current: readonly RegisteredSession[],
+ observed: DiscoveredTerminalAgent,
+): RegisteredSession | undefined {
+ const matches = current.filter((candidate) => (
+ !candidate.sessionId
+ && candidate.engine === observed.engine
+ && sharesPlacement(candidate, observed)
+ ))
+ return matches.length === 1 ? matches[0] : undefined
+}
+
+function unboundRouteObservation(
+ current: RegisteredSession,
+ observed: readonly DiscoveredTerminalAgent[],
+): DiscoveredTerminalAgent | undefined {
+ if (current.sessionId) return undefined
+ const matches = observed.filter((candidate) => (
+ candidate.engine === current.engine && sharesPlacement(current, candidate)
+ ))
+ return matches.length === 1 ? matches[0] : undefined
+}
+
/** Serialized, failure-isolated reconciliation across every enabled backend instance. */
export class TerminalAgentReconciler {
private readonly misses = new Map<string, number>()
@@ -70,10 +107,14 @@ export class TerminalAgentReconciler {
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)
+ const before = this.deps.current()
+ const current = before.find((candidate) => currentProcessKey(candidate) === key)
+ ?? unboundRouteOwner(before, observed)
if (current) await this.deps.onObserved(observed, current)
else await this.deps.onDiscovered(observed)
- return this.deps.current().find((candidate) => currentProcessKey(candidate) === key)
+ const after = this.deps.current()
+ return after.find((candidate) => currentProcessKey(candidate) === key)
+ ?? unboundRouteOwner(after, observed)
}
return this.deps.transaction ? this.deps.transaction(apply) : apply()
}
@@ -130,8 +171,9 @@ export class TerminalAgentReconciler {
// conflict handling never depends on backend probe completion order.
for (const current of before) {
const processKey = currentProcessKey(current)
- const observed = processKey ? observedByProcess.get(processKey) : undefined
- if (observed) matchedProcesses.add(processKey!)
+ const observed = (processKey ? observedByProcess.get(processKey) : undefined)
+ ?? unboundRouteObservation(current, probe.agents)
+ if (observed) matchedProcesses.add(processIdentityKey(observed.engine, observed.processIdentity))
let nextRuntimes = current.runtimes
for (const runtime of current.runtimes) {
@@ -155,7 +197,11 @@ export class TerminalAgentReconciler {
if (backend && current.processIdentity) {
const validation = await backend.validate(runtime, {
engine: current.engine,
- processIdentity: current.processIdentity,
+ // Before an engine session exists, the pane is the agent. Claude and other native
+ // launchers may replace their process while a first-run prompt is visible; requiring the
+ // earlier PID here deletes a perfectly live sessionless tile. A bound session keeps the
+ // strict PID/start-marker check so another process cannot inherit its transcript.
+ processIdentity: current.sessionId ? current.processIdentity : undefined,
}).catch((error: unknown) => ({
state: 'unknown' as const,
reason: error instanceof Error ? error.message : 'terminal validation failed',