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): stop a stale attach entry from spinning the daemon at 100% CPU (#586)

lingrdb0dc5a48bb85
diff --git a/cli/src/lib/attachTracker.spec.ts b/cli/src/lib/attachTracker.spec.ts
index 41d4ddc16..2eb23fb1d 100644
--- a/cli/src/lib/attachTracker.spec.ts
+++ b/cli/src/lib/attachTracker.spec.ts
@@ -47,6 +47,21 @@ describe('AttachTracker', () => {
expect(await b).toBe(true)
})
+ it('forgets an attach even when the session loses its id while it runs', async () => {
+ // The registry hands out one live object and unbinding blanks its sessionId mid-attach. The entry
+ // must still be removed, or the next reset awaits an already-settled promise forever and starves
+ // the event loop.
+ const tracker = new AttachTracker<Engine>()
+ const live = subject('s1')
+ const first = deferred<boolean>()
+ const run = tracker.attach(live, false, () => first.promise)
+ live.sessionId = ''
+ first.resolve(true)
+ await run
+ expect(tracker.attaching()).toEqual([])
+ expect(await tracker.attach(subject('s1'), true, async () => true)).toBe(true)
+ })
+
it('a start that throws synchronously frees the slot', async () => {
const tracker = new AttachTracker<Engine>()
await expect(tracker.attach(subject('s1'), false, () => { throw new Error('sync') })).rejects.toThrow('sync')
diff --git a/cli/src/lib/attachTracker.ts b/cli/src/lib/attachTracker.ts
index 791eb341a..cfbe50d80 100644
--- a/cli/src/lib/attachTracker.ts
+++ b/cli/src/lib/attachTracker.ts
@@ -64,15 +64,18 @@ export class AttachTracker<E> {
*/
async attach(session: AttachSubject<E>, reset: boolean, start: () => Promise<boolean>): Promise<boolean> {
// A loop, not an if: two resets waiting on the same attach would otherwise both start at once.
- for (let pending = this.inFlight.get(session.sessionId); pending; pending = this.inFlight.get(session.sessionId)) {
+ // The key is read once: `session` is the registry's live object and unbinding blanks its sessionId
+ // mid-attach, so reading it again later would miss the entry and leave it behind for good.
+ const key = session.sessionId
+ for (let pending = this.inFlight.get(key); pending; pending = this.inFlight.get(key)) {
if (!reset) return pending.run
await pending.run.catch(() => false)
}
const entry = { run: Promise.resolve(false), subject: session, since: null as number | null }
entry.run = this.runWhenFree(entry, start).finally(() => {
- if (this.inFlight.get(session.sessionId) === entry) this.inFlight.delete(session.sessionId)
+ if (this.inFlight.get(key) === entry) this.inFlight.delete(key)
})
- this.inFlight.set(session.sessionId, entry)
+ this.inFlight.set(key, entry)
return entry.run
}