The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep chrome API home when opening a Bot Chat
EndeavorYen0734cfd31988
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 3aa1d34f45f..f996529eeb6 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -62,12 +62,14 @@ import {$selectedStoredSessionId,$sessionResumeRequest,$sessions,+ rememberedSessionProfile,sessionMatchesStoredId,sessionPinId,setAwaitingResponse,setBusy,setMessages} from '@/store/session'+import { requestForSessionProfile } from '@/store/session-request-router'import { clearSessionTodos, setSessionTodos, todosForHydration } from '@/store/todos'import { armWakeWord, stopClientCapture } from '@/store/wake-word'import { isAuxiliaryWindow, isHudWindow } from '@/store/windows'@@ -279,7 +281,22 @@ export function ContribWiring({ children }: { children: ReactNode }) {setMessages})- const { connectionRef, gateway, gatewayRef, requestGateway } = useGatewayRequest()+ const { connectionRef, gateway, gatewayRef, requestGateway: ambientRequestGateway } = useGatewayRequest()++ // When chrome stays on the launch backend (Bot Mode / all-profiles+ // navigation), session-owned RPCs still have to hit the session's backend.+ const requestGateway = useCallback(+ <T,>(method: string, params?: Record<string, unknown>, timeoutMs?: number, signal?: AbortSignal) => {+ const owner = rememberedSessionProfile(+ $sessions.get(),+ selectedStoredSessionIdRef.current,+ $activeGatewayProfile.get()+ )++ return requestForSessionProfile<T>(owner, ambientRequestGateway, method, params ?? {}, timeoutMs, signal)+ },+ [ambientRequestGateway]+ )const { loadMoreMessagingForPlatform, loadMoreSessions, refreshCronJobs, refreshMessagingSessions, refreshSessions } =useSessionListActions({ profileScope })diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 572c7e1f620..96355eee624 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -13,6 +13,7 @@ import { setSessionYolo } from '@/lib/yolo-session'import { normalizeChoices, setClarifyRequest } from '@/store/clarify'import { migrateSessionDraft } from '@/store/composer'import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'+import { openGatewayForAgent, openGatewayForProfile } from '@/store/gateway'import { $gatewaySwitching } from '@/store/gateway-switch'import { $pinnedSessionIds } from '@/store/layout'import { clearNotifications, notify, notifyError } from '@/store/notifications'@@ -20,6 +21,7 @@ import {$activeGatewayProfile,$gatewaySwapTarget,$newChatProfile,+ $showAllProfiles,ensureGatewayAgent,ensureGatewayProfile,normalizeProfileKey@@ -740,7 +742,15 @@ export function useSessionActions({// A row spliced from a CONNECTED registry gateway (#88880) carries its// owning connection — activate THAT gateway, not a same-named local// profile. Rows without the tag keep the legacy profile path.- if (storedForProfile?.connection_id) {+ // All-profiles / plugin navigation must not steal chrome API-home:+ // dial the owning backend without moving $activeGatewayProfile.+ if ($showAllProfiles.get()) {+ if (storedForProfile?.connection_id) {+ await openGatewayForAgent(storedForProfile.connection_id, sessionProfile || 'default')+ } else if (sessionProfile) {+ await openGatewayForProfile(normalizeProfileKey(sessionProfile))+ }+ } else if (storedForProfile?.connection_id) {await ensureGatewayAgent(storedForProfile.connection_id, sessionProfile || 'default')} else {await ensureGatewayProfile(sessionProfile)diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 2aee7a86dca..ce2ed76527b 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -79,6 +79,8 @@ import {import { runGatewayRestart } from '@/store/system-actions'import type { UsageStats } from '@/types/hermes'+import { planPluginOpenSession } from './plugin-open-session-plan'+// -- state: readonly views over the app's live atoms -------------------------const readonlyAtom = <T>(atomLike: ReadableAtom<T>): ReadableAtom<T> => atomLike@@ -238,12 +240,14 @@ function waitForFocusedSessionHydration({expectHistory,generation,profile,+ requireActiveProfile,storedSessionId,timeoutMs}: {expectHistory: booleangeneration: numberprofile: string+ requireActiveProfile: booleanstoredSessionId: stringtimeoutMs: number}): Promise<void> {@@ -281,7 +285,8 @@ function waitForFocusedSessionHydration({return}- const profileMatches = normalizeProfileKey($activeGatewayProfile.get()) === profile+ const profileMatches =+ !requireActiveProfile || normalizeProfileKey($activeGatewayProfile.get()) === profileconst sessionMatches = $selectedStoredSessionId.get() === storedSessionIdconst runtimeReady = Boolean($activeSessionId.get())const historyPainted = Boolean($messages.get().length)@@ -336,8 +341,16 @@ function waitForFocusedSessionHydration({// regression. The trade is that a wake that is slow in BOTH phases can now take// up to twice the budget before it surfaces; that is a maintainer call and is// called out in the PR rather than buried here.-async function awaitProfileActivation(profile: string, targetProfile: string, timeoutMs: number): Promise<void> {- const activation = ensureGatewayProfile(profile)+// The caller supplies the dial itself, because WHICH backend to open is a+// routing decision (a workspace switch moves chrome; a plain bot navigation+// only opens the gateway) while the deadline enforced here is the same either+// way.+async function awaitProfileActivation(+ dial: () => Promise<void>,+ targetProfile: string,+ timeoutMs: number+): Promise<void> {+ const activation = dial()let timer: number | undefinedtry {@@ -548,14 +561,22 @@ export const host = {ensureGatewayAgent(connectionId, (profile ?? '').trim() || 'default'),/** Open a stored session the way core surfaces do. A plugin/Bot Mode open- * is navigation, not a workspace switch — keepAllProfilesScope defaults- * true so Sessions stays on the unified list (the bot forever-chat is- * hidden and would otherwise look like every session disappeared). */+ * is navigation, not a workspace or chrome API-home switch —+ * keepAllProfilesScope defaults true so `$activeGatewayProfile` /+ * Sessions REST stay on the previous (usually launch) backend while the+ * bot backend is dialed in the background. The bot forever-chat is hidden+ * and would otherwise look like every session disappeared. Pass false to+ * also scope chrome onto that profile and collapse the sidebar. */openSession: async (storedSessionId: string, options: PluginOpenSessionOptions = {}): Promise<void> => {const generation = ++openSessionGenerationconst profile = (options.profile ?? '').trim()const targetProfile = normalizeProfileKey(profile || $activeGatewayProfile.get())const expectHistory = options.expectHistory ?? false+ const plan = planPluginOpenSession({+ activeProfile: $activeGatewayProfile.get(),+ keepAllProfilesScope: options.keepAllProfilesScope,+ profile+ })// Wake-path phase timings. Logged ONLY on a hydration timeout (bridged// into desktop.log via the renderer-console tap), so a support bundle// pinpoints WHERE the budget went — profile activation vs hydration —@@ -574,23 +595,27 @@ export const host = {const maxAttempts = options.awaitHydration && options.retryHydrationTimeoutOnce ? 2 : 1try {- if (profile && profile !== $activeGatewayProfile.get()) {+ // WHICH backend to dial is the plan's call; HOW LONG to wait is the wake+ // 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 = plan.switchWorkspace+ ? () => ensureGatewayProfile(plan.switchWorkspace as string)+ : plan.dialWithoutSwitching+ ? () => openGatewayForProfile(plan.dialWithoutSwitching as string)+ : null++ if (dial) {// Bounded only on the hydration contract, which is where a budget and a// Retry surface both already exist. A plain open never asked for a// deadline and has nowhere to render one, so it keeps today's// behaviour rather than gaining a rejection its callers cannot handle.- await (options.awaitHydration- ? awaitProfileActivation(profile, targetProfile, hydrationTimeoutMs)- : ensureGatewayProfile(profile))+ await (options.awaitHydration ? awaitProfileActivation(dial, targetProfile, hydrationTimeoutMs) : dial())profileActiveAt = Date.now()}- // Outside the dial branch on purpose: re-opening a bot whose profile is- // ALREADY active still has to restore the unified list. Scoped inside,- // the second open of the same bot left Sessions collapsed onto a profile- // whose forever-chat is hidden — an empty sidebar and no roster.- if (profile && options.keepAllProfilesScope !== false) {- setShowAllProfiles(true)+ if (plan.showAllProfiles !== null) {+ setShowAllProfiles(plan.showAllProfiles)}wakePhase = 'hydration'@@ -648,6 +673,9 @@ export const host = {expectHistory,generation,profile: targetProfile,+ // A background dial never moves $activeGatewayProfile, so gating+ // hydration on it would wait for something that is not coming.+ requireActiveProfile: plan.requireActiveProfileForHydration,storedSessionId,timeoutMs: hydrationTimeoutMs})diff --git a/apps/desktop/src/sdk/plugin-open-session-plan.test.ts b/apps/desktop/src/sdk/plugin-open-session-plan.test.tsnew file mode 100644index 00000000000..068c8fe42c8--- /dev/null+++ b/apps/desktop/src/sdk/plugin-open-session-plan.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest'++import { planPluginOpenSession } from './plugin-open-session-plan'++describe('planPluginOpenSession', () => {+ it('defaults to navigation: dial the worker, do not steal chrome', () => {+ const plan = planPluginOpenSession({+ activeProfile: 'default',+ profile: 'worker'+ })++ expect(plan.switchWorkspace).toBeNull()+ expect(plan.dialWithoutSwitching).toBe('worker')+ expect(plan.showAllProfiles).toBe(true)+ expect(plan.requireActiveProfileForHydration).toBe(false)+ })++ it('does not steal chrome even when keepAllProfilesScope is explicitly true', () => {+ const plan = planPluginOpenSession({+ activeProfile: 'default',+ keepAllProfilesScope: true,+ profile: 'worker'+ })++ expect(plan.switchWorkspace).toBeNull()+ expect(plan.dialWithoutSwitching).toBe('worker')+ expect(plan.showAllProfiles).toBe(true)+ expect(plan.requireActiveProfileForHydration).toBe(false)+ })++ it('does not re-dial when chrome is already on that profile', () => {+ const plan = planPluginOpenSession({+ activeProfile: 'worker',+ keepAllProfilesScope: true,+ profile: 'worker'+ })++ expect(plan.switchWorkspace).toBeNull()+ expect(plan.dialWithoutSwitching).toBeNull()+ // Still restores the unified list: re-opening an already-live bot must not+ // leave Sessions collapsed onto a profile whose forever-chat is hidden.+ expect(plan.showAllProfiles).toBe(true)+ })++ it('treats keepAllProfilesScope:false as an explicit workspace switch', () => {+ const plan = planPluginOpenSession({+ activeProfile: 'default',+ keepAllProfilesScope: false,+ profile: 'worker'+ })++ expect(plan.switchWorkspace).toBe('worker')+ expect(plan.dialWithoutSwitching).toBeNull()+ expect(plan.showAllProfiles).toBe(false)+ expect(plan.requireActiveProfileForHydration).toBe(true)+ })++ it('treats an empty profile as neither a dial nor a workspace switch', () => {+ const plan = planPluginOpenSession({+ activeProfile: 'default',+ keepAllProfilesScope: true,+ profile: ' '+ })++ expect(plan.switchWorkspace).toBeNull()+ expect(plan.dialWithoutSwitching).toBeNull()+ expect(plan.showAllProfiles).toBeNull()+ })+})diff --git a/apps/desktop/src/sdk/plugin-open-session-plan.ts b/apps/desktop/src/sdk/plugin-open-session-plan.tsnew file mode 100644index 00000000000..bad5f490ec0--- /dev/null+++ b/apps/desktop/src/sdk/plugin-open-session-plan.ts@@ -0,0 +1,50 @@+/** How `host.openSession` should treat a named profile.++A plugin/Bot Mode open is navigation, not a workspace or chrome API-home+switch. `keepAllProfilesScope` defaults true (undefined counts as true).+Pass false for an explicit profile workspace switch. */+export interface PluginOpenSessionPlan {+ /** Dial this profile's backend without making it chrome-home. */+ dialWithoutSwitching: null | string+ /** Hydration may wait until `$activeGatewayProfile` matches the target. */+ requireActiveProfileForHydration: boolean+ /** Unified Sessions list vs collapse onto the switched profile. Null = leave. */+ showAllProfiles: boolean | null+ /** Activate this profile as the workspace/API home. Null = do not steal chrome. */+ switchWorkspace: null | string+}++export function planPluginOpenSession(input: {+ activeProfile: string+ keepAllProfilesScope?: boolean+ profile: string+}): PluginOpenSessionPlan {+ const profile = (input.profile ?? '').trim()+ const activeProfile = (input.activeProfile ?? '').trim()+ const keepWorkspace = input.keepAllProfilesScope !== false++ if (!profile) {+ return {+ dialWithoutSwitching: null,+ requireActiveProfileForHydration: false,+ showAllProfiles: null,+ switchWorkspace: null+ }+ }++ if (keepWorkspace) {+ return {+ dialWithoutSwitching: profile !== activeProfile ? profile : null,+ requireActiveProfileForHydration: false,+ showAllProfiles: true,+ switchWorkspace: null+ }+ }++ return {+ dialWithoutSwitching: null,+ requireActiveProfileForHydration: true,+ showAllProfiles: false,+ switchWorkspace: profile+ }+}diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.tsindex 0a1e24c9d43..e9cc11ff4fc 100644--- a/apps/desktop/src/sdk/profile-routing.test.ts+++ b/apps/desktop/src/sdk/profile-routing.test.ts@@ -102,7 +102,8 @@ vi.mock('@/store/gateway', async () => {const { host } = await import('./index')const { openSession: openSessionCore } = await import('@/app/open-session')const { deleteProfile } = await import('@/hermes')-const { requestGatewayForAgent, requestGatewayForProfile, retireLocalProfileGateways } = await import('@/store/gateway')+const { openGatewayForProfile, requestGatewayForAgent, requestGatewayForProfile, retireLocalProfileGateways } =+ await import('@/store/gateway')const { $activeGatewayProfile, $gatewaySwapTarget, $profiles, ensureGatewayProfile, refreshProfiles, setShowAllProfiles } =await import('@/store/profile')@@ -290,9 +291,7 @@ describe('connection-aware plugin host APIs', () => {describe('profile-aware plugin session opens', () => {it('waits until the target Bot Chat runtime and history are on main before resolving', async () => {- vi.mocked(ensureGatewayProfile).mockImplementationOnce(async (target: null | string | undefined) => {- $activeGatewayProfile.set(target || 'default')- })+ vi.mocked(openGatewayForProfile).mockImplementationOnce(async () => undefined)let resolved = false@@ -343,9 +342,7 @@ describe('profile-aware plugin session opens', () => {})it('requests an explicit resume on a cold open where selection has not settled (#89206)', async () => {- vi.mocked(ensureGatewayProfile).mockImplementationOnce(async (target: null | string | undefined) => {- $activeGatewayProfile.set(target || 'default')- })+ vi.mocked(openGatewayForProfile).mockImplementationOnce(async () => undefined)// Cold-start shape from the field: the persisted route already points at// the bot's stored session, but no selection, no runtime, no transcript.@@ -398,9 +395,7 @@ describe('profile-aware plugin session opens', () => {})it('resolves a history-bearing wake on transcript paint without waiting for the runtime (paint-first)', async () => {- vi.mocked(ensureGatewayProfile).mockImplementationOnce(async (target: null | string | undefined) => {- $activeGatewayProfile.set(target || 'default')- })+ vi.mocked(openGatewayForProfile).mockImplementationOnce(async () => undefined)setMockAtom($selectedStoredSessionId, null)setMockAtom($activeSessionId, null)@@ -554,11 +549,51 @@ describe('profile-aware plugin session opens', () => {await secondexpect(await firstOutcome).toMatch(/superseded/i)- expect($activeGatewayProfile.get()).toBe('hyoseob')+ expect($activeGatewayProfile.get()).toBe('remote-worker')expect($selectedStoredSessionId.get()).toBe('chat-b')expect($gatewaySwapTarget.get()).toBeNull()})+ it('keeps chrome API home on the previous profile when opening a Bot Chat', async () => {+ $activeGatewayProfile.set('default')++ await host.openSession('bot-chat', {+ profile: 'worker',+ keepAllProfilesScope: true+ })++ expect(ensureGatewayProfile).not.toHaveBeenCalled()+ expect(openGatewayForProfile).toHaveBeenCalledWith('worker')+ expect(setShowAllProfiles).toHaveBeenCalledWith(true)+ expect($activeGatewayProfile.get()).toBe('default')+ })++ it('defaults keepAllProfilesScope to navigation instead of a workspace switch', async () => {+ $activeGatewayProfile.set('default')++ await host.openSession('bot-chat', { profile: 'worker' })++ expect(ensureGatewayProfile).not.toHaveBeenCalled()+ expect(openGatewayForProfile).toHaveBeenCalledWith('worker')+ expect(setShowAllProfiles).toHaveBeenCalledWith(true)+ expect($activeGatewayProfile.get()).toBe('default')+ })++ it('still switches workspace when keepAllProfilesScope is false', async () => {+ $activeGatewayProfile.set('default')+ vi.mocked(openGatewayForProfile).mockImplementationOnce(async () => undefined)++ await host.openSession('stored-worker', {+ profile: 'worker',+ keepAllProfilesScope: false+ })++ expect(ensureGatewayProfile).toHaveBeenCalledWith('worker')+ expect(openGatewayForProfile).not.toHaveBeenCalled()+ expect(setShowAllProfiles).toHaveBeenCalledWith(false)+ expect($activeGatewayProfile.get()).toBe('worker')+ })+it('keeps the Sessions sidebar in all-profiles even when the bot is already live', async () => {$activeGatewayProfile.set('hyoseob')setMockAtom($selectedStoredSessionId, 'bot-chat')@@ -593,6 +628,7 @@ describe('profile-aware plugin session opens', () => {intent: 'main',awaitHydration: true,expectHistory: true,+ keepAllProfilesScope: false,hydrationTimeoutMs: 60})).rejects.toThrow("Timed out loading medicina's session history.")@@ -614,6 +650,7 @@ describe('profile-aware plugin session opens', () => {intent: 'main',awaitHydration: true,expectHistory: true,+ keepAllProfilesScope: false,hydrationTimeoutMs: 60})).rejects.toThrow('Timed out loading ')@@ -651,7 +688,8 @@ describe('profile-aware plugin session opens', () => {intent: 'main',awaitHydration: true,expectHistory: true,- hydrationTimeoutMs: 200+ keepAllProfilesScope: false,+ hydrationTimeoutMs: 200})// 300ms total is past a single shared 200ms budget and inside hydration's@@ -699,6 +737,7 @@ describe('profile-aware plugin session opens', () => {intent: 'main',awaitHydration: true,expectHistory: true,+ keepAllProfilesScope: false,hydrationTimeoutMs: 40})).rejects.toThrow('Timed out loading ')@@ -722,7 +761,8 @@ describe('profile-aware plugin session opens', () => {let settled = 'pending'- void host.openSession('plain-chat', { profile: 'medicina', intent: 'main', hydrationTimeoutMs: 40 }).then(+ void host.openSession('plain-chat', { profile: 'medicina', intent: 'main', keepAllProfilesScope: false,+ hydrationTimeoutMs: 40 }).then(() => {settled = 'resolved'},diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 5b723194d9f..3cf35be66c0 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -573,7 +573,9 @@ async function gatewayForProfile(export async function requestGatewayForProfile<T>(profile: string,method: string,- params: Record<string, unknown> = {}+ params: Record<string, unknown> = {},+ timeoutMs?: number,+ signal?: AbortSignal): Promise<T> {const route = await gatewayForProfile(profile, true)@@ -584,7 +586,7 @@ export async function requestGatewayForProfile<T>(const routedParams = route.scopeProfile ? { ...params, profile: route.key } : params- return await route.gateway.request<T>(method, routedParams)+ return await route.gateway.request<T>(method, routedParams, timeoutMs, signal)} finally {route.release()}diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex f6f3ef89a87..43335fe8170 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -167,6 +167,37 @@ describe('requestForSessionProfile', () => {expect(secondaryGateways[0].request).toHaveBeenCalledWith('session.resume', { session_id: 'stored-loki-chat' })})+ it('forwards timeout and abort signal onto the owning profile socket', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ await ensureGatewayForProfile('default')++ const ambient = vi.fn(async (method: string, params?: Record<string, unknown>) => ({+ ambient: true,+ method,+ params+ }))+ const controller = new AbortController()++ await requestForSessionProfile(+ 'loki',+ ambient as never,+ 'prompt.submit',+ { session_id: 'stored-loki-chat', text: 'hi' },+ 1_800_000,+ controller.signal+ )++ expect(ambient).not.toHaveBeenCalled()+ expect(secondaryGateways[0].request).toHaveBeenCalledWith(+ 'prompt.submit',+ { session_id: 'stored-loki-chat', text: 'hi' },+ 1_800_000,+ controller.signal+ )+ })+it('keeps the ambient dispatcher when the active route already serves the owner', async () => {const primary = makePrimary()setPrimaryGateway(primary as never, 'default')diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex 8c67a529163..82de324a1b5 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -40,13 +40,20 @@ export function sessionRpcNeedsProfileRoute(*/export function requestForSessionProfile<T>(ownerProfile: null | string | undefined,- ambientRequest: <R>(method: string, params?: Record<string, unknown>) => Promise<R>,+ ambientRequest: <R>(+ method: string,+ params?: Record<string, unknown>,+ timeoutMs?: number,+ signal?: AbortSignal+ ) => Promise<R>,method: string,- params: Record<string, unknown> = {}+ params: Record<string, unknown> = {},+ timeoutMs?: number,+ signal?: AbortSignal): Promise<T> {if (!sessionRpcNeedsProfileRoute(ownerProfile)) {- return ambientRequest<T>(method, params)+ return ambientRequest<T>(method, params, timeoutMs, signal)}- return requestGatewayForProfile<T>(normKey(ownerProfile), method, params)+ return requestGatewayForProfile<T>(normKey(ownerProfile), method, params, timeoutMs, signal)}