The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): active gateway is never a session-RPC routing authority
Tekniumd12bc0c4d9d5
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex fe929eec32b..782a3034a2c 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -14,6 +14,7 @@ import { type CSSProperties, lazy, type ReactNode, Suspense, useCallback, useEffimport { useLocation, useNavigate } from 'react-router'import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'+import { resolveSessionProfile } from '@/app/session/hooks/use-session-actions/utils'import { formatRefValue } from '@/components/assistant-ui/directive-text'import { BootFailureOverlay } from '@/components/boot-failure-overlay'import { ConfirmHost } from '@/components/confirm-host'@@ -71,14 +72,14 @@ import {$selectedStoredSessionId,$sessionResumeRequest,$sessions,- rememberedSessionProfile,+ knownSessionProfile,sessionMatchesStoredId,sessionPinId,setAwaitingResponse,setBusy,setMessages} from '@/store/session'-import { requestForSessionProfile } from '@/store/session-request-router'+import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'import { $focusedStoredSessionId, sessionTileOwnerRoute, storedSessionIdForRuntimeId } from '@/store/session-states'import { clearSessionTodos, setSessionTodos, todosForHydration } from '@/store/todos'import { armWakeWord, stopClientCapture } from '@/store/wake-word'@@ -315,8 +316,16 @@ export function ContribWiring({ children }: { children: ReactNode }) {// "session not found" / hang. The tile route is per-session, survives// relaunch, and needs no list membership, so it fixes an already-open chat// too. Fall back to the list-derived profile only when no tile route exists.+ // Session-scoped RPCs route to the backend that OWNS the session — its+ // profile's own local gateway — never to whatever is "active" (active is+ // presentation only). Resolve the owner from, in order: the tile's persisted+ // route (bot chats carry an exact connectionId+profile), the known session+ // profile (row or open-time hint), then a cross-profile REST probe that+ // stamps ownership for a hidden/unlisted session. Only a request with NO+ // session at all (a fresh draft, global chrome) falls to the ambient socket.+ // The probe result is cached as an owner hint so the next call is sync.const requestGateway = useCallback(- <T,>(method: string, params?: Record<string, unknown>, timeoutMs?: number, signal?: AbortSignal) => {+ async <T,>(method: string, params?: Record<string, unknown>, timeoutMs?: number, signal?: AbortSignal) => {// Route each RPC by the session IT targets, not by whatever tile is// focused. `requestGateway` is one shared closure used for every session// RPC in the window; keying the owner off $focusedStoredSessionId sent a@@ -347,9 +356,22 @@ export function ContribWiring({ children }: { children: ReactNode }) {undefined})- const owner =+ let owner: SessionOwnerScope =(routingSessionId ? sessionTileOwnerRoute(routingSessionId) : undefined) ??- rememberedSessionProfile($sessions.get(), routingSessionId, $activeGatewayProfile.get())+ knownSessionProfile($sessions.get(), routingSessionId)++ if (!owner && routingSessionId) {+ // Unknown owner for a REAL session: probe across profiles (REST, not the+ // gateway socket, so no recursion) rather than defaulting to active. A+ // hit stamps ownership + caches a hint; a miss leaves owner undefined+ // and the request falls to ambient, exactly as an unroutable session did+ // before — but only after we tried, never as a silent active fallback.+ const probed = await resolveSessionProfile(routingSessionId)++ if (probed) {+ owner = probed+ }+ }return requestForSessionProfile<T>(owner, ambientRequestGateway, method, params ?? {}, timeoutMs, signal)},diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex cd020dea619..b831668267e 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -128,18 +128,26 @@ describe('$activeGatewayRoute (registry-owned active profile)', () => {})describe('sessionRpcNeedsProfileRoute', () => {- it('routes ambient when the owner is unknown or already active', () => {- expect(sessionRpcNeedsProfileRoute(null, 'default')).toBe(false)- expect(sessionRpcNeedsProfileRoute('', 'default')).toBe(false)- expect(sessionRpcNeedsProfileRoute(' ', 'loki')).toBe(false)- expect(sessionRpcNeedsProfileRoute('loki', 'loki')).toBe(false)- expect(sessionRpcNeedsProfileRoute('default', 'default')).toBe(false)+ it('routes ambient ONLY when the owner is unknown (no session / global chrome)', () => {+ expect(sessionRpcNeedsProfileRoute(null)).toBe(false)+ expect(sessionRpcNeedsProfileRoute(undefined)).toBe(false)+ expect(sessionRpcNeedsProfileRoute('')).toBe(false)+ expect(sessionRpcNeedsProfileRoute(' ')).toBe(false)})- it('pins to the owning profile when the active route diverges', () => {- expect(sessionRpcNeedsProfileRoute('loki', 'default')).toBe(true)- expect(sessionRpcNeedsProfileRoute('default', 'loki')).toBe(true)- expect(sessionRpcNeedsProfileRoute('loki', 'hulk')).toBe(true)+ it('pins a KNOWN owner to its own profile regardless of what is active', () => {+ // No active-profile comparison exists anymore: "active" is presentation+ // state, never a routing authority. A known owner ALWAYS routes to its own+ // profile — even when it happens to equal whatever is currently active,+ // gatewayForProfile collapses that back to the primary socket (no cost).+ expect(sessionRpcNeedsProfileRoute('loki')).toBe(true)+ expect(sessionRpcNeedsProfileRoute('default')).toBe(true)+ expect(sessionRpcNeedsProfileRoute('hulk')).toBe(true)+ })++ it('pins a route owner with a connectionId', () => {+ expect(sessionRpcNeedsProfileRoute({ connectionId: 'local', profile: 'developer' })).toBe(true)+ expect(sessionRpcNeedsProfileRoute({ connectionId: '', profile: 'developer' })).toBe(false)})})@@ -303,11 +311,10 @@ describe('requestForSessionProfile', () => {)})- it('keeps the ambient dispatcher when the active route already serves the owner', async () => {+ it('routes an owner that IS the primary profile onto the primary socket (no active comparison)', async () => {const primary = makePrimary()- setPrimaryGateway(primary as never, 'default')+ setPrimaryGateway(primary as never, 'loki')installDesktop()- await ensureGatewayForProfile('loki')const ambient = vi.fn(async (method: string, params?: Record<string, unknown>) => ({ambient: true,@@ -315,10 +322,21 @@ describe('requestForSessionProfile', () => {params}))- const result = await requestForSessionProfile('loki', ambient as never, 'session.activate', { session_id: 'rt-1' })+ // Owner 'loki' equals the PRIMARY profile. There is no active-profile+ // comparison anymore, but gatewayForProfile collapses a primary-profile+ // owner back to the primary socket — so no secondary is spun up. The+ // ambient fn isn't used (routing goes through requestGatewayForProfile),+ // but the request still lands on the one primary gateway.+ const result = await requestForSessionProfile<{ method: string; params: Record<string, unknown> }>(+ 'loki',+ ambient as never,+ 'session.activate',+ { session_id: 'rt-1' }+ )- expect(ambient).toHaveBeenCalledWith('session.activate', { session_id: 'rt-1' })- expect(result).toEqual({ ambient: true, method: 'session.activate', params: { session_id: 'rt-1' } })+ expect(secondaryGateways).toHaveLength(0)+ expect(primary.request).toHaveBeenCalledWith('session.activate', { session_id: 'rt-1' })+ expect(result).toEqual({ method: 'session.activate', params: { session_id: 'rt-1' } })})it('keeps the ambient dispatcher for sessions with no owning profile', async () => {diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex f147df5b7af..b8c6cabab63 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -1,9 +1,4 @@-import {- activeGatewayConnectionId,- activeGatewayProfileKey,- requestGatewayForAgent,- requestGatewayForProfile-} from '@/store/gateway'+import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'export interface SessionProfileRoute {connectionId: string@@ -15,17 +10,22 @@ export interface SessionProfileRoute {export type SessionOwnerScope = undefined | null | string | SessionProfileRoute// ── Session-scoped RPC routing (the #89206 class) ───────────────────────────-// A session-scoped RPC (session.resume / session.activate / session.usage)-// only means anything on the backend that OWNS the session's profile. The-// ambient "active gateway" is a moving target: between the profile-swap await-// and the RPC dispatch, a concurrent switch, an idle-reap eviction, a failed-// dial, or a connection edit can re-point the active route at another-// backend. Dispatching on it anyway lands the RPC on a backend that has never-// heard of the session — it 404s or times out, the renderer burns its bounded-// retries, and the user sees "retries gave up" while the session's own-// backend is healthy (blank Bot Chats, dead wake-ups; local pool and SSH-// alike). These helpers make the owning profile, resolved at REQUEST time,-// the routing authority.+// A session-scoped RPC (session.resume / session.activate / session.usage /+// prompt.submit) only means anything on the backend that OWNS the session's+// profile. A session's profile is a PROPERTY OF THE SESSION, not of whatever+// the window is currently showing. The "active gateway" is a moving target+// (a concurrent switch, an idle-reap eviction, a failed dial, or a connection+// edit re-points it) AND, for a hidden/unlisted session, it is simply the+// WRONG backend — one that never owned the session. Dispatching there 404s or+// times out while the session's own backend is healthy (blank Bot Chats, dead+// wake-ups; local pool and SSH alike).+//+// So: a KNOWN owner is always routed to its own profile's socket — there is no+// "same as active, so use ambient" shortcut, because "active" carries no+// routing authority. Only a genuinely UNKNOWN owner (a fresh draft with no+// session yet, or truly global chrome) falls to the ambient dispatcher, and+// callers are expected to resolve the owner (cross-profile probe) before they+// reach that case for a real session.const normKey = (profile: null | string | undefined): string => (profile ?? '').trim() || 'default'@@ -41,16 +41,15 @@ function routeParams(route: SessionProfileRoute, params: Record<string, unknown>}/**- * True when a session-scoped RPC must be pinned to `ownerProfile`'s own- * socket because the active gateway currently serves a different profile.- * A null/empty owner means the session's profile is unknown — route ambient- * (the pre-multi-profile behavior) rather than guessing.+ * True when a session-scoped RPC must be pinned to `ownerProfile`'s own socket.+ *+ * A KNOWN owner (route or profile name) always needs its own socket: the+ * session belongs to that profile regardless of what the window is showing.+ * There is deliberately NO comparison against the active profile — "active" is+ * presentation state, never a routing authority. Only a null/empty owner (a+ * fresh draft with no session, or global chrome) routes ambient.*/-export function sessionRpcNeedsProfileRoute(- ownerProfile: SessionOwnerScope | undefined,- activeProfile: string = activeGatewayProfileKey(),- activeConnectionId: null | string = activeGatewayConnectionId()-): boolean {+export function sessionRpcNeedsProfileRoute(ownerProfile: SessionOwnerScope | undefined): boolean {if (isRoute(ownerProfile)) {// A descriptor is an immutable ownership claim. Even an explicitly local// route must not collapse to the ambient request: another connection can@@ -58,11 +57,7 @@ export function sessionRpcNeedsProfileRoute(return Boolean(ownerProfile.connectionId.trim())}- if (ownerProfile == null || !String(ownerProfile).trim()) {- return false- }-- return normKey(ownerProfile) !== normKey(activeProfile)+ return ownerProfile != null && Boolean(String(ownerProfile).trim())}/**diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex a2bcb462288..ef236136842 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -30,6 +30,7 @@ import {getRememberedRoute,getRememberedSessionId,getSessionOwnerHint,+ knownSessionProfile,mergeSessionPage,rememberedSessionProfile,resolveComposerSessionKey,@@ -949,3 +950,25 @@ describe('rememberedSessionProfile', () => {expect(rememberedSessionProfile([], null, null)).toBe('default')})})++describe('knownSessionProfile', () => {+ it('returns the row owner when the session is listed', () => {+ const sessions = [session({ id: 'stored-1', profile: 'ai-engineer' })]++ expect(knownSessionProfile(sessions, 'stored-1')).toBe('ai-engineer')+ })++ it('returns the owner hint for a hidden session absent from the list', () => {+ setSessionOwnerHint('hidden-bot-chat', { connectionId: 'local', mode: 'local', profile: 'developer' })++ expect(knownSessionProfile([], 'hidden-bot-chat')).toBe('developer')+ })++ it('returns undefined for an unknown session — NEVER falls back to active', () => {+ // This is the whole point of the no-active-fallback architecture: an+ // unresolved owner must be undefined so the caller does a cross-profile+ // probe, not silently route the RPC to whatever profile is on screen.+ expect(knownSessionProfile([], 'totally-unknown')).toBeUndefined()+ expect(knownSessionProfile([], null)).toBeUndefined()+ })+})diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex f3c555aa613..201d46c4036 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -117,42 +117,50 @@ export function sessionBelongsToProfile(}/**- * The profile a routed session belongs to, for keying the remembered id.+ * The profile that owns a session, from SYNC known sources only: the session+ * row (the cross-profile aggregator tags each row) then the owner hint recorded+ * at open time. Returns undefined when neither knows — the caller must resolve+ * it (cross-profile probe) rather than fall back to whatever is active, because+ * "active" is presentation state and never a routing authority. Hidden sessions+ * (Bot Mode's canonical "Bot Chat") never appear in the row list, so the hint is+ * often the only sync source.+ */+export function knownSessionProfile(+ sessions: readonly SessionInfo[],+ sessionId: null | string+): string | undefined {+ if (!sessionId) {+ return undefined+ }++ const owner = sessions.find(session => sessionMatchesStoredId(session, sessionId))?.profile?.trim()++ if (owner) {+ return owner+ }++ const hint = getSessionOwnerHint(sessionId)++ return (hint?.targetProfile ?? hint?.profile)?.trim() || undefined+}++/**+ * The profile a routed session belongs to, for keying the remembered id and+ * other PRESENTATION uses (which profile's sidebar/navigation this session sits+ * under). Falls back to the active gateway profile when the owner is unknown.*- * Prefer the owning profile recorded on the session row (the cross-profile- * aggregator tags each row), so the session is remembered under ITS profile- * even while a different one is live. Falls back to the active gateway profile- * for a session not yet in the in-memory list.+ * Do NOT use this to ROUTE a session-scoped RPC: the active-profile fallback is+ * exactly what sends a hidden/unlisted session's RPC to a backend that never+ * owned it. Routing must use `knownSessionProfile` + a cross-profile probe and+ * surface an error instead of falling back. This remains for the navigation+ * keying it was written for.*/export function rememberedSessionProfile(sessions: readonly SessionInfo[],sessionId: null | string,activeProfile: null | string): string {- if (sessionId) {- const owner = sessions.find(session => sessionMatchesStoredId(session, sessionId))?.profile?.trim()-- if (owner) {- return owner- }-- // Hidden / plugin-owned sessions (Bot Mode's canonical "Bot Chat" rows are- // born hidden) never appear in the sidebar list, so the row lookup above- // misses for them whenever the aggregator page replaced the in-memory row.- // Falling straight through to the ACTIVE profile routed their session RPCs- // at a backend that never owned the session — prompt.submit answered 4001- // "session not found" while the bot's own backend sat healthy. The open- // path records an owner hint for exactly this; honor it before falling- // back to the active profile.- const hint = getSessionOwnerHint(sessionId)- const hinted = (hint?.targetProfile ?? hint?.profile)?.trim()-- if (hinted) {- return hinted- }- }-- return (activeProfile ?? '').trim() || 'default'+ return knownSessionProfile(sessions, sessionId) ?? ((activeProfile ?? '').trim() || 'default')}// The last non-overlay route (a page like /skills, or a session route), so a