The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): roster route hints never outlive a primary re-home
Teknium337b95c993cb
diff --git a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.tsindex 4b0e0f41504..848dc7317c8 100644--- a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts@@ -53,6 +53,7 @@ vi.mock('@/store/session-request-router', async importOriginal => ({const { $gateway } = await import('@/store/gateway')const { $gatewayState } = await import('@/store/session')+const { $primaryGatewayRoute } = await import('@/store/gateway-primary-route')const ownerOf = (call: unknown[]) => JSON.stringify(call[0] ?? 'ambient')const callsFor = (owner: unknown) => h.request.mock.calls.filter(c => ownerOf(c) === JSON.stringify(owner)).length@@ -246,4 +247,19 @@ describe('useLiveWorkRoster', () => {await act(async () => finishOld({ sessions: [] }))expect($liveWorkRoster.get()['::y']).toBeDefined()})++ it('starts over when the primary re-homes to another connection while the socket state stays open', async () => {+ act(() => $primaryGatewayRoute.set({ connectionId: 'old-host', mode: 'remote' }))+ h.request.mockRejectedValueOnce(Object.assign(new Error('method not found'), { code: -32601 }))+ renderHook(() => useLiveWorkRoster())+ await tick(0)+ expect(callsFor('ambient')).toBe(1)++ h.request.mockResolvedValue({ sessions: [{ session_id: 'new-host-row', subagents: 1 }] })+ act(() => $primaryGatewayRoute.set({ connectionId: 'new-host', mode: 'remote' }))+ await tick(0)++ expect(callsFor('ambient')).toBe(2)+ expect($liveWorkRoster.get()['primary:default']?.sessions['new-host-row']?.subagents).toBe(1)+ })})diff --git a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.tsindex 2f8ac4bee64..2d7dc50745c 100644--- a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts+++ b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts@@ -3,6 +3,7 @@ import { useEffect } from 'react'import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { $gateway, activeGatewayProfileKey, gatewayRouteState, isActivePrimary } from '@/store/gateway'+import { $primaryGatewayRoute } from '@/store/gateway-primary-route'import { $liveWorkRoster, rosterSourceHasWork, setLiveWorkRosterSource } from '@/store/live-work-roster'import { $gatewayState, ownerLookupSessionRows } from '@/store/session'import { ambientRequestFor } from '@/store/session-gone-latch'@@ -73,12 +74,17 @@ function rosterSources(): Map<string, RosterSource> {* included) and keeps retrying, so a recovered socket comes back on its own. */export function useLiveWorkRoster() {const gatewayState = useStore($gatewayState)+ // Route keys (`primary:<profile>`, `ambient`) name a socket, not a backend:+ // a soft re-home of the primary must start over, even while the foreground+ // socket (a secondary) stays open, or old buckets and stops outlive it.+ const { connectionId: primaryConnection, mode: primaryMode } = useStore($primaryGatewayRoute)useEffect(() => {- if (gatewayState !== 'open') {- // Counts from a dropped socket are unverified; the reconnect re-reads them.- $liveWorkRoster.set({})+ // Counts from a dropped socket or a previous primary are unverified; the+ // (re)connect re-reads them.+ $liveWorkRoster.set({})+ if (gatewayState !== 'open') {return}@@ -176,5 +182,5 @@ export function useLiveWorkRoster() {window.clearInterval(timer)window.removeEventListener('focus', hydrate)}- }, [gatewayState])+ }, [gatewayState, primaryConnection, primaryMode])}diff --git a/apps/desktop/src/store/gateway-primary-rider.test.ts b/apps/desktop/src/store/gateway-primary-rider.test.tsnew file mode 100644index 00000000000..8ab286fe479--- /dev/null+++ b/apps/desktop/src/store/gateway-primary-rider.test.ts@@ -0,0 +1,70 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// gatewayRouteState keys a profile that rode the shared primary socket as+// `primary:<profile>`. That hint belongs to the primary socket it was learned+// on: after a soft re-home (connection apply) the same profile may be served by+// a different backend, and keying it under the new primary would merge two+// owners into one roster source and skip a backend.++vi.mock('@/hermes', () => ({+ setApiRequestConnection: vi.fn(),+ HermesGateway: class {+ connectionState = 'closed'+ connect = vi.fn()+ close = vi.fn()+ onEvent = vi.fn(() => () => {})+ onState = vi.fn(() => () => {})+ }+}))+vi.mock('@/store/session', () => ({ setConnection: vi.fn(), setGatewayState: vi.fn() }))+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))++const {+ closeSecondaryGateways,+ configureGatewayRegistry,+ gatewayRouteState,+ requestGatewayForProfile,+ setPrimaryGateway,+ setPrimaryGatewayConnectionId+} = await import('./gateway')++const shared = () => ({+ getConnection: vi.fn(async () => ({ port: 4242, profile: 'venture', sharedPrimary: true, token: 't' }))+})++const primary = () => ({ connectionState: 'open', request: vi.fn(async () => ({})) })++beforeEach(() => {+ configureGatewayRegistry({ onEvent: vi.fn(), primaryProfile: 'default' } as never)+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = shared()+})++afterEach(() => {+ closeSecondaryGateways()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++describe('primary rider hint', () => {+ it('keys a shared profile on the primary it was learned on, and drops it when the primary socket changes', async () => {+ setPrimaryGateway(primary() as never, 'default')+ await requestGatewayForProfile('venture', 'subagent.roster')++ expect(gatewayRouteState(null, 'venture').key).toBe('primary:venture')++ setPrimaryGateway(primary() as never, 'default')++ expect(gatewayRouteState(null, 'venture').key).toBe('venture')+ })++ it('drops the hint when the same primary socket is re-homed to another connection', async () => {+ setPrimaryGateway(primary() as never, 'default')+ setPrimaryGatewayConnectionId('conn-a', 'remote')+ await requestGatewayForProfile('venture', 'subagent.roster')++ expect(gatewayRouteState(null, 'venture').key).toBe('primary:venture')++ setPrimaryGatewayConnectionId('conn-b', 'remote')++ expect(gatewayRouteState(null, 'venture').key).toBe('venture')+ })+})diff --git a/apps/desktop/src/store/gateway-shared-route.ts b/apps/desktop/src/store/gateway-shared-route.tsindex f27535612af..cf3a014cb21 100644--- a/apps/desktop/src/store/gateway-shared-route.ts+++ b/apps/desktop/src/store/gateway-shared-route.ts@@ -35,12 +35,20 @@ export async function sharedPrimaryRoute(profile: string): Promise<boolean> {// Scopes whose last route resolution rode the primary socket (shared primary /// shared remote). A HINT for passive readers only (gateway.ts gatewayRouteState);-// requests still resolve the route per call.-const primaryRiders = new Set<string>()+// requests still resolve the route per call. Each hint is bound to the primary+// socket + connection it was learned on: after a soft re-home the same profile+// may live on another backend, so a hint from the old primary must not key it+// as `primary:<profile>` under the new one.+export interface PrimaryIdentity {+ connectionId: null | string+ gateway: unknown+}++const primaryRiders = new Map<string, PrimaryIdentity>()-export function notePrimaryRider(scope: string, rides: boolean): boolean {+export function notePrimaryRider(owner: PrimaryIdentity, scope: string, rides: boolean): boolean {if (rides) {- primaryRiders.add(scope)+ primaryRiders.set(scope, owner)} else {primaryRiders.delete(scope)}@@ -48,4 +56,8 @@ export function notePrimaryRider(scope: string, rides: boolean): boolean {return rides}-export const isPrimaryRider = (scope: string): boolean => primaryRiders.has(scope)+export function isPrimaryRider(scope: string, current: PrimaryIdentity): boolean {+ const owner = primaryRiders.get(scope)++ return Boolean(owner && owner.gateway === current.gateway && owner.connectionId === current.connectionId)+}diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 397baed6b07..0b7cfeede6c 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -33,7 +33,12 @@ import {import { $gatewayActivationEpoch } from '@/store/gateway-activation-epoch'import { isMissingConnectionError, isMissingProfileError } from '@/store/gateway-dial-failures'import { $primaryGatewayRoute } from '@/store/gateway-primary-route'-import { isPrimaryRider, notePrimaryRider, sharedPrimaryRoute } from '@/store/gateway-shared-route'+import {+ isPrimaryRider,+ notePrimaryRider,+ type PrimaryIdentity,+ sharedPrimaryRoute+} from '@/store/gateway-shared-route'import { notifyError, RECOVERY_ACTIONS } from '@/store/notifications'import { markNativeNotifyBaseline } from '@/store/notify-baseline'import { setConnection, setGatewayState } from '@/store/session'@@ -325,7 +330,7 @@ export function gatewayRouteState(connectionId: null | string, profile: string):const scope = registryBackendScopeKey(connectionId, key)const onPrimary = key === g.primaryProfile && (scope === key || isPrimaryRegistryRoute(connectionId, key))- if (onPrimary || isPrimaryRider(scope)) {+ if (onPrimary || isPrimaryRider(scope, primaryIdentity())) {return { key: `primary:${key}`, open: isOpen(g.primaryGateway) }}@@ -380,6 +385,10 @@ function primaryConnectionId(): null | string {return $primaryGatewayRoute.get().connectionId}+// Taken BEFORE a route await, so a hint learned across a re-home stays bound+// to the primary the route was resolved against.+const primaryIdentity = (): PrimaryIdentity => ({ connectionId: primaryConnectionId(), gateway: g.primaryGateway })+export function setPrimaryGateway(gateway: HermesGateway | null, profile = 'default'): void {const next = normKey(profile)@@ -1139,7 +1148,7 @@ async function gatewayForProfile(throw new Error(`Backend for "${key}" is reconnecting; retry after it settles.`)}- if (notePrimaryRider(key, await sharedPrimaryRoute(key))) {+ if (notePrimaryRider(primaryIdentity(), key, await sharedPrimaryRoute(key))) {return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: true }}@@ -1277,7 +1286,7 @@ export async function requestGatewayForAgent<T>(return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal, { spawnPriority })}- if (notePrimaryRider(scope, await ridesPrimaryBackend(connectionId, key))) {+ if (notePrimaryRider(primaryIdentity(), scope, await ridesPrimaryBackend(connectionId, key))) {traceAgentRoute(scope, 'primary-shared')return requestOnPrimaryGateway<T>(method, { ...params, profile: key }, timeoutMs, signal)@@ -1688,9 +1697,14 @@ function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {const key = turnLeaseKey(scope, sessionId)- if (!acceptExecutionEvent(turnExecutionAuthorities, key, event.type, event)) {return}+ if (!acceptExecutionEvent(turnExecutionAuthorities, key, event.type, event)) {+ return+ }- if (event.type === 'message.start' || (event.type === 'session.info' && (event.payload as Record<string, unknown>)?.running === true)) {+ if (+ event.type === 'message.start' ||+ (event.type === 'session.info' && (event.payload as Record<string, unknown>)?.running === true)+ ) {// 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)