The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a Webapp tab loaded on ?profile=<name> asks the gateway for that profile by name
emozilla984897fcd7c3
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot-webapp-profile.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-webapp-profile.test.tsxnew file mode 100644index 00000000000..600d2c9a1c8--- /dev/null+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-webapp-profile.test.tsx@@ -0,0 +1,178 @@+import { act, cleanup, render } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'+import { $desktopBoot } from '@/store/boot'+import { closeSecondaryGateways, isActivePrimary, requestGatewayForProfile } from '@/store/gateway'+import { $activeGatewayProfile } from '@/store/profile'+import { $connection, $gatewayState } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { FakeWebSocket } from '../../../test/fake-gateway-socket'++import { takeGatewaySurvivor } from './gateway-hmr-survivor'+import { useGatewayBoot } from './use-gateway-boot'++// A Webapp tab has one socket, and the serving gateway answers it for the profile it was launched as+// whenever a request names no profile, exactly as its REST does. A tab loaded or reloaded on+// `?profile=<name>` (or opened on the origin's saved default) therefore keeps that launch profile as its+// primary and selects <name> on top of it, the way a live switch does: every request for <name> carries+// `profile`. These tests boot the real hook against the real browser bridge.++vi.mock(import('@/store/notifications'), async importOriginal => ({+ ...(await importOriginal()),+ notifyError: vi.fn()+}))++vi.mock(import('@/store/terminal-backend-warning'), () => ({+ warnIfTerminalBackendUnavailable: vi.fn(async () => false)+}))++type WebappWindow = Window & { __HERMES_DASHBOARD_PROFILE__?: string }++function Harness() {+ useGatewayBoot({+ beforeConnectionSwitch: () => undefined,+ handleGatewayEvent: () => undefined,+ handleServerRequest: () => false,+ onConnectionReady: () => undefined,+ onGatewayReady: () => undefined,+ refreshHermesConfig: async () => undefined,+ refreshSessions: async () => undefined+ })++ return null+}++function closeSurvivor() {+ try {+ takeGatewaySurvivor()?.gateway.close()+ } catch {+ // ignore+ }+}++const originalWebSocket = globalThis.WebSocket+const mints: URL[] = []+const frames: { method?: string; params?: Record<string, unknown> }[] = []++async function flush() {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+}++/** Boot a Webapp tab at `url` against a gateway launched as `launch`; resolves once boot is done. */+async function bootWebappTab(url: string, launch = 'default') {+ ;(window as WebappWindow).__HERMES_DASHBOARD_PROFILE__ = launch+ window.history.replaceState(null, '', url)+ seedWebappSession('served-token')+ expect(installBrowserDesktopBridge()).toBe(true)+ render(<Harness />)++ for (let i = 0; i < 10 && $desktopBoot.get().running; i += 1) {+ await flush()+ }++ expect($desktopBoot.get().running).toBe(false)+}++/** The params the tab's socket carried for one request to `profile`. */+async function sentFor(profile: string, method: string) {+ frames.length = 0+ void requestGatewayForProfile(profile, method, {}).catch(() => undefined)+ await flush()++ return frames.find(frame => frame.method === method)?.params+}++beforeEach(() => {+ closeSurvivor()+ closeSecondaryGateways()+ $activeGatewayProfile.set('default')+ $connection.set(null)+ mints.length = 0+ frames.length = 0+ vi.useFakeTimers()+ FakeWebSocket.mode = 'open'+ FakeWebSocket.instances = []+ FakeWebSocket.pingMode = 'pong'+ ;(globalThis as { WebSocket: unknown }).WebSocket = FakeWebSocket+ vi.spyOn(FakeWebSocket.prototype, 'send').mockImplementation(function (this: FakeWebSocket, data: string) {+ frames.push(JSON.parse(data) as (typeof frames)[number])+ })+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (url: URL) => {+ if (url.pathname.endsWith('/api/webapp/socket-ticket')) {+ mints.push(url)++ return new Response(JSON.stringify({ ticket: `ticket-${mints.length}` }), { status: 200 })+ }++ return new Response(JSON.stringify({ profiles: [{ name: 'default' }, { name: 'research' }] }), { status: 200 })+ })+ )+ $gatewayState.set('idle')+ $desktopBoot.set({+ error: null,+ fakeMode: false,+ message: '',+ phase: 'init',+ progress: 0,+ running: true,+ timestamp: Date.now(),+ visible: true+ })+})++afterEach(() => {+ cleanup()+ closeSurvivor()+ closeSecondaryGateways()+ $connection.set(null)+ $activeGatewayProfile.set('default')+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ ;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket+ Reflect.deleteProperty(window, 'hermesDesktop')+ delete (window as WebappWindow).__HERMES_DASHBOARD_PROFILE__+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ clearWebappSession()+ window.localStorage.clear()+ window.history.replaceState(null, '', '/#/')+})++it('a tab loaded on ?profile=<name> asks its socket for that profile, by name', async () => {+ await bootWebappTab('/?profile=research#/')+ expect($activeGatewayProfile.get()).toBe('research')++ // The live-status poll and every other request for the tab's profile name it on the wire...+ expect(await sentFor('research', 'session.active_list')).toEqual({ profile: 'research' })+ // ...and the gateway's own profile is the one a request without `profile` reaches.+ expect(await sentFor('default', 'session.active_list')).toEqual({})++ // One socket, minted for the gateway's own profile: the mint names no other.+ expect(FakeWebSocket.instances).toHaveLength(1)+ expect(mints.map(url => url.searchParams.get('profile'))).toEqual([null])+ expect($connection.get()).toMatchObject({ profile: 'research', sharedPrimary: true })+ expect(isActivePrimary()).toBe(true)+})++it('a bare tab on a gateway launched as a named profile names default when it asks for it', async () => {+ await bootWebappTab('/#/', 'research')++ expect($activeGatewayProfile.get()).toBe('research')+ expect(await sentFor('research', 'session.active_list')).toEqual({})+ expect(await sentFor('default', 'session.active_list')).toEqual({ profile: 'default' })+})++it('a bare tab opens on the saved default the same way', async () => {+ window.localStorage.setItem('hermes:webapp:default-profile:/', JSON.stringify({ connectionId: 'local', profile: 'research' }))+ await bootWebappTab('/#/')++ expect($activeGatewayProfile.get()).toBe('research')+ expect(await sentFor('research', 'session.active_list')).toEqual({ profile: 'research' })+ expect(mints.map(url => url.searchParams.get('profile'))).toEqual([null])+})diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 04b310164c5..f1d83ff6cd8 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -23,6 +23,7 @@ import {LIVENESS_REPROBE_DELAY_MS} from '@/lib/gateway-liveness-policy'import { resolveDesktopGatewayWsUrl } from '@/lib/gateway-ws-url'+import { browserLaunchProfile, isBrowserHostedDesktop } from '@/lib/platform'import { BACKEND_BOOT_WAIT_TIMEOUT_MS, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'import {$desktopBoot,@@ -69,6 +70,7 @@ import { notify, notifyError, RECOVERY_ACTIONS } from '@/store/notifications'import {$activeGatewayProfile,currentProfileSelectionRevision,+ ensureGatewayProfile,normalizeProfileKey,refreshActiveProfile} from '@/store/profile'@@ -166,6 +168,29 @@ export function primaryRuntimeConnectionId(connection: Pick<HermesConnection, 'creturn connection.mode === 'local' ? 'local' : null}+/**+ * Open a Webapp tab on the profile it was loaded for, the way a live switch reaches it. The tab's one+ * socket answers for the profile its gateway runs as (`primary`) when a request names none, as its REST+ * does; any other profile rides that socket with `profile` on every request. So the tab's `?profile=`+ * (which a live switch keeps current, so a reload lands where the user was), else on a cold boot the+ * origin's saved default, is selected on top of the primary instead of becoming it.+ */+async function openWebappTabProfile(desktop: Window['hermesDesktop'], primary: string, startup: boolean) {+ const profile =+ windowProfileOverride() ??+ (startup && !isPeerInstanceWindow() ? (await desktop.profile?.getDefault?.())?.profile?.trim() : null)++ if (!profile || normalizeProfileKey(profile) === primary) {+ return+ }++ try {+ await ensureGatewayProfile(profile)+ } catch (error) {+ console.warn(`[gateway] could not open this tab on profile "${profile}"; it stays on "${primary}"`, error)+ }+}+// A freshly spawned backend can block its event loop for 15-30s while it// connects MCP servers and discovers plugins, so a single initial connect// attempt races backend cold-start and loses intermittently — the renderer@@ -705,6 +730,11 @@ export function useGatewayBoot({// default profile's last session (#82285). The override wins over the// stored preference; absent, behavior is unchanged.async function getWindowBackend(startup = false): Promise<HermesConnection> {+ // Webapp: the tab's own socket, whatever profile the tab opens on (openWebappTabProfile).+ if (isBrowserHostedDesktop()) {+ return desktop.getConnection()+ }+const profile = windowProfileOverride()const peer = isPeerInstanceWindow()@@ -726,11 +756,14 @@ export function useGatewayBoot({async function adoptPrimaryProfile(connection: HermesConnection,selectionRevision: number,- shouldPublish: () => boolean = () => true+ shouldPublish: () => boolean = () => true,+ startup = false): Promise<boolean> {+ const webapp = isBrowserHostedDesktop()// The resolved descriptor reflects the explicit startup default. The// legacy profile.get preference only remembers the last workspace used.- const override = windowProfileOverride() ?? connection.profile+ // A Webapp tab's primary is the profile its gateway runs as.+ const override = webapp ? browserLaunchProfile() : (windowProfileOverride() ?? connection.profile)try {const profileKey = override ?? (await desktop.profile?.get?.())?.profile ?? ''@@ -755,6 +788,10 @@ export function useGatewayBoot({if (!userPicked) {void ensureGatewayForProfile(key)}++ if (webapp && !userPicked) {+ await openWebappTabProfile(desktop, key, startup)+ }} catch {if (!shouldPublish()) {return false@@ -1561,7 +1598,7 @@ export function useGatewayBoot({// (cwd seed, config, sessions) are independent REST calls — running// them serially added their sum to time-to-populated-sidebar when only// the max is needed.- await adoptPrimaryProfile(conn, selectionRevision)+ await adoptPrimaryProfile(conn, selectionRevision, undefined, true)setDesktopBootStep({phase: 'renderer.config',diff --git a/apps/desktop/src/lib/browser-connection.ts b/apps/desktop/src/lib/browser-connection.tsindex a12d0994773..c879debf41c 100644--- a/apps/desktop/src/lib/browser-connection.ts+++ b/apps/desktop/src/lib/browser-connection.ts@@ -11,7 +11,7 @@ import {navigateToBrowserLogin,ticketedWebsocketUrl} from '@/lib/browser-transport'-import { windowProfileOverride } from '@/store/windows'+import { browserLaunchProfile } from '@/lib/platform'/** The serving origin is the only connection a browser-hosted Desktop has. */export function requireBrowserConnection(connectionId?: null | string): void {@@ -22,6 +22,14 @@ export function requireBrowserConnection(connectionId?: null | string): void {}}+// The tab's one socket answers for the profile the serving gateway runs as when a request names+// none, as its REST does. Any other profile rides that socket with `profile` on every request.+function ridesWithProfile(profile?: null | string): boolean {+ const name = profile?.trim()++ return Boolean(name) && name !== (browserLaunchProfile() || 'default')+}+function connectionFor(bootstrap: BrowserBootstrap, profile?: null | string): HermesConnection {if (!bootstrap.authRequired && !bootstrap.token) {throw webappSignInRequired()}@@ -37,7 +45,7 @@ function connectionFor(bootstrap: BrowserBootstrap, profile?: null | string): Heprofile: profile || undefined,remoteHost: window.location.host,remoteKind: 'url',- sharedPrimary: Boolean(profile),+ sharedPrimary: ridesWithProfile(profile),source: 'settings',token: bootstrap.token,windowButtonPosition: null,@@ -89,11 +97,6 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect| 'oauthLogoutConnectionConfig'| 'testConnectionConfig'> {- // The window's own backend is the profile this tab booted on. A live switch- // rewrites `?profile=` so a reload lands where the user is, but reconnecting- // the window's primary socket must not follow it onto another profile.- const windowProfile = windowProfileOverride()-const getGatewayWsUrl = async (profile?: null | string) => {try {return {@@ -152,9 +155,10 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectreturn ticketedWebsocketUrl(bootstrap, payload.path, payload.profile)},- // Reconnect belongs to the window, not whichever secondary profile is active.- // Explicit null still selects the default backend.- getConnection: async (profile: null | string = windowProfile) => ({+ // Without a profile: the tab's own socket, the one boot and every reconnect dial, whatever+ // profile the tab is on. A named profile other than the gateway's own is a view of that same+ // socket (sharedPrimary), so its requests carry `profile`.+ getConnection: async (profile?: null | string) => ({...connectionFor(bootstrap, profile),connectionId: LOCAL_CONNECTION_ID}),diff --git a/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.ts b/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.tsindex daf4b545f63..238d6393cae 100644--- a/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.ts@@ -246,15 +246,16 @@ afterEach(() => {vi.restoreAllMocks()})-it('reconnects the window owner rather than the active secondary profile', async () => {+it("reconnects the tab's own socket rather than the profile the tab is on", async () => {seedWebappSession('served-token')window.history.replaceState(null, '', '/?profile=window-owner#/session')expect(installBrowserDesktopBridge()).toBe(true)- const initial = await win.hermesDesktop.getConnection('window-owner')$connection.set({ profile: 'active-secondary' } as never)+ // The tab's own socket names no profile: its gateway answers it for the profile it runs as, and+ // `?profile=window-owner` is selected on top of it (requests for it carry `profile`).const reconnect = await win.hermesDesktop.getConnection()- expect(reconnect.profile).toBe(initial.profile)- expect(new URL(reconnect.wsUrl).searchParams.get('profile')).toBe('window-owner')+ expect(reconnect.profile).toBeUndefined()+ expect(new URL(reconnect.wsUrl).searchParams.has('profile')).toBe(false)const explicitDefault = await win.hermesDesktop.getConnection(null)expect(new URL(explicitDefault.wsUrl).searchParams.has('profile')).toBe(false)const namedDefault = await win.hermesDesktop.getConnection('default')diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsindex 50e77cd9ca8..6bf90d445aa 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -13,6 +13,7 @@ import { downloadGatewayMediaFile, resolveMediaPlaybackSrc } from './media'type MutableWindow = Window & {__HERMES_AUTH_REQUIRED__?: boolean__HERMES_BASE_PATH__?: string+ __HERMES_DASHBOARD_PROFILE__?: stringhermesDesktop?: Window['hermesDesktop']}@@ -22,6 +23,7 @@ afterEach(() => {const win = mutableWindow()delete win.__HERMES_AUTH_REQUIRED__delete win.__HERMES_BASE_PATH__+ delete win.__HERMES_DASHBOARD_PROFILE__clearWebappSession()Reflect.deleteProperty(win, 'hermesDesktop')document.documentElement.removeAttribute('data-hermes-desktop-host')@@ -1043,6 +1045,38 @@ describe('browser-hosted Desktop bridge', () => {expect(ws.searchParams.get('profile')).toBe('worker-a')})+ // A tab's own socket answers for the profile the serving gateway was launched as whenever a request+ // names none, as its REST does. So that is the tab's own connection whatever `?profile=` the tab is on;+ // every other profile is reached on that socket with `profile` on each request (sharedPrimary), the+ // route a live switch takes.+ it.each([+ { launch: 'default', other: 'research' },+ { launch: 'work', other: 'default' }+ ])("keeps the $launch launch profile as the tab's own connection on ?profile=$other", async ({ launch, other }) => {+ const win = mutableWindow()+ win.__HERMES_DASHBOARD_PROFILE__ = launch+ seedWebappSession('served-token')+ window.history.replaceState(null, '', `/?profile=${other}#/`)+ const fetchMock = vi.fn(async (_url: URL) => new Response(JSON.stringify({ ticket: 'one-use' }), { status: 200 }))+ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)+ const desktop = win.hermesDesktop!++ const own = await desktop.getConnection()+ expect(own.profile).toBeUndefined()+ expect(own.sharedPrimary).toBeFalsy()+ expect(new URL(own.wsUrl).searchParams.has('profile')).toBe(false)+ await resolveDesktopGatewayWsUrl(desktop, own)+ const mint = new URL(String(fetchMock.mock.calls[0][0]))+ expect(mint.pathname).toBe('/api/webapp/socket-ticket')+ expect(mint.searchParams.get('socket')).toBe('gateway')+ expect(mint.searchParams.has('profile')).toBe(false)++ await expect(desktop.getConnection(other)).resolves.toMatchObject({ profile: other, sharedPrimary: true })+ await expect(desktop.getConnection(launch)).resolves.toMatchObject({ profile: launch, sharedPrimary: false })+ })+// The serving gateway mints the ticket itself, so there is no gateway to start and no verdict to// translate: a failed mint is reported as the route answered it.it("reports a failed mint as the route's own answer", async () => {diff --git a/apps/desktop/src/lib/browser-launch-session.test.ts b/apps/desktop/src/lib/browser-launch-session.test.tsindex 410be652f1e..602f44095fc 100644--- a/apps/desktop/src/lib/browser-launch-session.test.ts+++ b/apps/desktop/src/lib/browser-launch-session.test.ts@@ -64,11 +64,12 @@ it('uses one private session for REST, RPC and terminal across reload without lo// RPC: the gateway socket's one-use ticket is minted over REST with the same private session;// the session token itself never rides a socket URL.expect(new URL((await desktop.getConnection()).wsUrl).searchParams.has('token')).toBe(false)- // As the boot dial does (resolveGatewayWsUrl): mint for the descriptor's own profile.+ // As the boot dial does (resolveGatewayWsUrl): mint for the tab's own socket, which names no+ // profile; the tab's `?profile=coder` is selected on top of it once connected.const rpc = await desktop.getGatewayWsUrl((await desktop.getConnection()).profile)const rpcUrl = new URL(typeof rpc === 'string' ? rpc : rpc.ok ? rpc.wsUrl : '')expect(rpcUrl.searchParams.get('ticket')).toBe('rpc-ticket')- expect(rpcUrl.searchParams.get('profile')).toBe('coder')+ expect(rpcUrl.searchParams.has('profile')).toBe(false)const mintFor = (socket: string) =>fetchMock.mock.calls.find(diff --git a/apps/desktop/src/lib/platform.ts b/apps/desktop/src/lib/platform.tsindex 435d7ba2501..5179f1ccfaf 100644--- a/apps/desktop/src/lib/platform.ts+++ b/apps/desktop/src/lib/platform.ts@@ -25,9 +25,19 @@ export const isLinuxPlatform = (): boolean =>export interface BrowserHostGlobals {__HERMES_AUTH_REQUIRED__?: boolean__HERMES_BASE_PATH__?: string+ __HERMES_DASHBOARD_PROFILE__?: string__HERMES_UI_SURFACE__?: string}+/**+ * The profile the server that served this page runs as: its gateway socket and its REST answer for+ * this profile when a request names none. Empty when the server cannot name its own home (a custom+ * HERMES_HOME), which the browser host reads as `default`.+ */+export function browserLaunchProfile(): string {+ return String((window as Window & BrowserHostGlobals).__HERMES_DASHBOARD_PROFILE__ ?? '').trim()+}+/*** The server served this page as the browser-hosted Desktop: a gated host* (cookie auth) or the Webapp surface (its session arrives by launch link).diff --git a/apps/desktop/src/store/profile-select-webapp.test.ts b/apps/desktop/src/store/profile-select-webapp.test.tsindex fe73d532d52..8cea74176e2 100644--- a/apps/desktop/src/store/profile-select-webapp.test.ts+++ b/apps/desktop/src/store/profile-select-webapp.test.ts@@ -6,8 +6,9 @@ import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'// A live profile switch in a Webapp tab is recorded in THAT tab's URL, so a// reload lands on the profile the user is in, and a generic New session// follows it. It is not the origin's saved default (only "Set as default"-// writes that), no other tab hears about it, and the tab's own backend — the-// one its primary socket reconnects to — stays the profile it booted on.+// writes that), no other tab hears about it, and the tab's own socket — the+// one boot and every reconnect dial — stays the one its gateway answers for+// the profile it runs as; the URL's profile is selected on top of it.const ensureGatewayForProfile = vi.fn(async (_profile: string) => undefined)const ensureGatewayForAgent = vi.fn(async (_connectionId: null | string, _profile: string) => true)@@ -75,6 +76,8 @@ it.each([expect(window.location.hash).toBe('#/')await expect(window.hermesDesktop.profile.getDefault()).resolves.toEqual(savedDefault)expect(defaultChanged).not.toHaveBeenCalled()- await expect(window.hermesDesktop.getConnection()).resolves.toMatchObject({ profile: 'arrived' })+ const own = await window.hermesDesktop.getConnection()+ expect(own.profile).toBeUndefined()+ expect(own.sharedPrimary).toBe(false)unsubscribe()})