The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retain routed socket through turn completion
Shaq Wu120430be4758
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 2478d64a23f..7ffd3d7a60d 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -110,6 +110,10 @@ interface GatewayRegistryState {secondaries: Map<string, Secondary>/** Scopes that opened in this renderer generation, even if later pruned. */openedSecondaryScopes?: Set<string>+ /** Routed prompt sockets held until their terminal turn event arrives. */+ turnLeases: Map<string, () => void>+ /** Debounced releases so an immediate chained turn can reuse its lease. */+ turnLeaseReleaseTimers: Map<string, ReturnType<typeof setTimeout>>$gateway: ReturnType<typeof atom<HermesGateway | null>>$activeProfile: ReturnType<typeof atom<string>>}@@ -126,6 +130,8 @@ function createRegistryState(): GatewayRegistryState {activationEpoch: 0,secondaries: new Map<string, Secondary>(),openedSecondaryScopes: new Set<string>(),+ turnLeases: new Map<string, () => void>(),+ turnLeaseReleaseTimers: new Map<string, ReturnType<typeof setTimeout>>(),// The active gateway instance, exposed for inline message-stream// components (inline ClarifyTool, model overlays) that call gateway// methods without the instance threaded down through props.@@ -152,6 +158,10 @@ function gatewayState(): GatewayRegistryState {const store = globalThis as unknown as { [STATE_KEY]?: GatewayRegistryState }store[STATE_KEY] ??= createRegistryState()+ // Existing dev-HMR containers predate whole-turn leases.+ store[STATE_KEY].turnLeases ??= new Map()+ store[STATE_KEY].turnLeaseReleaseTimers ??= new Map()+return store[STATE_KEY]}@@ -558,17 +568,25 @@ function createSecondary(profile: string, connectionId: null | string = null): S// Events keep carrying the bare profile — session routing is profile-keyed// everywhere. connectionId rides along for surfaces that need the source.- entry.offEvent = gateway.onEvent(event =>+ entry.offEvent = gateway.onEvent(event => {g.config?.onEvent({ ...event, profile, ...(connectionId ? { connectionId } : {}) })- )+ releaseTerminalTurnLease(entry.scope, event)+ })entry.offState = gateway.onState(state => {reportGatewayState(scope, state)if (state === 'open') {entry.reconnectAttempt = 0clearTimer(entry)- } else if ((state === 'closed' || state === 'error') && entry.wantOpen) {- scheduleReconnect(entry)+ } else if (state === 'closed' || state === 'error') {+ // A dead socket cannot emit the terminal event that normally releases+ // its turn lease. Drop the orphaned lease before deciding whether this+ // route is still retained/active enough to reconnect.+ releaseTurnLeasesForScope(scope)++ if (entry.wantOpen) {+ scheduleReconnect(entry)+ }}})@@ -915,6 +933,124 @@ export async function retainGatewayForAgent(connectionId: null | string, profilereturn release}+const turnLeaseKey = (scope: string, sessionId: string): string => `${scope}\u0000${sessionId}`+const TURN_LEASE_SETTLE_DELAY_MS = 500++function cancelTurnLeaseRelease(key: string): void {+ const timer = g.turnLeaseReleaseTimers.get(key)++ if (timer !== undefined) {+ clearTimeout(timer)+ g.turnLeaseReleaseTimers.delete(key)+ }+}++function releaseTurnLeasesForScope(scope: string): void {+ const prefix = `${scope}\u0000`++ for (const [key, timer] of [...g.turnLeaseReleaseTimers]) {+ if (key.startsWith(prefix)) {+ clearTimeout(timer)+ g.turnLeaseReleaseTimers.delete(key)+ }+ }++ for (const [key, release] of [...g.turnLeases]) {+ if (key.startsWith(prefix)) {+ release()+ }+ }+}++/**+ * Keep a routed Desktop prompt's socket alive after prompt.submit ACKs.+ *+ * Routed requests normally own a per-request lease. prompt.submit ACKs as soon+ * as the background turn starts, so releasing that lease at RPC completion+ * detaches the runtime session while the model is still working; the gateway's+ * 20-second orphan guard then interrupts it as `client_gone`. Hold one lease per+ * (route, runtime session) until message.complete/session.info settles the turn.+ */+export async function retainGatewayForSessionTurn(+ connectionId: null | string,+ profile: string,+ sessionId: string+): Promise<() => void> {+ const scope = registryBackendScopeKey(connectionId, normKey(profile))+ const key = turnLeaseKey(scope, sessionId)++ cancelTurnLeaseRelease(key)++ // A busy-session redirect/queue can submit again while the original turn is+ // still retained. The existing lease owns that turn; the extra submit must+ // not replace or release it. The no-op means "another caller owns the+ // shared lease", not "this caller acquired a separately releasable lease".+ if (g.turnLeases.has(key)) {+ return () => undefined+ }++ const releaseRoute = await retainGatewayForAgent(connectionId, profile)+ let released = false++ const release = () => {+ if (released) {+ return+ }++ released = true++ if (g.turnLeases.get(key) === release) {+ g.turnLeases.delete(key)+ }++ cancelTurnLeaseRelease(key)+ releaseRoute()+ }++ g.turnLeases.set(key, release)++ return release+}++function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {+ const sessionId = String(event.session_id || '').trim()++ if (!sessionId) {+ return+ }++ const key = turnLeaseKey(scope, sessionId)++ if (event.type === 'message.start') {+ // The gateway emits settled session.info before immediately chaining a+ // queued/goal follow-up. Keep the same route alive for that next turn.+ cancelTurnLeaseRelease(key)++ return+ }++ if (event.type === 'session.reclaimed') {+ g.turnLeases.get(key)?.()++ return+ }++ const payload = event.payload as Record<string, unknown> | undefined++ if (event.type === 'session.info' && payload?.running === false && !g.turnLeaseReleaseTimers.has(key)) {+ // session.info(false) is the authoritative settled edge, but auto-followup+ // emits message.start immediately after it. A short debounce lets that+ // frame cancel release while still reclaiming ordinary completed turns.+ g.turnLeaseReleaseTimers.set(+ key,+ setTimeout(() => {+ g.turnLeaseReleaseTimers.delete(key)+ g.turnLeases.get(key)?.()+ }, TURN_LEASE_SETTLE_DELAY_MS)+ )+ }+}+// Open `profile`'s socket WITHOUT making it active — the hover-intent pre-warm// (store/profile). Runs the same spawn + connect chain as a real switch, so by// click time ensureGatewayForProfile finds an open socket and just activates@@ -1228,7 +1364,6 @@ export function pruneSecondaryGateways(keep: Set<string>): void {key === g.activeKey ||keep.has(key) ||(!entry.connectionId && keep.has(entry.profile)) ||- entry.activeRequests > 0 ||// Bot-relay retention (#93594): the relay pins its remote routes for// its whole active lifetime; the live-work pruner must not undo that// pin between drain ticks or the socket churn returns.@@ -1243,6 +1378,19 @@ export function pruneSecondaryGateways(keep: Set<string>): void {continue}+ // The route is no longer live work. Release turn leases first so their+ // counted request holds cannot outlive a disposed route or leave a stale+ // release closure attached to a later same-key socket.+ releaseTurnLeasesForScope(key)++ if (g.secondaries.get(key) !== entry) {+ continue+ }++ if (entry.activeRequests > 0) {+ continue+ }+disposeSecondary(entry)g.secondaries.delete(key)}@@ -1251,6 +1399,18 @@ export function pruneSecondaryGateways(keep: Set<string>): void {}export function closeSecondaryGateways(): void {+ for (const timer of g.turnLeaseReleaseTimers.values()) {+ clearTimeout(timer)+ }++ g.turnLeaseReleaseTimers.clear()++ for (const release of [...g.turnLeases.values()]) {+ release()+ }++ g.turnLeases.clear()+for (const entry of g.secondaries.values()) {disposeSecondary(entry)}diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex b831668267e..8ef30502990 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -13,12 +13,18 @@ const secondaryGateways: Array<{close: ReturnType<typeof vi.fn>connect: ReturnType<typeof vi.fn>connectionState: string+ emit: (event: { payload?: Record<string, unknown>; session_id?: string; type: string }) => void+ emitState: (state: string) => voidrequest: ReturnType<typeof vi.fn>}> = []+let promptAckStatus: null | string = null+vi.mock('@/hermes', () => ({HermesGateway: class {connectionState = 'closed'+ eventHandler: ((event: { payload?: Record<string, unknown>; session_id?: string; type: string }) => void) | null = null+ stateHandler: ((state: string) => void) | null = nullconnect = vi.fn(async () => {this.connectionState = 'open'})@@ -27,11 +33,25 @@ vi.mock('@/hermes', () => ({throw new Error('gateway is not connected')}- return { method, params }+ return method === 'prompt.submit' && promptAckStatus ? { status: promptAckStatus } : { method, params }})close = vi.fn()- onEvent = vi.fn(() => () => {})- onState = vi.fn(() => () => {})+ emit = (event: { payload?: Record<string, unknown>; session_id?: string; type: string }) => this.eventHandler?.(event)+ emitState = (state: string) => this.stateHandler?.(state)+ onEvent = vi.fn((handler: (event: { payload?: Record<string, unknown>; session_id?: string; type: string }) => void) => {+ this.eventHandler = handler++ return () => {+ this.eventHandler = null+ }+ })+ onState = vi.fn((handler: (state: string) => void) => {+ this.stateHandler = handler++ return () => {+ this.stateHandler = null+ }+ })constructor() {secondaryGateways.push(this)@@ -78,6 +98,7 @@ function makePrimary() {beforeEach(() => {secondaryGateways.length = 0+ promptAckStatus = nullconfigureGatewayRegistry({ onEvent: vi.fn() })closeSecondaryGateways()})@@ -311,6 +332,121 @@ describe('requestForSessionProfile', () => {)})+ it('keeps a routed prompt socket alive until the turn terminal event (#client-gone)', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ const ambient = vi.fn(async () => ({ ambient: true }))++ await requestForSessionProfile(+ { connectionId: 'local', profile: 'default' },+ ambient as never,+ 'prompt.submit',+ { session_id: 'rt-bot-chat', text: 'research this' }+ )++ // prompt.submit ACKs immediately while the model keeps running. Releasing+ // the request-scoped socket here detaches the runtime session; the backend+ // then interrupts it on the 20-second client-gone timer.+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ vi.useFakeTimers()++ secondaryGateways[0].emit({+ payload: { running: false },+ session_id: 'rt-bot-chat',+ type: 'session.info'+ })++ // A chained goal/queue turn starts immediately after the settled frame;+ // it must cancel the pending release and inherit the live socket.+ secondaryGateways[0].emit({ session_id: 'rt-bot-chat', type: 'message.start' })+ await vi.advanceTimersByTimeAsync(500)+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ secondaryGateways[0].emit({+ payload: { running: false },+ session_id: 'rt-bot-chat',+ type: 'session.info'+ })+ await vi.advanceTimersByTimeAsync(500)++ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ vi.useRealTimers()+ })++ it.each(['queued', 'redirected', 'future-nonterminal'])('retains a routed socket for non-terminal ACK status %s', async status => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ const ambient = vi.fn(async () => ({ ambient: true }))++ promptAckStatus = status++ await requestForSessionProfile(+ 'loki',+ ambient as never,+ 'prompt.submit',+ { session_id: `rt-${status}`, text: 'continue' }+ )++ expect(secondaryGateways[0].close).not.toHaveBeenCalled()+ })++ it.each(['complete', 'completed', 'error'])('releases a routed socket for terminal ACK status %s', async status => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ const ambient = vi.fn(async () => ({ ambient: true }))++ promptAckStatus = status++ await requestForSessionProfile(+ 'loki',+ ambient as never,+ 'prompt.submit',+ { session_id: `rt-${status}`, text: 'finish' }+ )++ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ })++ it('releases turn leases when their route is pruned and creates a fresh route next time', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ const ambient = vi.fn(async () => ({ ambient: true }))+ const route = { connectionId: 'source-a', profile: 'worker' }++ await requestForSessionProfile(route, ambient as never, 'prompt.submit', {+ session_id: 'rt-pruned',+ text: 'work'+ })+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ pruneSecondaryGateways(new Set())+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()++ await requestForSessionProfile(route, ambient as never, 'session.resume', { session_id: 'rt-pruned' })+ expect(secondaryGateways).toHaveLength(2)+ })++ it('releases a retained turn when its owning socket closes without a terminal event', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ const ambient = vi.fn(async () => ({ ambient: true }))++ await requestForSessionProfile('loki', ambient as never, 'prompt.submit', {+ session_id: 'rt-socket-closed',+ text: 'work'+ })+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ secondaryGateways[0].emitState('closed')+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ })+it('routes an owner that IS the primary profile onto the primary socket (no active comparison)', async () => {const primary = makePrimary()setPrimaryGateway(primary as never, 'loki')diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex b8c6cabab63..4775975fe7f 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -1,4 +1,4 @@-import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'+import { requestGatewayForAgent, requestGatewayForProfile, retainGatewayForSessionTurn } from '@/store/gateway'export interface SessionProfileRoute {connectionId: string@@ -40,6 +40,56 @@ function routeParams(route: SessionProfileRoute, params: Record<string, unknown>return { ...params, profile: route.targetProfile }}+function promptSessionId(method: string, params: Record<string, unknown>): string {+ return method === 'prompt.submit' && typeof params.session_id === 'string' ? params.session_id.trim() : ''+}++const TERMINAL_TURN_ACK_STATUSES = new Set(['complete', 'completed', 'error'])++function turnKeepsRunning(result: unknown): boolean {+ if (!result || typeof result !== 'object' || !('status' in result)) {+ // Older gateways may ACK without the newer structured status. Retaining+ // until the terminal event is safer than recreating the client-gone cut.+ return true+ }++ const status = (result as { status?: unknown }).status++ // Queued, redirected and future status values are non-terminal by default.+ // Releasing only an explicit terminal ACK avoids recreating client_gone+ // when a gateway accepts a turn without calling it "streaming".+ return typeof status !== 'string' || !TERMINAL_TURN_ACK_STATUSES.has(status)+}++async function withRoutedTurnLease<T>(+ connectionId: null | string,+ profile: string,+ method: string,+ params: Record<string, unknown>,+ request: () => Promise<T>+): Promise<T> {+ const sessionId = promptSessionId(method, params)++ if (!sessionId) {+ return request()+ }++ const release = await retainGatewayForSessionTurn(connectionId, profile, sessionId)++ try {+ const result = await request()++ if (!turnKeepsRunning(result)) {+ release()+ }++ return result+ } catch (error) {+ release()+ throw error+ }+}+/*** True when a session-scoped RPC must be pinned to `ownerProfile`'s own socket.*@@ -88,9 +138,13 @@ export function requestForSessionProfile<T>(const routedParams = routeParams(ownerProfile, params)- return timeoutMs === undefined && signal === undefined- ? requestGatewayForAgent<T>(connectionId, normKey(ownerProfile.profile), method, routedParams)- : requestGatewayForAgent<T>(connectionId, normKey(ownerProfile.profile), method, routedParams, timeoutMs, signal)+ const profile = normKey(ownerProfile.profile)++ return withRoutedTurnLease(connectionId, profile, method, routedParams, () =>+ timeoutMs === undefined && signal === undefined+ ? requestGatewayForAgent<T>(connectionId, profile, method, routedParams)+ : requestGatewayForAgent<T>(connectionId, profile, method, routedParams, timeoutMs, signal)+ )}if (!sessionRpcNeedsProfileRoute(ownerProfile)) {@@ -105,5 +159,9 @@ export function requestForSessionProfile<T>(: ambientRequest<T>(method, params, timeoutMs, signal)}- return requestGatewayForProfile<T>(normKey(ownerProfile), method, params, timeoutMs, signal)+ const profile = normKey(ownerProfile)++ return withRoutedTurnLease(null, profile, method, params, () =>+ requestGatewayForProfile<T>(profile, method, params, timeoutMs, signal)+ )}