The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): cache the served profile set and refuse unserved dials
Adolaniumad03c02014b9
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.tsxindex a942af72720..5e5cd427e7e 100644--- 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.tsx@@ -4,7 +4,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'import { $desktopBoot } from '@/store/boot'import { closeSecondaryGateways, isActivePrimary, requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'-import { $activeGatewayProfile } from '@/store/profile'+import { $activeGatewayProfile, ensureGatewayProfile } from '@/store/profile'import { $connection, $gatewayState } from '@/store/session'import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'@@ -54,6 +54,10 @@ function closeSurvivor() {const originalWebSocket = globalThis.WebSocketconst mints: URL[] = []+// What the gateway reports: every installed profile on /api/profiles, the ones it serves on+// /api/status (null: a backend that does not report the set).+let installed: string[] = []+let served: null | string[] = nullconst frames: { method?: string; params?: Record<string, unknown> }[] = []async function flush() {@@ -93,6 +97,8 @@ beforeEach(() => {$connection.set(null)mints.length = 0frames.length = 0+ installed = ['default', 'research']+ served = nullvi.useFakeTimers()FakeWebSocket.mode = 'open'FakeWebSocket.instances = []@@ -110,7 +116,11 @@ beforeEach(() => {return new Response(JSON.stringify({ ticket: `ticket-${mints.length}` }), { status: 200 })}- return new Response(JSON.stringify({ profiles: [{ name: 'default' }, { name: 'research' }] }), { status: 200 })+ if (url.pathname.endsWith('/api/status')) {+ return new Response(JSON.stringify({ gateway_running: true, gateway_shared_with: served }), { status: 200 })+ }++ return new Response(JSON.stringify({ profiles: installed.map(name => ({ name })) }), { status: 200 })}))$gatewayState.set('idle')@@ -193,3 +203,27 @@ it("a tab loaded on a profile the gateway no longer has stays on the gateway's o// A reload lands on the profile the tab is really on, not on the stale link's.expect(new URLSearchParams(window.location.search).get('profile')).toBe('default')})++it("a tab loaded on a profile its gateway does not serve stays on the gateway's own", async () => {+ installed = ['default', 'research', 'solo']+ served = ['default', 'research']+ await bootWebappTab('/?profile=solo#/')++ expect($activeGatewayProfile.get()).toBe('default')+ expect(new URLSearchParams(window.location.search).get('profile')).toBe('default')+ expect(FakeWebSocket.instances).toHaveLength(1)+})++it('picking a profile the gateway does not serve is refused with the reason and dials nothing', async () => {+ installed = ['default', 'research', 'solo']+ served = ['default', 'research']+ await bootWebappTab('/?profile=research#/')+ expect($activeGatewayProfile.get()).toBe('research')++ await expect(ensureGatewayProfile('solo')).rejects.toThrow(+ 'This gateway does not serve profile "solo", so this tab cannot open it.'+ )+ expect($activeGatewayProfile.get()).toBe('research')+ expect(FakeWebSocket.instances).toHaveLength(1)+ 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 89b13e5b1ae..1b198647370 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -184,11 +184,11 @@ async function openWebappTabProfile(desktop: Window['hermesDesktop'], primary: sreturn}- // A stale link or bookmark can name a profile this gateway no longer has: stay on the gateway's own.+ // A stale link or bookmark can name a profile this gateway no longer has or does not serve: stay on its own.const routes = await desktop.getProfileRoutes?.([profile]).catch(() => null)if (routes && !routes.some(route => normalizeProfileKey(route.profile) === normalizeProfileKey(profile))) {- console.warn(`[gateway] this gateway has no profile "${profile}"; this tab stays on "${primary}"`)+ console.warn(`[gateway] this gateway does not serve profile "${profile}"; this tab stays on "${primary}"`)await desktop.profile?.remember?.(primary)returndiff --git a/apps/desktop/src/lib/browser-bridge-stubs.ts b/apps/desktop/src/lib/browser-bridge-stubs.tsindex 831c5d4bf2c..f21b0ffa41e 100644--- a/apps/desktop/src/lib/browser-bridge-stubs.ts+++ b/apps/desktop/src/lib/browser-bridge-stubs.ts@@ -89,7 +89,6 @@ export const BROWSER_BRIDGE_STUBS = {}),repairBootstrap: async () => ({ ok: true }),resetBootstrap: async () => ({ ok: true }),- revalidateConnection: async () => ({ ok: true, rebuilt: false }),saveConnectionConfig: async () => {throw browserUnsupported('Gateway reconfiguration')},diff --git a/apps/desktop/src/lib/browser-connection.ts b/apps/desktop/src/lib/browser-connection.tsindex cce55c498da..8d0e3d3a17f 100644--- a/apps/desktop/src/lib/browser-connection.ts+++ b/apps/desktop/src/lib/browser-connection.ts@@ -2,6 +2,7 @@ import { LOCAL_CONNECTION_ID } from '@hermes/shared'import type { HermesApiRequest, HermesConnection } from '@/global'import { webappSignInRequired } from '@/lib/browser-launch-session'+import { createServedProfiles } from '@/lib/browser-served-profiles'import {type AudioSocketPath,type BrowserBootstrap,@@ -11,7 +12,7 @@ import {navigateToBrowserLogin,ticketedWebsocketUrl} from '@/lib/browser-transport'-import { browserLaunchProfile, browserLaunchProfileOrDefault } from '@/lib/platform'+import { browserLaunchProfileOrDefault } from '@/lib/platform'/** The serving origin is the only connection a browser-hosted Desktop has. */export function requireBrowserConnection(connectionId?: null | string): void {@@ -23,27 +24,15 @@ 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 name is only a candidate; callers still consult the served set.+// none, as its REST does. Any other profile it serves rides that socket with `profile` on every+// request.function ridesWithProfile(profile?: null | string): boolean {const name = profile?.trim()return Boolean(name) && name !== browserLaunchProfileOrDefault()}-function profileKey(profile?: null | string): string {- return profile?.trim().toLowerCase() || 'default'-}--function launchProfileKey(): string {- return profileKey(browserLaunchProfile())-}--// `served === null` is an unreported set: an older backend, or a status read that failed.-function servedHere(profile: string | null | undefined, served: Set<string> | null): boolean {- return served === null || served.has(profileKey(profile))-}--function connectionFor(bootstrap: BrowserBootstrap, profile?: null | string): HermesConnection {+function connectionFor(bootstrap: BrowserBootstrap, profile: null | string | undefined, servedHere: boolean): HermesConnection {if (!bootstrap.authRequired && !bootstrap.token) {throw webappSignInRequired()}const baseUrl = `${window.location.origin}${bootstrap.basePath}`@@ -58,7 +47,7 @@ function connectionFor(bootstrap: BrowserBootstrap, profile?: null | string): Heprofile: profile || undefined,remoteHost: window.location.host,remoteKind: 'url',- sharedPrimary: ridesWithProfile(profile),+ sharedPrimary: ridesWithProfile(profile) && servedHere,source: 'settings',token: bootstrap.token,windowButtonPosition: null,@@ -108,9 +97,20 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect| 'getProfileRoutes'| 'oauthLoginConnectionConfig'| 'oauthLogoutConnectionConfig'+ | 'revalidateConnection'| 'testConnectionConfig'> {+ const served = createServedProfiles(api)++ // The gateway's own profile, or another one it serves: the only profiles this tab's socket reaches.+ const reachesSocket = (profile?: null | string) => !ridesWithProfile(profile) || served.serves(profile)+const getGatewayWsUrl = async (profile?: null | string) => {+ // Its ticket would mint, then the gateway would close the dial (4403) without a reason to show.+ if (!reachesSocket(profile)) {+ throw new Error(`This gateway does not serve profile "${profile?.trim()}", so this tab cannot open it.`)+ }+try {return {ok: true as const,@@ -135,43 +135,17 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectreturn [...new Set((result.profiles || []).map(profile => String(profile.name || '').trim()).filter(Boolean))]}- // Missing gateway_shared_with is an older backend that does not report its served set, so- // installed profiles stay reachable. An empty list is a gateway that serves only the profile- // it was launched as. A failed read is the same unknown case: a status blip must not empty- // the roster.- const servedProfileKeys = async (): Promise<Set<string> | null> => {- try {- const status = await api<{ gateway_shared_with?: string[] | null }>({ path: '/api/status' })- const shared = status?.gateway_shared_with-- if (!Array.isArray(shared)) {- return null- }-- const names = new Set(shared.map(name => profileKey(String(name))))- names.add(launchProfileKey())-- return names- } catch {- return null- }- }-- const profilesThisGatewayServes = async () => {+ // Every installed profile, with the served set brought up to date for that list.+ const installedProfiles = async () => {const profiles = await getProfiles()- const served = await servedProfileKeys()-- if (!served) {- return profiles- }+ await served.refresh(profiles)- return profiles.filter(name => served.has(profileKey(name)))+ return profiles}return {getAgentRoster: async () => {- const profiles = await getProfiles()- const served = await servedProfileKeys()+ const profiles = await installedProfiles()const connectionLabel = window.location.hostreturn {@@ -182,7 +156,8 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnecthandle: profile === 'default' ? 'hermes' : profile,profile,targetProfile: profile,- ...(served && !served.has(profileKey(profile)) ? { reachable: false as const } : {})+ // Installed here, so listed, but served elsewhere or nowhere.+ ...(reachesSocket(profile) ? {} : { reachable: false as const })})),primaryConnectionId: LOCAL_CONNECTION_ID,sources: [{@@ -203,39 +178,24 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectreturn ticketedWebsocketUrl(bootstrap, payload.path, payload.profile)},- // Without a profile: the tab's own socket, the one boot and every reconnect dial. A named- // profile this gateway serves, other than its own, is a view of that same socket- // (sharedPrimary), so its requests carry `profile`.- getConnection: async (profile?: null | string) => {- const connection = {- ...connectionFor(bootstrap, profile),- connectionId: LOCAL_CONNECTION_ID- }-- if (connection.sharedPrimary !== true) {- return connection- }-- const served = await servedProfileKeys()-- return {- ...connection,- sharedPrimary: servedHere(profile, served)- }- },+ // Without a profile: the tab's own socket, the one boot and every reconnect dial, whatever+ // profile the tab is on. A named profile the gateway serves, other than its own, is a view of+ // that same socket (sharedPrimary), so its requests carry `profile`. Routing reads the cached+ // served set and never fetches it.+ getConnection: async (profile?: null | string) => ({+ ...connectionFor(bootstrap, profile, served.serves(profile)),+ connectionId: LOCAL_CONNECTION_ID+ }),getConnectionConfig: async (profile?: null | string) => browserConnectionConfig(bootstrap, profile),getConnectionFor: async (payload: { connectionId?: null | string; profile?: null | string }) => {requireBrowserConnection(payload.connectionId)- const named = Boolean(payload.profile)- const served = named ? await servedProfileKeys() : null-return {- ...connectionFor(bootstrap, payload.profile),+ ...connectionFor(bootstrap, payload.profile, served.serves(payload.profile)),connectionId: LOCAL_CONNECTION_ID,registryScoped: true,sharedPrimary: false,- sharedRemote: named && servedHere(payload.profile, served)+ sharedRemote: Boolean(payload.profile) && reachesSocket(payload.profile)}},getGatewayWsUrl,@@ -245,7 +205,7 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectreturn getGatewayWsUrl(payload.profile)},getProfileRoutes: async (profiles: string[]) => {- const available = new Set(await profilesThisGatewayServes())+ const available = new Set((await installedProfiles()).filter(reachesSocket))return [...new Set(profiles.map(profile => profile.trim() || 'default'))].filter(profile => available.has(profile))@@ -278,6 +238,12 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectreturn { connected: false, ok: true }},+ // Runs before every redial of the tab's socket: a gateway that restarted may serve another set.+ revalidateConnection: async () => {+ served.invalidate()++ return { ok: true, rebuilt: false }+ },testConnectionConfig: async () => ({baseUrl: `${window.location.origin}${bootstrap.basePath}`,ok: true,diff --git a/apps/desktop/src/lib/browser-desktop-bridge-served-profiles.test.ts b/apps/desktop/src/lib/browser-desktop-bridge-served-profiles.test.tsnew file mode 100644index 00000000000..a08d41c2789--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge-served-profiles.test.ts@@ -0,0 +1,238 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { resolveDesktopGatewayWsUrl } from './gateway-ws-url'++type ServedWindow = Window & { __HERMES_DASHBOARD_PROFILE__?: string; hermesDesktop?: Window['hermesDesktop'] }++const win = window as unknown as ServedWindow++// One gateway's answers: `/api/profiles` lists every installed profile, `/api/status` names the+// ones this process serves. Tests mutate it to change what the gateway reports.+interface Gateway {+ profiles: string[]+ status: (init?: RequestInit) => Promise<Response> | Response+}++function stubGateway(gateway: Gateway) {+ const fetchMock = vi.fn(async (url: URL, init?: RequestInit) => {+ if (url.pathname.endsWith('/api/status')) {+ return gateway.status(init)+ }++ const body = url.pathname.endsWith('/api/webapp/socket-ticket')+ ? { ticket: 'one-use' }+ : { profiles: gateway.profiles.map(name => ({ name })) }++ return new Response(JSON.stringify(body), { status: 200 })+ })++ vi.stubGlobal('fetch', fetchMock)++ return fetchMock+}++const reports = (shared: null | string[]) => () =>+ new Response(JSON.stringify({ gateway_running: true, gateway_shared_with: shared }), { status: 200 })++const callsTo = (fetchMock: ReturnType<typeof stubGateway>, path: string) =>+ fetchMock.mock.calls.filter(([url]) => url.pathname.endsWith(path)).length++function installServedBridge(launchProfile = 'default') {+ win.__HERMES_DASHBOARD_PROFILE__ = launchProfile+ seedWebappSession('served-token')+ expect(installBrowserDesktopBridge()).toBe(true)++ return win.hermesDesktop!+}++afterEach(() => {+ delete win.__HERMES_DASHBOARD_PROFILE__+ clearWebappSession()+ Reflect.deleteProperty(win, 'hermesDesktop')+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ $connection.set(null)+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('profiles the serving gateway does not serve', () => {+ it('lists them on the roster as unreachable and routes none of them over the tab socket', async () => {+ stubGateway({ profiles: ['default', 'research', 'solo'], status: reports(['default', 'research']) })+ const desktop = installServedBridge()++ await expect(desktop.getProfileRoutes?.(['default', 'research', 'solo'])).resolves.toEqual([+ { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },+ { connectionId: 'local', mode: 'local', profile: 'research', targetProfile: 'research' }+ ])++ const roster = await desktop.getAgentRoster?.()+ expect(roster?.sources).toEqual([expect.objectContaining({ connectionId: 'local', kind: 'local', reachable: true })])+ expect(roster?.agents.find(agent => agent.profile === 'research')).toEqual(expect.not.objectContaining({ reachable: false }))+ expect(roster?.agents.find(agent => agent.profile === 'solo')).toMatchObject({+ connectionId: 'local',+ profile: 'solo',+ reachable: false+ })++ await expect(desktop.getConnection('research')).resolves.toMatchObject({ profile: 'research', sharedPrimary: true })+ await expect(desktop.getConnection('solo')).resolves.toMatchObject({ profile: 'solo', sharedPrimary: false })+ await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'research' })).resolves.toMatchObject({+ sharedRemote: true+ })+ await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'solo' })).resolves.toMatchObject({+ sharedPrimary: false,+ sharedRemote: false+ })+ })++ it('reads an empty served list as a gateway that serves only the profile it runs as', async () => {+ stubGateway({ profiles: ['default', 'research'], status: reports([]) })+ const desktop = installServedBridge('research')++ await expect(desktop.getProfileRoutes?.(['default', 'research'])).resolves.toEqual([+ { connectionId: 'local', mode: 'local', profile: 'research', targetProfile: 'research' }+ ])++ const roster = await desktop.getAgentRoster?.()+ expect(roster?.agents.find(agent => agent.profile === 'research')).toEqual(expect.not.objectContaining({ reachable: false }))+ expect(roster?.agents.find(agent => agent.profile === 'default')?.reachable).toBe(false)+ await expect(desktop.getConnection('default')).resolves.toMatchObject({ sharedPrimary: false })+ await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'default' })).resolves.toMatchObject({+ sharedRemote: false+ })+ await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'research' })).resolves.toMatchObject({+ sharedRemote: true+ })+ })++ it('keeps every installed profile reachable when the gateway does not report its served set', async () => {+ stubGateway({ profiles: ['default', 'research'], status: reports(null) })+ const desktop = installServedBridge()++ await expect(desktop.getProfileRoutes?.(['default', 'research'])).resolves.toHaveLength(2)+ const roster = await desktop.getAgentRoster?.()+ expect(roster?.agents.every(agent => agent.reachable !== false)).toBe(true)+ await expect(desktop.getConnection('research')).resolves.toMatchObject({ sharedPrimary: true })+ await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'research' })).resolves.toMatchObject({+ sharedRemote: true+ })+ })++ it('refuses a dial to one with the reason, before minting a ticket the gateway would reject', async () => {+ const fetchMock = stubGateway({ profiles: ['default', 'research', 'solo'], status: reports(['default', 'research']) })+ const desktop = installServedBridge()+ await desktop.getProfileRoutes?.(['solo'])++ const refusal = 'This gateway does not serve profile "solo", so this tab cannot open it.'+ await expect(resolveDesktopGatewayWsUrl(desktop, await desktop.getConnection('solo'))).rejects.toThrow(refusal)+ await expect(+ resolveDesktopGatewayWsUrl(desktop, await desktop.getConnectionFor!({ connectionId: 'local', profile: 'solo' }))+ ).rejects.toThrow(refusal)+ expect(callsTo(fetchMock, '/api/webapp/socket-ticket')).toBe(0)++ // The tab's own socket and a served profile still mint their tickets.+ await expect(resolveDesktopGatewayWsUrl(desktop, await desktop.getConnection())).resolves.toContain('ticket=one-use')+ await expect(desktop.getGatewayWsUrl('research')).resolves.toMatchObject({ ok: true })+ expect(callsTo(fetchMock, '/api/webapp/socket-ticket')).toBe(2)+ })+})++describe('the served set read', () => {+ it('is never fetched to install the bridge or to route a request', async () => {+ const fetchMock = stubGateway({ profiles: ['default', 'owner'], status: reports(['default']) })+ const desktop = installServedBridge()++ await desktop.getConnection()+ await desktop.getConnection('default')+ await expect(desktop.getConnection('owner')).resolves.toMatchObject({ sharedPrimary: true })+ await desktop.getConnectionFor?.({ connectionId: 'local', profile: 'owner' })+ expect(fetchMock).not.toHaveBeenCalled()++ // Once an inventory read learns the set, routing uses it, still without a request of its own.+ await desktop.getProfileRoutes?.(['owner'])+ const reads = fetchMock.mock.calls.length+ await expect(desktop.getConnection('owner')).resolves.toMatchObject({ sharedPrimary: false })+ await desktop.getConnectionFor?.({ connectionId: 'local', profile: 'owner' })+ expect(fetchMock).toHaveBeenCalledTimes(reads)+ })++ it('is shared by inventory reads until the installed list changes, the gateway reconnects or 30 s pass', async () => {+ const gateway: Gateway = { profiles: ['default', 'research', 'solo'], status: reports(['default', 'research']) }+ const fetchMock = stubGateway(gateway)+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000)+ const desktop = installServedBridge()+ const statusReads = () => callsTo(fetchMock, '/api/status')++ await desktop.getProfileRoutes?.(['research'])+ await desktop.getAgentRoster?.()+ await desktop.getProfileRoutes?.(['solo'])+ expect(statusReads()).toBe(1)++ // A new profile: the multiplexer adopts it before its create returns, so read the set again.+ gateway.profiles = [...gateway.profiles, 'fresh']+ gateway.status = reports(['default', 'research', 'fresh'])+ await expect(desktop.getProfileRoutes?.(['fresh'])).resolves.toHaveLength(1)+ expect(statusReads()).toBe(2)++ // A park or unpark leaves the list alone and shows up on the next read after 30 s.+ gateway.status = reports(['default', 'research', 'fresh', 'solo'])+ now.mockReturnValue(1_029_000)+ await expect(desktop.getProfileRoutes?.(['solo'])).resolves.toEqual([])+ now.mockReturnValue(1_031_000)+ await expect(desktop.getProfileRoutes?.(['solo'])).resolves.toHaveLength(1)+ expect(statusReads()).toBe(3)++ // A gateway that restarted may serve another set.+ gateway.status = reports(['default'])+ await desktop.revalidateConnection()+ await expect(desktop.getProfileRoutes?.(['research'])).resolves.toEqual([])+ expect(statusReads()).toBe(4)+ })++ it('keeps the last answer when a later read fails', async () => {+ const gateway: Gateway = { profiles: ['default', 'research', 'solo'], status: reports(['default', 'research']) }+ stubGateway(gateway)+ const desktop = installServedBridge()++ await desktop.getProfileRoutes?.(['solo'])+ gateway.status = () => new Response('{"detail":"gateway unavailable"}', { status: 503 })+ await desktop.revalidateConnection()++ await expect(desktop.getProfileRoutes?.(['research', 'solo'])).resolves.toEqual([+ { connectionId: 'local', mode: 'local', profile: 'research', targetProfile: 'research' }+ ])+ await expect(desktop.getConnection('solo')).resolves.toMatchObject({ sharedPrimary: false })+ })++ it('holds an inventory read back at most 5 s, then answers as if every profile is served', async () => {+ vi.useFakeTimers()+ stubGateway({+ profiles: ['default', 'solo'],+ // A gateway too busy to answer: only the request's own deadline ends the read.+ status: init =>+ new Promise<Response>((_resolve, reject) =>+ init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))+ )+ })++ const desktop = installServedBridge()+ let routes: unknown = null+ void desktop.getProfileRoutes?.(['default', 'solo']).then(value => (routes = value))++ // Routing does not wait for the read in flight.+ await expect(desktop.getConnection('solo')).resolves.toMatchObject({ sharedPrimary: true })++ await vi.advanceTimersByTimeAsync(4_900)+ expect(routes).toBeNull()+ await vi.advanceTimersByTimeAsync(100)+ expect(routes).toEqual([+ { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },+ { connectionId: 'local', mode: 'local', profile: 'solo', targetProfile: 'solo' }+ ])+ })+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsindex e7e092967ac..850d796d70d 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -454,130 +454,6 @@ describe('browser-hosted Desktop bridge', () => {).rejects.toThrow('No connection with id "another-host"')})- function stubProfileStatus(status: Record<string, unknown>, profiles: { name: string }[]) {- vi.stubGlobal(- 'fetch',- vi.fn().mockImplementation(async (url: URL) => {- const path = url.pathname-- const body = path.endsWith('/api/webapp/socket-ticket')- ? { ticket: 'one-use' }- : path.endsWith('/api/status')- ? status- : { profiles }-- return new Response(JSON.stringify(body), { status: 200 })- })- )- }-- it('does not mark a profile this gateway does not serve as reachable', async () => {- const win = mutableWindow()- win.__HERMES_DASHBOARD_PROFILE__ = 'default'- seedWebappSession('served-token')- stubProfileStatus(- { gateway_running: true, gateway_shared_with: ['default', 'research'] },- [{ name: 'default' }, { name: 'research' }, { name: 'solo' }]- )-- expect(installBrowserDesktopBridge()).toBe(true)- const desktop = win.hermesDesktop!-- await expect(desktop.getProfileRoutes?.(['default', 'research', 'solo'])).resolves.toEqual([- { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },- { connectionId: 'local', mode: 'local', profile: 'research', targetProfile: 'research' }- ])-- const roster = await desktop.getAgentRoster?.()- expect(roster?.sources).toEqual([- expect.objectContaining({ connectionId: 'local', kind: 'local', reachable: true })- ])- expect(roster?.agents.find(agent => agent.profile === 'research')).toEqual(- expect.not.objectContaining({ reachable: false })- )- expect(roster?.agents.find(agent => agent.profile === 'solo')).toMatchObject({- connectionId: 'local',- profile: 'solo',- reachable: false- })-- await expect(desktop.getConnection('research')).resolves.toMatchObject({- profile: 'research',- sharedPrimary: true- })- await expect(desktop.getConnection('solo')).resolves.toMatchObject({- profile: 'solo',- sharedPrimary: false- })- await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'research' })).resolves.toMatchObject({- profile: 'research',- sharedRemote: true- })- await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'solo' })).resolves.toMatchObject({- profile: 'solo',- sharedPrimary: false,- sharedRemote: false- })- })-- it('treats an empty served list as this gateway serving only its own profile', async () => {- const win = mutableWindow()- win.__HERMES_DASHBOARD_PROFILE__ = 'default'- seedWebappSession('served-token')- stubProfileStatus(- { gateway_running: true, gateway_shared_with: [] },- [{ name: 'default' }, { name: 'research' }]- )-- expect(installBrowserDesktopBridge()).toBe(true)- const desktop = win.hermesDesktop!-- await expect(desktop.getProfileRoutes?.(['default', 'research'])).resolves.toEqual([- { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' }- ])- await expect(desktop.getConnection('research')).resolves.toMatchObject({- profile: 'research',- sharedPrimary: false- })- await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'research' })).resolves.toMatchObject({- sharedRemote: false- })-- const roster = await desktop.getAgentRoster?.()- expect(roster?.sources?.[0]?.reachable).toBe(true)- expect(roster?.agents.find(agent => agent.profile === 'default')).toEqual(- expect.not.objectContaining({ reachable: false })- )- expect(roster?.agents.find(agent => agent.profile === 'research')?.reachable).toBe(false)- })-- it('keeps installed profiles reachable when the gateway does not report its served set', async () => {- const win = mutableWindow()- seedWebappSession('served-token')- stubProfileStatus({ gateway_running: true, gateway_shared_with: null }, [- { name: 'default' },- { name: 'research' }- ])-- expect(installBrowserDesktopBridge()).toBe(true)- const desktop = win.hermesDesktop!-- await expect(desktop.getProfileRoutes?.(['default', 'research'])).resolves.toEqual([- { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },- { connectionId: 'local', mode: 'local', profile: 'research', targetProfile: 'research' }- ])- await expect(desktop.getConnection('research')).resolves.toMatchObject({- profile: 'research',- sharedPrimary: true- })- await expect(desktop.getConnectionFor?.({ connectionId: 'local', profile: 'research' })).resolves.toMatchObject({- sharedRemote: true- })- const roster = await desktop.getAgentRoster?.()- expect(roster?.agents.every(agent => agent.reachable !== false)).toBe(true)- expect(roster?.sources?.[0]?.reachable).toBe(true)- })-it('maps REST requests to the loopback API with token and profile scoping', async () => {const win = mutableWindow()win.__HERMES_BASE_PATH__ = '/hermes'@@ -733,12 +609,7 @@ describe('browser-hosted Desktop bridge', () => {$connection.set({ mode: 'remote', profile: 'switched-profile' } as never)await expect(pending).resolves.toMatchObject({ saved: true })- const downloadCall = (fetchMock.mock.calls as [URL, RequestInit][]).find(([input]) =>- input.pathname.endsWith('/api/fs/download')- )-- expect(downloadCall).toBeTruthy()- const [requestUrl, init] = downloadCall!+ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]// The workspace download route native Desktop uses: it reads an SSH-backed profile's files on// that machine, like the file tree that listed them, not a same-named file on the gateway host.expect(requestUrl.pathname).toBe('/hermes/api/fs/download')@@ -805,16 +676,12 @@ describe('browser-hosted Desktop bridge', () => {'https://cdn.example.com/video.mp4')- const ticketCalls = (fetchMock.mock.calls as [URL, RequestInit][]).filter(([input]) =>- input.pathname.endsWith('/api/files/ticket')- )-- for (const [input, init] of ticketCalls) {+ for (const [input, init] of fetchMock.mock.calls as [URL, RequestInit][]) {expect(input.pathname).toBe('/hermes/api/files/ticket')expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe(token)}- expect(ticketCalls).toHaveLength(token ? 5 : 0)+ expect(fetchMock).toHaveBeenCalledTimes(token ? 5 : 0)})it('persists browser image bytes through the existing chat upload API', async () => {@@ -1345,9 +1212,7 @@ describe('browser-hosted Desktop bridge', () => {seedWebappSession('served-token')vi.stubGlobal('fetch',- vi.fn().mockImplementation(- () => new Response('{"detail":"gateway unavailable"}', { status: 503 })- )+ vi.fn().mockResolvedValue(new Response('{"detail":"gateway unavailable"}', { status: 503 })))expect(installBrowserDesktopBridge()).toBe(true)const desktop = win.hermesDesktop!diff --git a/apps/desktop/src/lib/browser-served-profiles.ts b/apps/desktop/src/lib/browser-served-profiles.tsnew file mode 100644index 00000000000..01cc597ef89--- /dev/null+++ b/apps/desktop/src/lib/browser-served-profiles.ts@@ -0,0 +1,73 @@+import type { HermesApiRequest } from '@/global'+import { browserLaunchProfile } from '@/lib/platform'++// The multiplexer applies a park, unpark or standalone change on its 30 s profile rescan, and none+// of those changes the installed list, so a known served set is re-read on that cadence.+const SERVED_SET_TTL_MS = 30_000+// An inventory read waits at most this long for the set, then answers with the set it already has.+const SERVED_SET_READ_TIMEOUT_MS = 5_000++const profileKey = (profile?: null | string) => profile?.trim() || 'default'++/**+ * The profiles the gateway serving this tab answers for. `/api/profiles` lists every installed+ * profile, but the tab's one socket reaches only the gateway's own profile and, on a multiplexer,+ * the rest of its served set (`/api/status` `gateway_shared_with`). A standalone or parked profile,+ * and every other profile of a single-profile gateway, is installed here but not served here.+ *+ * Only an inventory read (`refresh`) fetches the set. Routing reads the cached answer (`serves`)+ * and never waits on the network. Until a gateway reports the set, every installed profile counts+ * as served, which is how the tab treated them before the set was read.+ */+export function createServedProfiles(api: <T>(request: HermesApiRequest) => Promise<T>) {+ let served: null | Set<string> = null+ // The installed list the last read went with. A reconnect clears it so the next read re-reads.+ let readFor: null | string = null+ let readAt = 0+ let pending: null | Promise<void> = null++ const read = async () => {+ try {+ const status = await api<{ gateway_shared_with?: null | string[] }>({+ path: '/api/status',+ timeoutMs: SERVED_SET_READ_TIMEOUT_MS+ })++ const shared = status?.gateway_shared_with++ // Absent on a backend older than the field; [] on a gateway that serves only its own profile.+ served = Array.isArray(shared)+ ? new Set([...shared.map(name => profileKey(String(name))), profileKey(browserLaunchProfile())])+ : null+ } catch {+ // A failed read keeps the last answer: a status blip must not change which profiles are reachable.+ }+ }++ return {+ invalidate: () => {+ readFor = null+ },+ /** Re-read the set when the installed list changed since the last read, or the read is stale. */+ refresh: (installed: string[]): Promise<void> => {+ const key = installed.map(profileKey).sort().join('\n')++ if (pending) {+ return pending+ }++ if (key === readFor && Date.now() - readAt < SERVED_SET_TTL_MS) {+ return Promise.resolve()+ }++ readFor = key+ pending = read().finally(() => {+ readAt = Date.now()+ pending = null+ })++ return pending+ },+ serves: (profile?: null | string) => served === null || served.has(profileKey(profile))+ }+}diff --git a/apps/desktop/src/lib/browser-staged-attachments.test.ts b/apps/desktop/src/lib/browser-staged-attachments.test.tsindex 692c6c60ce7..45ef04ede90 100644--- a/apps/desktop/src/lib/browser-staged-attachments.test.ts+++ b/apps/desktop/src/lib/browser-staged-attachments.test.ts@@ -48,10 +48,6 @@ async function installBrowser(withProvenance = true) {return new Response(JSON.stringify({ dataUrl: 'data:text/plain;base64,cGF5bG9hZA==' }))}- if (url.pathname.endsWith('/api/status')) {- return new Response(JSON.stringify({ gateway_shared_with: null }), { status: 200 })- }-throw new Error(`Unexpected fetch: ${url}`)})@@ -62,10 +58,6 @@ async function installBrowser(withProvenance = true) {return fetchMock}-function transportCalls(fetchMock: { mock: { calls: [RequestInfo | URL, RequestInit?][] } }) {- return fetchMock.mock.calls.filter(([input]) => !String(input).includes('/api/status'))-}-afterEach(() => {cleanup()clearNotifications()@@ -154,9 +146,8 @@ describe('browser staged attachment transport', () => {})expect(result.refText).toBe(refText)expect(result.stagedUpload).toEqual(source)- const calls = transportCalls(fetchMock)- expect(calls).toHaveLength(1)- const [input, init] = calls[0]+ expect(fetchMock).toHaveBeenCalledTimes(1)+ const [input, init] = fetchMock.mock.calls[0]const uploadUrl = new URL(String(input))expect(uploadUrl.pathname).toBe('/api/chat/file-upload')expect(uploadUrl.searchParams.get('profile')).toBe('owner')@@ -192,7 +183,7 @@ describe('browser staged attachment transport', () => {}expect(requestGateway).toHaveBeenCalledTimes(2)- expect(transportCalls(fetchMock)).toHaveLength(1)+ expect(fetchMock).toHaveBeenCalledTimes(1)})it('retains the legacy byte transport when an older upload endpoint supplies only a path', async () => {@@ -205,7 +196,7 @@ describe('browser staged attachment transport', () => {expect(requestGateway).toHaveBeenCalledWith('file.attach', {name: sourceName, path, session_id: 'runtime', data_url: 'data:text/plain;base64,cGF5bG9hZA=='})- expect(transportCalls(fetchMock)).toHaveLength(2)+ expect(fetchMock).toHaveBeenCalledTimes(2)})it('retries a failed attach from the same source without another upload or download', async () => {@@ -222,7 +213,7 @@ describe('browser staged attachment transport', () => {expect(attachment.stagedUpload).toEqual(source)expect(attachment.attachedSessionId).toBeUndefined()await expect(uploadComposerAttachment(attachment, opts)).resolves.toMatchObject({ refText })- expect(transportCalls(fetchMock)).toHaveLength(1)+ expect(fetchMock).toHaveBeenCalledTimes(1)expect(requestGateway.mock.calls.every(([, params]) => params.staged_upload === source)).toBe(true)})@@ -252,7 +243,7 @@ describe('browser staged attachment transport', () => {expect(requestGateway).toHaveBeenLastCalledWith('file.attach', {name: sourceName, session_id: 'new-runtime', staged_upload: source})- expect(transportCalls(fetchMock)).toHaveLength(1)+ expect(fetchMock).toHaveBeenCalledTimes(1)})it.each(['another Hermes backend', 'Profile not found'])(@@ -265,7 +256,7 @@ describe('browser staged attachment transport', () => {remote: true, requestGateway, sessionId: 'runtime'})).rejects.toThrow(message)expect(requestGateway).toHaveBeenCalledTimes(1)- expect(transportCalls(fetchMock)).toHaveLength(1)+ expect(fetchMock).toHaveBeenCalledTimes(1)})diff --git a/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx b/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsxindex ccb54b49c0e..34e575664a8 100644--- a/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx@@ -26,7 +26,17 @@ import { renderHook, waitFor } from '@testing-library/react'import type { ReactNode } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { $botMeta, $lastRoster, botMentionTag, cachedUnionRoster, primeRoster, ROSTER_KEY, useRoster } from './data'+import {+ $botMeta,+ $lastRoster,+ annotateBotSource,+ botMentionTag,+ botSourceStatus,+ cachedUnionRoster,+ primeRoster,+ ROSTER_KEY,+ useRoster+} from './data'import type { RosterRow } from './types'const { hostMock } = vi.hoisted(() => ({@@ -702,7 +712,9 @@ describe('the roster only caches rows from the connection it is keyed under', ()})describe('a profile this gateway does not serve', () => {- it('stays listed and is marked unreachable while served profiles stay reachable', async () => {+ it('stays listed and unavailable, also to the first selection the pane seats', async () => {+ const sources = [{ connectionId: 'local', kind: 'local', reachable: true }]+const rows = await mergedRoster({ profiles: [{ name: 'default' }, { name: 'research' }, { name: 'solo' }] },{@@ -718,13 +730,22 @@ describe('a profile this gateway does not serve', () => {}],primaryConnectionId: 'local',- sources: [{ connectionId: 'local', kind: 'local', reachable: true }]+ sources})expect(rows.map(row => row.name)).toEqual(['default', 'research', 'solo'])expect(rows.find(row => row.name === 'research')?.sourceReachable).toBe(true)expect(rows.find(row => row.name === 'solo')?.sourceReachable).toBe(false)++ // The roster pane annotates each row again with the source snapshot before it seats the first+ // available bot (roster-pane.tsx, reconcileRosterSelection). The source being up must not make+ // the unserved row selectable there.+ const selectable = (rows as RosterRow[])+ .filter(row => botSourceStatus(annotateBotSource(row, sources)).available)+ .map(row => row.name)++ expect(selectable).toEqual(['default', 'research'])})})diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.tsindex 0faa7aeccae..0ac5351c8b3 100644--- a/apps/desktop/src/plugins/hermes-bots/data.ts+++ b/apps/desktop/src/plugins/hermes-bots/data.ts@@ -728,6 +728,12 @@ interface UnionAgentRow {targetProfile?: string}+/** A source can be up and still not serve a profile it lists. Only an explicit+ * `reachable: false` says so: a native roster never sets the field. */+function unservedFlag(agent: UnionAgentRow): Pick<RosterRow, 'unserved'> {+ return agent.reachable === false ? { unserved: true } : {}+}+/** The union roster payload. `primaryConnectionId` is served by Electron but* absent from the SDK's `DesktopAgentRoster`, so the merge reads it here. */interface UnionRoster {@@ -832,12 +838,7 @@ async function fetchRosterSnapshot(activeConnectionId: null | string | undefinedconst merged = mergeMultiSourceRoster(local, union, activeConnectionId, previous)const sources = Array.isArray(union?.sources) ? union.sources : []traceRosterSnapshot(local, sources, activeConnectionId, merged?.profiles || [])-- const profiles = applyUnservedAgents(- (merged?.profiles || []).map(row => annotateBotSource(row, sources)),- Array.isArray(union?.agents) ? union.agents : []- )-+ const profiles = (merged?.profiles || []).map(row => annotateBotSource(row, sources))await reconcileBotMeta(profiles, issuedAt)return {@@ -1086,6 +1087,7 @@ export function mergeMultiSourceRoster(targetProfile: agent.targetProfile || profile}row.sourceScoped = true+ Object.assign(row, unservedFlag(agent))continue}@@ -1114,7 +1116,8 @@ export function mergeMultiSourceRoster(targetProfile: agent.targetProfile || profile},remoteSource: true,- sourceScoped: true+ sourceScoped: true,+ ...unservedFlag(agent)})}@@ -1497,31 +1500,9 @@ export function sourceByConnection(sources: GatewaySource[] | null | undefined):)}-/** A source can be up and still not serve a profile. Those rows stay listed.- * Absence is not that signal: a native roster omits the field, and one poll- * can list a profile on only one of the two inventories. */-export function applyUnservedAgents(- rows: RosterRow[],- agents: { connectionId?: string; profile?: string; reachable?: boolean }[]-): RosterRow[] {- const unserved = new Set(- agents- .filter(agent => agent.reachable === false)- .map(agent => `${String(agent.connectionId || '').trim()}::${String(agent.profile || '').trim()}`)- )-- if (unserved.size === 0) {- return rows- }-- return rows.map(row =>- unserved.has(`${String(row.connectionId || '').trim()}::${String(row.name || '').trim()}`)- ? { ...row, sourceReachable: false }- : row- )-}--/** Copy current source health onto a row without changing its owner. */+/** Copy current source health onto a row without changing its owner. A row+ * its source lists but does not serve stays unreachable while the source is+ * up: the pane re-annotates rows before seating a first selection. */export function annotateBotSource(bot: RosterRow, sources: GatewaySource[] | null | undefined): RosterRow {const id = String(bot?.connectionId || '').trim()@@ -1549,7 +1530,7 @@ export function annotateBotSource(bot: RosterRow, sources: GatewaySource[] | nul...(source.installId ? { installId: source.installId } : {}),sourceError: source.error || null,sourceMissing: false,- sourceReachable: source.reachable+ sourceReachable: source.reachable && !bot.unserved}}diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.tsindex 860445748c4..afff6f7da14 100644--- a/apps/desktop/src/plugins/hermes-bots/types.ts+++ b/apps/desktop/src/plugins/hermes-bots/types.ts@@ -120,6 +120,9 @@ export interface RosterRow {sourceReachable?: boolean | nullsourceScoped?: booleantargetProfile?: string+ /** Its source lists this profile but does not serve it (the Webapp's gateway+ * lists every installed profile and reaches only those it serves). */+ unserved?: boolean/** Nullable: the gateway sends `null` for a profile with no configured role,* and the create form threads its own optional title through the same shape. */title?: null | string