Skip to content

The agent that grows with you

fix(desktop): cancelAndWait resolves only once the composed drain settles

kshitijk4poor9b199246e592
diff --git a/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts b/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts
index 76aa1d262d2..0e9549658ab 100644
--- a/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts
+++ b/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts
@@ -288,18 +288,21 @@ test('a second cancelAndWait on the same scope composes with the teardown still
})
await teardownStarted.promise
- await coordinator.cancelAndWait('scope')
+ const apply = coordinator.cancelAndWait('scope').then(() => events.push('apply-drained'))
const next = coordinator.start('scope', 'new', async () => {
events.push('new-start')
return 'new'
})
- await Promise.resolve()
- await Promise.resolve()
+ // A macrotask, not a microtask tick: nothing may run before the first teardown finishes.
+ await new Promise(resolve => setTimeout(resolve, 0))
assert.deepEqual(events, ['teardown-start'])
teardownGate.resolve()
- await poolStop
+ await Promise.all([poolStop, apply])
assert.equal(await next, 'new')
- assert.deepEqual(events, ['teardown-start', 'teardown-done', 'new-start'])
+ // Both the apply and the new bootstrap wake on the same drained barrier; only
+ // their position after teardown-done is the contract.
+ assert.deepEqual(events.slice(0, 2), ['teardown-start', 'teardown-done'])
+ assert.deepEqual(events.slice(2).sort(), ['apply-drained', 'new-start'])
})
diff --git a/apps/desktop/electron/ssh-bootstrap-coordinator.ts b/apps/desktop/electron/ssh-bootstrap-coordinator.ts
index 3e0715dd748..57586214938 100644
--- a/apps/desktop/electron/ssh-bootstrap-coordinator.ts
+++ b/apps/desktop/electron/ssh-bootstrap-coordinator.ts
@@ -104,7 +104,8 @@ function createBootstrapCoordinator() {
// start() must wait for every active teardown, and the map entry is
// cleared only once the composed barrier settles.
const prior = drains.get(scope)
- const barrier: Promise<void> = prior ? Promise.allSettled([prior, own]).then(() => undefined) : own
+ // Drain barriers never reject, so chaining is equivalent to allSettled.
+ const barrier = prior ? prior.then(() => own) : own
drains.set(scope, barrier)
void barrier.finally(() => {
@@ -133,6 +134,10 @@ function createBootstrapCoordinator() {
} finally {
release()
}
+
+ // "Cancel and wait" means the scope is drained: callers tear down SSH right
+ // after this returns, so wait for the composed barrier, not just our own.
+ await barrier
}
function cancelAll() {