Skip to content

The agent that grows with you

fix(desktop): never register a turn lease that nothing can release

John Paul Solivae1374093aa07
diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
index 7bab024916a..b712b897a98 100644
--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
@@ -17,6 +17,7 @@ const gatewayMocks = vi.hoisted(() => {
return {
connect: vi.fn(async (_wsUrl: string): Promise<void> => undefined),
+ eventHandlers: [] as ((event: unknown) => void)[],
instances
}
})
@@ -37,7 +38,11 @@ vi.mock('@/hermes', () => ({
await gatewayMocks.connect(wsUrl)
this.connectionState = 'open'
}
- onEvent = vi.fn(() => () => {})
+ onEvent = vi.fn((handler: (event: unknown) => void) => {
+ gatewayMocks.eventHandlers.push(handler)
+
+ return () => {}
+ })
onState = vi.fn(() => () => {})
constructor() {
gatewayMocks.instances.push(this as never)
@@ -67,6 +72,7 @@ const {
pruneSecondaryGateways,
reconnectSecondaryGateways,
retainGatewayForAgent,
+ retainGatewayForSessionTurn,
retireLocalProfileGateways,
setPrimaryGateway
} = await import('./gateway')
@@ -94,11 +100,76 @@ beforeEach(() => {
afterEach(() => {
closeSecondaryGateways()
gatewayMocks.instances.length = 0
+ gatewayMocks.eventHandlers.length = 0
vi.clearAllMocks()
vi.useRealTimers()
delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
})
+describe('retainGatewayForSessionTurn', () => {
+ it('lets the next turn take a real hold after a turn that rode the primary socket', async () => {
+ // A routed prompt holds one lease per (route, runtime session) until the turn settles, and for a
+ // streaming turn only a Secondary's terminal-event listener ends it. When the route is served by
+ // the primary socket there is no Secondary, so a lease registered then can never be released —
+ // and the map is keyed per session, so it silently suppresses every later hold on that session,
+ // including after the route is dialed as a real secondary. The socket is then free to be reaped
+ // mid-turn, which is the interruption this whole mechanism exists to prevent.
+ installDesktop({ getConnection: vi.fn() }) // no getConnectionFor: nothing to hold, no Secondary
+
+ // The streaming turn deliberately does NOT release: its release would arrive as a terminal event.
+ await retainGatewayForSessionTurn('homelab', 'writer', 'session-1')
+
+ installDesktop({
+ getConnection: vi.fn(),
+ getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
+ descriptorFor(connectionId, profile)
+ )
+ })
+ const dialedBefore = gatewayMocks.instances.length
+
+ await retainGatewayForSessionTurn('homelab', 'writer', 'session-1')
+
+ expect(gatewayMocks.instances.length).toBeGreaterThan(dialedBefore)
+ })
+
+ it('does not orphan a hold when two submits for one session race the dial', async () => {
+ // The duplicate-lease guard runs BEFORE the retain awaits, and the map is written after it, so
+ // two submits for the same (route, session) can both pass. Only the mapped release is ever
+ // invoked — releaseTerminalTurnLease does `g.turnLeases.get(key)?.()` — so the loser's hold is
+ // never released and the socket can never be reclaimed.
+ let openDial = () => {}
+
+ const dialed = new Promise<void>(resolve => {
+ openDial = resolve
+ })
+
+ gatewayMocks.connect.mockImplementationOnce(async () => dialed)
+ installDesktop({
+ getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
+ descriptorFor(connectionId, profile)
+ )
+ })
+
+ const both = Promise.all([
+ retainGatewayForSessionTurn('homelab', 'writer', 'session-2'),
+ retainGatewayForSessionTurn('homelab', 'writer', 'session-2')
+ ])
+
+ openDial()
+ await both
+
+ // The terminal event releases the one lease the map holds, exactly as the gateway's own
+ // listener does; a leaked second hold would keep activeRequests above zero.
+ for (const handler of gatewayMocks.eventHandlers) {
+ handler({ session_id: 'session-2', type: 'session.reclaimed' })
+ }
+
+ pruneSecondaryGateways(new Set())
+
+ expect(gatewayMocks.instances[0].close).toHaveBeenCalled()
+ })
+})
+
describe('a redial of the active route', () => {
it('is not cancelled by a prune that runs while it is dialing', async () => {
// Editing the connection you are viewing defers the redial until its lease drops, then
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 27a134f4559..81c49a688c1 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -1500,6 +1500,31 @@ export async function retainGatewayForSessionTurn(
}
const releaseRoute = await retainGatewayForAgent(connectionId, profile)
+
+ // Only a Secondary's own terminal-event listener releases this lease, so a route with no
+ // Secondary can never release one: retainGatewayForAgent and gatewayForProfile both hand back a
+ // no-op exactly when the route rides the primary socket (shared-remote collapse, shared-primary
+ // route, or a build without registry dialing), and none of those creates an entry. Storing the
+ // key there leaves the same phantom the primary-profile guard above avoids, and it would suppress
+ // the real hold once that route IS dialed as a secondary — which the shared-remote probe
+ // explicitly expects ("prefer the primary until a later probe can prove isolation"). Decide by
+ // outcome rather than re-probing every no-op case.
+ if (!g.secondaries.has(scope)) {
+ releaseRoute()
+
+ return () => undefined
+ }
+
+ // Re-check after the await: the guard above the retain ran before it, so a second submit for the
+ // same (route, session) can arrive while this one suspends and both pass it. Only the release
+ // stored in the map is ever invoked — releaseTerminalTurnLease does `g.turnLeases.get(key)?.()` —
+ // so the loser's hold would never be released and the socket could never be reclaimed.
+ if (g.turnLeases.has(key)) {
+ releaseRoute()
+
+ return () => undefined
+ }
+
let released = false
const release = () => {