Skip to content

The agent that grows with you

fix(desktop): route bot-chat RPCs to the bot's own gateway via tile ownerRoute (#92956)

Teknium9452bca388f4
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index e5b7dbdcc26..c146b87ffb9 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -79,6 +79,7 @@ import {
setMessages
} from '@/store/session'
import { requestForSessionProfile } from '@/store/session-request-router'
+import { $focusedStoredSessionId, sessionTileOwnerRoute } from '@/store/session-states'
import { clearSessionTodos, setSessionTodos, todosForHydration } from '@/store/todos'
import { armWakeWord, stopClientCapture } from '@/store/wake-word'
import { isAuxiliaryWindow, isHudWindow } from '@/store/windows'
@@ -294,13 +295,24 @@ export function ContribWiring({ children }: { children: ReactNode }) {
// When chrome stays on the launch backend (Bot Mode / all-profiles
// navigation), session-owned RPCs still have to hit the session's backend.
+ //
+ // A bot chat is a persisted TILE that already records the EXACT owning route
+ // (connectionId + profile) it was opened with — the same authoritative owner
+ // Sessions mode reads off the session row. Prefer it, keyed on the FOCUSED
+ // stored id: a tile is never $selectedStoredSessionId (that stays the primary
+ // pane), so routing off `selected` would send the bot's RPC to the primary's
+ // profile. The canonical Bot Chat is also hidden, so it never appears in
+ // $sessions and rememberedSessionProfile's row lookup misses and falls back to
+ // the ACTIVE profile — the Bot Mode "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 (keyed on
+ // the same focused id) only when no tile route exists.
const requestGateway = useCallback(
<T,>(method: string, params?: Record<string, unknown>, timeoutMs?: number, signal?: AbortSignal) => {
- const owner = rememberedSessionProfile(
- $sessions.get(),
- selectedStoredSessionIdRef.current,
- $activeGatewayProfile.get()
- )
+ const routingSessionId = $focusedStoredSessionId.get() ?? selectedStoredSessionIdRef.current
+ const owner =
+ (routingSessionId ? sessionTileOwnerRoute(routingSessionId) : undefined) ??
+ rememberedSessionProfile($sessions.get(), routingSessionId, $activeGatewayProfile.get())
return requestForSessionProfile<T>(owner, ambientRequestGateway, method, params ?? {}, timeoutMs, signal)
},
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 4f4d7b83607..7c8ec204e23 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -717,9 +717,29 @@ export const host = {
* also scope chrome onto that profile and collapse the sidebar. */
openSession: async (storedSessionId: string, options: PluginOpenSessionOptions = {}): Promise<void> => {
const generation = ++openSessionGeneration
- const ownerRoute = options.route ? { ...options.route } : null
- const profile = (ownerRoute?.profile ?? options.profile ?? '').trim()
+ const explicitRoute = options.route ? { ...options.route } : null
+ const profile = (explicitRoute?.profile ?? options.profile ?? '').trim()
const targetProfile = normalizeProfileKey(profile || $activeGatewayProfile.get())
+
+ // A local bot open passes only `profile` (no cross-connection route), but
+ // its RPCs STILL have to reach that profile's own local gateway while chrome
+ // stays on the launch profile. Synthesize a local owner route from the
+ // profile so the persisted tile carries it — the session-request router
+ // reads the tile route to dispatch on the owning backend, and the canonical
+ // Bot Chat is hidden (never in $sessions), so this is the only owner record
+ // it can consult. Without it, submit falls back to the active profile and
+ // 4001s / hangs against a backend that never owned the session.
+ //
+ // This is ROUTING metadata only (tile ownerRoute + owner hint); the dial
+ // path below still keys off the explicit cross-connection route, so a plain
+ // local open dials exactly as before (openGatewayForProfile), never the
+ // registry-secondary path.
+ const localConnectionId = activeGatewayConnectionId()
+ const ownerRoute =
+ explicitRoute ??
+ (options.workspaceMode === 'bots' && profile && localConnectionId
+ ? { connectionId: localConnectionId, mode: 'local' as const, profile: targetProfile }
+ : null)
const expectHistory = options.expectHistory ?? false
if (options.workspaceMode === 'bots') {
@@ -779,8 +799,13 @@ export const host = {
// budget's. A workspace switch moves $activeGatewayProfile / chrome REST;
// a plain navigation only opens the bot's gateway so session.resume can
// hydrate, leaving chrome on the launch backend.
- const dial = ownerRoute
- ? () => openGatewayForAgent(ownerRoute.connectionId, ownerRoute.profile)
+ // Dial keys off the EXPLICIT cross-connection route only: a synthesized
+ // local ownerRoute is routing metadata for the tile/hint, and a local
+ // profile must dial through openGatewayForProfile (its established path),
+ // not the registry-secondary path openGatewayForAgent takes for a 'local'
+ // connection id. Behavior for a plain local open is unchanged.
+ const dial = explicitRoute
+ ? () => openGatewayForAgent(explicitRoute.connectionId, explicitRoute.profile)
: plan.switchWorkspace
? () => ensureGatewayProfile(plan.switchWorkspace as string)
: plan.dialWithoutSwitching
@@ -800,7 +825,10 @@ export const host = {
throw new Error('Session open was superseded by a newer selection.')
}
- if (ownerRoute) {
+ // Only a cross-connection (explicit route) open forces the all-profiles
+ // view; a local bot open keeps the planner's decision, unchanged from
+ // before the synthesized-route addition.
+ if (explicitRoute) {
setShowAllProfiles(true)
} else if (plan.showAllProfiles !== null) {
setShowAllProfiles(plan.showAllProfiles)
@@ -892,7 +920,10 @@ export const host = {
throw error
}
- if (ownerRoute && !(await pluginRouteStillRegistered(ownerRoute))) {
+ // The registry check applies only to a real cross-connection route
+ // (explicit): a synthesized local route is never in getProfileRoutes,
+ // so checking it would spuriously abort a local bot's hydration retry.
+ if (explicitRoute && !(await pluginRouteStillRegistered(explicitRoute))) {
throw new Error(`The ${targetProfile} gateway is no longer available.`)
}
diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.ts
index 6eff590dbf7..bd1a3cb521f 100644
--- a/apps/desktop/src/store/session-states.test.ts
+++ b/apps/desktop/src/store/session-states.test.ts
@@ -21,6 +21,7 @@ import {
resetTileRuntimeBindings,
selectionHomesToWorkspace,
type SessionTileDelegate,
+ sessionTileOwnerRoute,
setSessionTileDelegate,
setSessionTileWorkspaceScope
} from '@/store/session-states'
@@ -459,3 +460,39 @@ describe('reopenLastClosedTile focuses the restored tab', () => {
expect(tree.$activeTreeGroup.get()).toBe('grp-main')
})
})
+
+describe('sessionTileOwnerRoute', () => {
+ afterEach(() => {
+ $sessionTiles.set([])
+ })
+
+ it('returns the exact owning route a bot chat tile was opened with', () => {
+ // This is what lets a bot chat RPC reach the bot's OWN local gateway even
+ // while chrome stays on the launch profile: the tile carries the route, so
+ // the request router never has to guess from the (hidden, unlisted) row.
+ $sessionTiles.set([
+ {
+ ownerRoute: { connectionId: 'local', mode: 'local', profile: 'developer' },
+ storedSessionId: 'bot-chat-developer'
+ }
+ ])
+
+ expect(sessionTileOwnerRoute('bot-chat-developer')).toEqual({
+ connectionId: 'local',
+ mode: 'local',
+ profile: 'developer'
+ })
+ })
+
+ it('returns undefined for a tile with no owner route (plain session)', () => {
+ $sessionTiles.set([{ storedSessionId: 'plain' }])
+
+ expect(sessionTileOwnerRoute('plain')).toBeUndefined()
+ })
+
+ it('returns undefined when the session has no tile', () => {
+ $sessionTiles.set([])
+
+ expect(sessionTileOwnerRoute('missing')).toBeUndefined()
+ })
+})