The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop background secondary reopens from re-resuming every tile
Calvin Ngee94a6727f5d
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 9e328360047..7aa16eb1ede 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@ -218,6 +218,11 @@ export function useSessionTileDelegate({}}},+ dropRuntimeBindings: storedSessionIds => {+ for (const storedSessionId of storedSessionIds) {+ runtimeIdByStoredSessionIdRef.current.delete(storedSessionId)+ }+ },// Reconnect reconcile (#93059): retire an orphaned runtime's busy claim// through updateSessionState so the cache, focused view, busyRef and// tile mirrors settle together. A runtime this cache never held reportsdiff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex aa536213ae3..3f3bf79c259 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -31,6 +31,7 @@ const gatewayMocks = vi.hoisted(() => {const reconnectStateMocks = vi.hoisted(() => ({reconcileBusyStatesOnReconnect: vi.fn(),+ resetRouteOwnedTileRuntimeBindings: vi.fn(),resetTileRuntimeBindings: vi.fn()}))@@ -352,11 +353,14 @@ describe('secondary reconnect runtime scope', () => {const reopening = openGatewayForAgent('homelab', 'writer')await vi.waitFor(() => expect(gatewayMocks.connect).toHaveBeenCalledTimes(2))- expect(reconnectStateMocks.resetTileRuntimeBindings).toHaveBeenCalledWith({+ // Not the window's ambient gateway: only tiles owned by this route can hold+ // its runtime ids, so the reset is route-owned rather than window-wide.+ expect(reconnectStateMocks.resetRouteOwnedTileRuntimeBindings).toHaveBeenCalledWith({connectionId: 'homelab',profile: 'writer'})- expect(reconnectStateMocks.resetTileRuntimeBindings.mock.invocationCallOrder[0]).toBeLessThan(+ expect(reconnectStateMocks.resetTileRuntimeBindings).not.toHaveBeenCalled()+ expect(reconnectStateMocks.resetRouteOwnedTileRuntimeBindings.mock.invocationCallOrder[0]).toBeLessThan(gatewayMocks.connect.mock.invocationCallOrder[1])@@ -364,6 +368,30 @@ describe('secondary reconnect runtime scope', () => {await reopening})+ it('does not re-resume unrelated tiles when a background request lease reopens its route', async () => {+ // The Bot relay drains every registered connection on a 30s tick through+ // requestGatewayForAgent. A local route is exempt from relay retention, so+ // each tick dials a fresh socket and disposes it after the RPC. Treating+ // every such reopen as a window-wide backend restart dropped every open+ // tile's runtime binding, remounting its composer (caret reset, layout+ // shift, model pick reverted) every 30 seconds.+ installDesktop({+ getConnectionFor: vi.fn(async ({ connectionId, profile }) => descriptorFor(connectionId, profile))+ })++ await requestGatewayForAgent('local', 'writer', 'bot_relay.outbox.drain')+ expect(gatewayMocks.instances[0]?.close).toHaveBeenCalledOnce()++ await requestGatewayForAgent('local', 'writer', 'bot_relay.outbox.drain')++ expect(gatewayMocks.connect).toHaveBeenCalledTimes(2)+ expect(reconnectStateMocks.resetTileRuntimeBindings).not.toHaveBeenCalled()+ expect(reconnectStateMocks.resetRouteOwnedTileRuntimeBindings).toHaveBeenCalledWith({+ connectionId: 'local',+ profile: 'writer'+ })+ })+it('rebinds only Bot runtimes owned by the reconnected profile route', async () => {installDesktop({getConnectionFor: vi.fn(async ({ connectionId, profile }) => descriptorFor(connectionId, profile))diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 3bc17ab82e2..0e54703c902 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -696,12 +696,21 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bif (reopening) {try {- const { reconcileBusyStatesOnReconnect, resetTileRuntimeBindings } = await import('@/store/session-states')+ const { reconcileBusyStatesOnReconnect, resetRouteOwnedTileRuntimeBindings, resetTileRuntimeBindings } =+ await import('@/store/session-states')++ const scope = { connectionId: entry.connectionId || 'local', profile: entry.profile }++ // Only the window's ambient gateway carries un-owned tiles and the main+ // thread. A background route (e.g. a relay request lease that disposed+ // its socket after the last tick) can only have minted runtimes for+ // tiles that name it as their owner route.+ if (g.activeKey === entry.scope) {+ resetTileRuntimeBindings(scope)+ } else {+ resetRouteOwnedTileRuntimeBindings(scope)+ }- resetTileRuntimeBindings({- connectionId: entry.connectionId || 'local',- profile: entry.profile- })reconcileBusyAfterOpen = () => reconcileBusyStatesOnReconnect(entry.scope)} catch {// Best effort for partial test/HMR graphs. Production always loads thediff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.tsindex 1bb5e4a0e73..731862473dc 100644--- a/apps/desktop/src/store/session-states.test.ts+++ b/apps/desktop/src/store/session-states.test.ts@@ -43,6 +43,7 @@ import {recordSessionEventScope,releaseSessionTranscript,requestForOwnedSession,+ resetRouteOwnedTileRuntimeBindings,resetTileRuntimeBindings,selectionHomesToWorkspace,type SessionTileDelegate,@@ -261,6 +262,58 @@ describe('resetTileRuntimeBindings', () => {})})+describe('resetRouteOwnedTileRuntimeBindings', () => {+ afterEach(() => {+ $sessionTiles.set([])+ })++ it('drops only tiles owned by the reopened route and leaves ambient tiles bound', () => {+ const invalidateRuntimeBindings = vi.fn()+ const dropRuntimeBindings = vi.fn()+ setSessionTileDelegate({ dropRuntimeBindings, invalidateRuntimeBindings } as unknown as SessionTileDelegate)+ $sessionTiles.set([+ {+ ownerRoute: { connectionId: 'local', mode: 'local', profile: 'writer', targetProfile: 'writer' },+ runtimeId: 'runtime-writer-bot',+ storedSessionId: 'stored-writer-bot',+ workspaceMode: 'bots'+ },+ {+ ownerRoute: { connectionId: 'local', mode: 'local', profile: 'coder', targetProfile: 'coder' },+ runtimeId: 'runtime-coder-bot',+ storedSessionId: 'stored-coder-bot',+ workspaceMode: 'bots'+ },+ { runtimeId: 'runtime-ambient', storedSessionId: 'stored-ambient' }+ ])++ resetRouteOwnedTileRuntimeBindings({ connectionId: 'local', profile: 'writer' })++ const [writerBot, coderBot, ambient] = $sessionTiles.get()++ expect(writerBot).toMatchObject({ storedSessionId: 'stored-writer-bot' })+ expect(writerBot).not.toHaveProperty('runtimeId')+ expect(coderBot).toMatchObject({ runtimeId: 'runtime-coder-bot' })+ expect(ambient).toMatchObject({ runtimeId: 'runtime-ambient' })+ expect(dropRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-writer-bot']))+ expect(invalidateRuntimeBindings).not.toHaveBeenCalled()+ })++ it('is a no-op when no open tile belongs to the reopened route', () => {+ const invalidateRuntimeBindings = vi.fn()+ const dropRuntimeBindings = vi.fn()+ setSessionTileDelegate({ dropRuntimeBindings, invalidateRuntimeBindings } as unknown as SessionTileDelegate)+ const tiles = [{ runtimeId: 'runtime-ambient', storedSessionId: 'stored-ambient' }]+ $sessionTiles.set(tiles)++ resetRouteOwnedTileRuntimeBindings({ connectionId: 'local', profile: 'writer' })++ expect($sessionTiles.get()).toBe(tiles)+ expect(dropRuntimeBindings).not.toHaveBeenCalled()+ expect(invalidateRuntimeBindings).not.toHaveBeenCalled()+ })+})+describe('SessionTile workspace scope', () => {afterEach(() => {$activeGatewayProfile.set('default')diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex ad815c6b809..54df09155ce 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -1527,6 +1527,43 @@ export function resetTileRuntimeBindings(}}+/** Reset for a pooled secondary route that reopened while it was NOT the+ * window's ambient gateway. Only tiles whose exact owner route names that+ * runtime can hold ids it minted; un-owned tiles and the main thread ride the+ * ambient socket, whose own reconnect path runs `resetTileRuntimeBindings`.+ * Background request leases (the Bot relay drain) reopen such a route every+ * tick, and a window-wide reset there re-resumed every open tile each time —+ * remounting its composer (caret reset, layout shift, model pick reverted). */+export function resetRouteOwnedTileRuntimeBindings(scope: RuntimeReconnectScope) {+ const connectionId = scope.connectionId.trim()+ const profile = scope.profile?.trim() || null+ const tiles = $sessionTiles.get()++ const ownedStoredIds = new Set(+ tiles+ .filter(tile => {+ const route = tile.ownerRoute++ return (+ Boolean(connectionId) &&+ route?.connectionId === connectionId &&+ (!profile || (route.targetProfile || route.profile) === profile)+ )+ })+ .map(tile => tile.storedSessionId)+ )++ if (ownedStoredIds.size === 0) {+ return+ }++ sessionTileDelegate()?.dropRuntimeBindings?.(ownedStoredIds)++ if (tiles.some(tile => tile.runtimeId && ownedStoredIds.has(tile.storedSessionId))) {+ $sessionTiles.set(tiles.map(tile => (ownedStoredIds.has(tile.storedSessionId) ? toStored(tile) : tile)))+ }+}+/** Unbind ONE reclaimed runtime from whichever tile holds it — the targeted* sibling of resetTileRuntimeBindings. The reconnect-time reset can't cover a* backend reclaim: the WS re-dials immediately, but the orphan reaper fires a@@ -1569,6 +1606,11 @@ export interface SessionTileDelegate {* warm path re-binds tiles to dead runtime ids (the sleep/wake "empty* right pane" bug). Bindings re-record from live post-reconnect events. */invalidateRuntimeBindings?(preserveStoredSessionIds?: ReadonlySet<string>): void+ /** Drop ONLY these stored→runtime bindings from the wiring cache — the+ * route-scoped twin of invalidateRuntimeBindings for a reopened secondary+ * (`resetRouteOwnedTileRuntimeBindings`). Bindings for every other stored+ * session, including the main thread, stay warm. */+ dropRuntimeBindings?(storedSessionIds: ReadonlySet<string>): void/** Bind a live runtime id for a stored session (resume without touching* the main view). Returns the runtime id, or throws.* `refreshTranscript` forces a REST merge even when a warm cached