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.

fix(registry): drop the agent a resume leaves behind, and tell the clients

0xdiego25ddc376e885c6
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 10c7e77f5..cc5e361c0 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1764,12 +1764,23 @@ async function runForeground(session: AuthSession): Promise<void> {
}
/** Release a mutable session binding, or remove the process-owned agent everywhere. */
- const forgetSession = (id: string, opts: { force?: boolean; keepAgent?: boolean } = {}): void => {
+ const forgetSession = (
+ id: string,
+ opts: { force?: boolean; keepAgent?: boolean; agentId?: string } = {},
+ ): void => {
const doomed = registry.resolve(id)
const sessionId = doomed?.sessionId || id
+ // Clients key on the AGENT id. Normally it is read off the entry, but an
+ // agent already removed from the registry cannot be looked up — and
+ // announcing its sessionId instead is silently useless: the app takes
+ // payload.agentId verbatim, matches nothing, and leaves the dead row on
+ // screen. Callers who know the id pass it.
+ const announceId = doomed?.agentId ?? opts.agentId ?? sessionId
+
console.log(opts.keepAgent
- ? `[agent] ${sid(doomed?.agentId ?? sessionId)} released session ${sid(sessionId)}`
- : `[agent] ${sid(doomed?.agentId ?? sessionId)} forgotten`)
+ ? `[agent] ${sid(announceId)} released session ${sid(sessionId)}`
+ : `[agent] ${sid(announceId)} forgotten`)
+
if (opts.keepAgent) registry.unbindSession(sessionId)
else if (doomed) registry.removeAgent(doomed.agentId)
else registry.remove(sessionId)
@@ -1809,17 +1820,20 @@ async function runForeground(session: AuthSession): Promise<void> {
input.forget(doomed?.agentId ?? sessionId)
mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summary
if (opts.keepAgent) return
- backend.send({ type: 'agent_deleted', payload: { agentId: doomed?.agentId ?? sessionId } }) // web tab
- backend.sendCommander({ type: 'agent_deleted', payload: { agentId: doomed?.agentId ?? sessionId } })
+ backend.send({ type: 'agent_deleted', payload: { agentId: announceId } }) // web tab
+ backend.sendCommander({ type: 'agent_deleted', payload: { agentId: announceId } })
+
}
type RegisteredMeta = {
isNew: boolean
evicted: string | null
rebound: string | null
+ orphaned?: { agentId: string; sessionId: string } | null
hookEvent?: string
}
+
const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {
if (meta.rebound) {
registry.inheritName(meta.rebound, entry.sessionId)
@@ -1828,8 +1842,23 @@ async function runForeground(session: AuthSession): Promise<void> {
backend.send({ type: 'session_reset', payload: { staleSessionId: meta.rebound } })
console.log(`[agent] ${sid(entry.agentId)} rebound ${sid(meta.rebound)} → ${sid(entry.sessionId)}`)
} else if (meta.evicted) {
+
forgetSession(meta.evicted, { force: true })
}
+ // The agent this bind emptied out — `claude --resume` in a second pane, with
+ // the first one's engine already gone. The registry dropped it; without this
+ // the app kept showing it until someone hit Reload machines by hand, and
+ // opening it landed on TERMINAL FROZEN because it has nothing left to open.
+ //
+ // Not part of the chain above: a rebound bind can orphan an agent too, so
+ // this has to be asked independently of which branch ran.
+ if (meta.orphaned) {
+ forgetSession(meta.orphaned.agentId, {
+ force: true,
+ agentId: meta.orphaned.agentId,
+ })
+ }
+
// agy is excluded for the same reason as cursor, arriving by a different road: it has no
// session-start event at all. The closest thing is `PreInvocation`, which fires before EVERY model
// round-trip — four to seven times in one measured turn — and each one re-folded the transcript and
@@ -1998,7 +2027,21 @@ async function runForeground(session: AuthSession): Promise<void> {
gateway: observed.gateway,
})
if (!opened) return
- if (opened.evicted) console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted)}`)
+ if (opened.evicted) {
+ console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted.agentId)}`)
+ // ⚠️ THE REGISTRY ALREADY DROPPED IT; NOBODY HAD TOLD THE CLIENTS. That
+ // is the whole bug behind "two sessions, one of them frozen": resuming
+ // an engine in a pane another agent owned takes the pane away, and an
+ // agent with no pane can never be opened again — but the app kept the
+ // row until someone hit Reload machines by hand, and opening it landed
+ // on TERMINAL FROZEN. This is the same call the hook path already makes
+ // for the same situation (see onRegistered below).
+ forgetSession(opened.evicted.sessionId || opened.evicted.agentId, {
+ force: true,
+ agentId: opened.evicted.agentId,
+ })
+ }
+
if (opened.isNew) {
console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · terminal=${observed.primaryRuntimeKey}`)
announceSession(opened.entry)
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index c2d789b49..d14b029bd 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -49,7 +49,18 @@ export interface PairOutcome {
}
export interface HookServerHandlers {
- onRegistered: (entry: RegisteredSession, meta: { isNew: boolean; evicted: string | null; rebound: string | null; hookEvent?: string }) => void
+ onRegistered: (
+ entry: RegisteredSession,
+ meta: {
+ isNew: boolean
+ evicted: string | null
+ rebound: string | null
+ /** An agent this bind left with no session and no process — see registry.register. */
+ orphaned?: { agentId: string; sessionId: string } | null
+ hookEvent?: string
+ },
+ ) => void
+
/** SessionEnd — a reconciliation hint only; it is never process-lifetime authority. */
onSessionEnd: (sessionId: string, reason: string | undefined) => void
/** Ensure a matching process-owned agent exists before a hook binds its mutable engine session. */
@@ -276,7 +287,7 @@ async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers
if (!result) return
console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine}`
+ ` · isNew=${result.isNew} · after waiting ${((i + 1) * TRANSCRIPT_WAIT_MS) / 1000}s for its transcript`)
- handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, hookEvent: body.hookEvent })
+ handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
return
}
console.warn(`[hooks] ${sid(body.sessionId ?? '?')} announced a transcript that never appeared: ${body.transcriptPath}`)
@@ -304,7 +315,7 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers
const result = registry.register(body)
if (!result) return
console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=hermes · isNew=${result.isNew} · after a source check`)
- handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, hookEvent: body.hookEvent })
+ handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
}
export function startHookServer(
@@ -424,7 +435,7 @@ export function startHookServer(
return
}
console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`)
- handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, hookEvent: body.hookEvent })
+ handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
json(200, { ok: true })
return
}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index a794c0177..8c2d1b56e 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -33,7 +33,9 @@ function registerProcess(
isNew: boolean
evicted: string | null
rebound: string | null
+ orphaned: { agentId: string; sessionId: string } | null
} | null
+
},
input: RegisterInput,
) {
@@ -818,10 +820,104 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(replacement?.entry.agentId).toBe('replacement-agent')
expect(replacement?.entry.sessionId).toBe('')
- expect(replacement?.evicted).toBe('s1')
+ // BOTH ids, because the caller has to finish a removal the registry only
+ // half did: the agent is already gone from here, so the agentId is the only
+ // thing clients can be told to drop, and the sessionId the only thing the
+ // daemon's own per-session state can be cleaned by.
+ expect(replacement?.evicted).toEqual({
+ agentId: 'bound-agent',
+ sessionId: 's1',
+ })
expect(registry.resolve('s1')).toBeUndefined()
})
+ it('removes an agent a resume left with no session and no process', async () => {
+ // `claude --resume` in a second pane after quitting the first: the session
+ // moves, and the agent it moved from has nothing left to be. Kept, it is a
+ // second row for the same work that can never be opened — which is exactly
+ // the "Terminal frozen" tile this removes.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'old-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: processIdentity(401),
+ })
+ registerProcess(registry, {
+ launcherId: 'old-agent', sessionId: 's-resume', transcriptPath: transcript('s-resume'),
+ tmuxPane: '%1', cwd: '/tmp/demo',
+ })
+ registry.setActive('old-agent', false) // its engine was quit before the resume
+
+ registry.openProcessAgent({
+ agentId: 'new-agent', engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo',
+ processIdentity: processIdentity(402),
+ })
+ const bound = registerProcess(registry, {
+ launcherId: 'new-agent', sessionId: 's-resume', transcriptPath: transcript('s-resume'),
+ tmuxPane: '%2', cwd: '/tmp/demo',
+ })
+
+ expect(bound?.orphaned).toEqual({ agentId: 'old-agent', sessionId: 's-resume' })
+ expect(registry.byAgent('old-agent')).toBeUndefined()
+ expect(registry.byAgent('new-agent')?.sessionId).toBe('s-resume')
+ })
+
+ it('leaves a still-running agent alone when its session is resumed elsewhere', async () => {
+ // Its engine is alive, so it is a real second agent that merely became
+ // unbound. Removing it would take a working tile off the screen.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'live-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: processIdentity(501),
+ })
+ registerProcess(registry, {
+ launcherId: 'live-agent', sessionId: 's-live', transcriptPath: transcript('s-live'),
+ tmuxPane: '%1', cwd: '/tmp/demo',
+ })
+
+ registry.openProcessAgent({
+ agentId: 'other-agent', engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo',
+ processIdentity: processIdentity(502),
+ })
+ const bound = registerProcess(registry, {
+ launcherId: 'other-agent', sessionId: 's-live', transcriptPath: transcript('s-live'),
+ tmuxPane: '%2', cwd: '/tmp/demo',
+ })
+
+ expect(bound?.orphaned).toBeNull()
+ expect(registry.byAgent('live-agent')).toBeDefined()
+ expect(registry.byAgent('live-agent')?.sessionId).toBe('')
+ })
+
+ it('reports no eviction when the displaced agent still owns another pane', async () => {
+
+ // It lost a terminal, not its life. Announcing it as deleted would take a
+ // working tile off every client.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'two-panes',
+ engine: 'claude',
+ runtimes: [
+ { backend: 'tmux', paneId: '%1' },
+ { backend: 'tmux', paneId: '%2' },
+ ],
+
+ cwd: '/tmp/demo',
+ processIdentity: processIdentity(301),
+ })
+
+ const replacement = registry.openProcessAgent({
+ agentId: 'takes-pane-1', engine: 'codex', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: processIdentity(302),
+ })
+
+ expect(replacement?.evicted).toBeNull()
+ expect(registry.byAgent('two-panes')?.runtimes).toHaveLength(1)
+ })
+
+
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 7fb2d5f9f..fd85e561a 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -788,7 +788,22 @@ class Registry {
processIdentity: ProcessIdentity
gateway?: 'ori' | null
}):
- { entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {
+ {
+ entry: RegisteredSession
+ isNew: boolean
+ /**
+ * The agent this one took a terminal from, once it has no terminal left.
+ *
+ * BOTH IDS, because by the time the caller reads this the agent is ALREADY
+ * GONE from the registry — `drop()` removes it and the loop below only
+ * re-indexes it if it still owns a runtime — so nothing can look either id
+ * up afterwards. Clients key on the agentId and the daemon's per-session
+ * state keys on the sessionId, and the caller needs both to finish the
+ * removal it was never told to do.
+ */
+ evicted: { agentId: string; sessionId: string } | null
+ } | null {
+
if (this.writeBlocked) return null
const { engine, processIdentity } = input
const runtimes = normalizedRuntimes(input.runtimes, input.tmuxPane)
@@ -828,7 +843,8 @@ class Registry {
}
const agentId = input.agentId || randomUUID()
- let evicted: string | null = null
+ let evicted: { agentId: string; sessionId: string } | null = null
+
for (const runtime of runtimes) {
const otherId = this.runtimeIndex.get(terminalRouteKey(runtime))
const other = otherId ? this.agents.get(otherId) : undefined
@@ -840,7 +856,12 @@ class Registry {
other.active = other.runtimes.length > 0
if (other.runtimes.length) this.index(other)
else this.terminalAvailableAgents.delete(other.agentId)
- evicted ??= other.sessionId || other.agentId
+ // Only when it has nothing left. An agent that still owns another pane is
+ // alive and simply narrower; it must not be announced as deleted.
+ if (!other.runtimes.length) {
+ evicted ??= { agentId: other.agentId, sessionId: other.sessionId }
+ }
+
}
const now = Date.now()
const entry: RegisteredSession = {
@@ -885,7 +906,25 @@ class Registry {
* showing two tiles. Returns { entry, isNew, evicted } — isNew=false on a re-register (so callers
* can skip re-announcing), evicted = the sessionId displaced from this pane (caller removes it).
*/
- register(input: RegisterInput): { entry: RegisteredSession; isNew: boolean; evicted: string | null; rebound: string | null } | null {
+ register(input: RegisterInput): {
+ entry: RegisteredSession
+ isNew: boolean
+ evicted: string | null
+ rebound: string | null
+ /**
+ * An agent left with NOTHING by this bind, and therefore removed here.
+ *
+ * `claude --resume` in a second pane moves the engine session to the new
+ * agent. If the old one still has a live engine it is a real, separate
+ * agent and is left alone — it merely became unbound. But if its engine is
+ * already gone (the usual case: you quit it in order to resume it
+ * elsewhere) it now has no session AND no process, and the only thing it
+ * can still do is sit in the list as a second row for the same work that
+ * cannot be opened. The caller announces the removal.
+ */
+ orphaned: { agentId: string; sessionId: string } | null
+ } | null {
+
if (this.writeBlocked) return null
const transcriptPath = input.transcriptPath
const sessionId =
@@ -925,12 +964,20 @@ class Registry {
const evicted: string | null = rebound
// The same engine session cannot belong to two agents — `claude --resume X` in a second pane. The
// newest bind wins; the old process agent remains visible but becomes unbound.
+ let orphaned: { agentId: string; sessionId: string } | null = null
const stolenFrom = this.bySession(sessionId)
if (stolenFrom && stolenFrom.agentId !== agentId) {
console.log(`[registry] session ${sessionId.slice(0, 8)} moved from agent ${stolenFrom.agentId.slice(0, 8)} to ${agentId.slice(0, 8)}`)
+ const wasDormant = !stolenFrom.active
this.releaseBinding(stolenFrom)
+ if (wasDormant) {
+ orphaned = { agentId: stolenFrom.agentId, sessionId }
+ this.drop(stolenFrom)
+ this.terminalAvailableAgents.delete(stolenFrom.agentId)
+ }
}
+
// Command Code announces SessionStart BEFORE writing its transcript, and validTranscriptPath stats the
// file — so a real path is rejected at that moment and only arrives with the first Stop hook, AFTER the
// first turn. Nothing tailed the transcript for that turn, and a transcript-derived turn_started is the
@@ -984,7 +1031,7 @@ class Registry {
if (rebound) this.sessionIndex.delete(rebound)
this.index(entry)
this.save()
- return { entry, isNew, evicted, rebound }
+ return { entry, isNew, evicted, rebound, orphaned }
}
remove(sessionId: string): boolean {