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(cli): persist deferred Close after registry transactions (#1624)

0xken15e75e826ef622
diff --git a/cli/src/core/agents/closeCleanup.spec.ts b/cli/src/core/agents/closeCleanup.spec.ts
index 3f3afaa3e..8f961445e 100644
--- a/cli/src/core/agents/closeCleanup.spec.ts
+++ b/cli/src/core/agents/closeCleanup.spec.ts
@@ -50,6 +50,7 @@ function setup(physical = false) {
const registry = {
byAgent: (id: string) => id === session?.agentId ? session : undefined,
advertised: () => session ? [session] : [], list: () => session ? [session] : [],
+ afterTransaction: async <T>(action: () => T): Promise<T> => action(),
setClosePlan: vi.fn((_id: string, plan: RegisteredSession['closePlan'] | null) => { session!.closePlan = plan ?? undefined; return session }),
} as unknown as ClosingDeps['registry']
const stopped = vi.fn()
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index a29ea74be..9f2c3991f 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -303,6 +303,39 @@ it('persists a deferred close, survives a daemon restart and waits for sustained
await service.tick()
expect(deps.stop).toHaveBeenCalledOnce()
})
+
+it('durably records a deferred close that arrives during a registry discovery transaction', async () => {
+ let finish!: () => void
+ const hold = new Promise<void>(resolve => { finish = resolve })
+ const transaction = registry.transaction(async () => { await hold })
+ try {
+ const closing = service.request(request('after_task'))
+ await vi.waitFor(() => expect(deps.activity).toHaveBeenCalledOnce())
+ await new Promise(resolve => setImmediate(resolve))
+ expect(row.closePlan).toBeUndefined()
+ finish()
+ await transaction
+ expect(await closing).toEqual({ deferred: true })
+ expect(registry.byAgent(row.agentId)?.closePlan?.state).toBe('waiting')
+ registry.load()
+ expect(registry.byAgent(row.agentId)?.closePlan?.state).toBe('waiting')
+ } finally { finish(); await transaction }
+})
+
+it('does not defer a close if its conversation changes before the discovery transaction commits', async () => {
+ let finish!: () => void
+ const hold = new Promise<void>(resolve => { finish = resolve })
+ const transaction = registry.transaction(async () => { await hold })
+ try {
+ const closing = service.request(request('after_task'))
+ await vi.waitFor(() => expect(deps.activity).toHaveBeenCalledOnce())
+ row.sessionId = 'another-conversation'
+ finish()
+ await transaction
+ expect(await closing).toEqual({ error: 'AGENT_CHANGED' })
+ expect(row.closePlan).toBeUndefined()
+ } finally { finish(); await transaction }
+})
it('keeps questions and subsequent turns alive during a deferred close', async () => {
await service.request(request('after_task'))
await service.tick()
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index e7db2e250..90d94e178 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -103,7 +103,7 @@ function matches(s: RegisteredSession | undefined, request: AgentCloseRequest, a
}
export interface CloseAgentServiceDeps {
- registry: Pick<typeof liveRegistry, 'byAgent' | 'list' | 'setClosePlan'>
+ registry: Pick<typeof liveRegistry, 'byAgent' | 'list' | 'setClosePlan' | 'afterTransaction'>
activity(s: RegisteredSession): Promise<CloseActivity>
/** Cheap revocation after the final activity read, at each physical Stop boundary. */
idleCurrent?(s: RegisteredSession): boolean
@@ -277,9 +277,18 @@ export class CloseAgentService {
if (request.mode === 'inspect') return { activity }
if (request.mode === 'after_task') {
if (s.closePlan?.identity === target && s.closePlan.state === 'waiting') return { deferred: true }
- const updated = this.deps.registry.setClosePlan(s.agentId, { id: randomUUID(), identity: target, requestedAt: this.now(), state: 'waiting' })
+ let created = false
+ const updated = await this.deps.registry.afterTransaction(() => {
+ const latest = current()
+ if (!latest) return null
+ if (latest.closePlan?.identity === target && latest.closePlan.state === 'waiting') return latest
+ const saved = this.deps.registry.setClosePlan(latest.agentId, { id: randomUUID(), identity: target, requestedAt: this.now(), state: 'waiting' })
+ created = !!saved
+ return saved
+ })
+ if (!updated) return { error: 'AGENT_CHANGED' }
this.idleSince.delete(s.agentId)
- if (updated) this.deps.changed(updated)
+ if (created) this.deps.changed(updated)
this.schedule()
return { deferred: true }
}
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 8baf16ed8..1ad9ce005 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -1071,6 +1071,7 @@ class Registry {
private terminalAvailableAgents = new Set<string>()
private transactionDepth = 0
private savePending = false
+ private readonly afterTransactionCallbacks: Array<{ run: () => void; reject: (error: unknown) => void }> = []
/** Root corruption/unknown schemas are read-only until the operator restores valid bytes. */
private writeBlocked = false
/** Last committed row bytes, used for a three-way merge with daemon-down hook writes. */
@@ -2618,9 +2619,17 @@ class Registry {
if (!holding) return
holding = false
this.transactionDepth--
- if (this.transactionDepth === 0 && this.savePending) {
- this.savePending = false
- this.save()
+ if (this.transactionDepth === 0) {
+ try {
+ if (this.savePending) {
+ this.savePending = false
+ this.save()
+ }
+ } catch (error) {
+ for (const callback of this.afterTransactionCallbacks.splice(0)) callback.reject(error)
+ throw error
+ }
+ while (this.transactionDepth === 0 && this.afterTransactionCallbacks.length) this.afterTransactionCallbacks.shift()!.run()
}
}
const timer = options.holdSavesMs === undefined ? undefined : setTimeout(() => {
@@ -2638,6 +2647,18 @@ class Registry {
}
}
+ /** Run a durability-sensitive action only after the current discovery batch has committed. */
+ afterTransaction<T>(action: () => T): Promise<T> {
+ if (this.transactionDepth === 0) {
+ try { return Promise.resolve(action()) } catch (error) { return Promise.reject(error) }
+ }
+ return new Promise<T>((resolve, reject) => {
+ this.afterTransactionCallbacks.push({ run: () => {
+ try { resolve(action()) } catch (error) { reject(error) }
+ }, reject })
+ })
+ }
+
flush(options: { exiting?: boolean } = {}): void {
this.save(false, options.exiting === true)
this.saveNames()