The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): refresh the served set before a pick routes a profile it lacks
unsupportedpastels562d95142c38
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 35a2a8620ea..70062a69e9c 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -82,6 +82,10 @@ declare global {// remote cache was dropped.revalidateConnection: () => Promise<{ ok: boolean; rebuilt: boolean }>getGatewayWsUrl: (profile?: null | string) => Promise<GatewayWsUrlResult>+ // Browser host only: before a pick routes `profile`, re-read the served+ // set when its cached answer does not serve that profile. Bounded, and+ // never rejects: on a timeout or failure the cached set stands.+ refreshServedProfile?: (profile: string) => Promise<void>// Open (or focus) a standalone OS window for a single chat session so// the user can work with multiple chats side by side. Returns ok:false// with an error code when the sessionId is empty/invalid. `watch` opensdiff --git a/apps/desktop/src/lib/browser-connection.ts b/apps/desktop/src/lib/browser-connection.tsindex 10e6d0f9839..34018a4d03b 100644--- a/apps/desktop/src/lib/browser-connection.ts+++ b/apps/desktop/src/lib/browser-connection.ts@@ -14,6 +14,12 @@ import {} from '@/lib/browser-transport'import { browserLaunchProfileOrDefault } from '@/lib/platform'+// A pick waits at most this long for the served set before routing on the set it has: one+// `/api/profiles` read, then a `/api/status` read capped at the same 5 s. It sits well under the+// store's 20 s budget for a dial's URL, so a stalled gateway costs a pick 5 s and a profile that+// stays unserved is still refused and parked rather than timed out and redialed.+const SERVED_PROFILE_REFRESH_TIMEOUT_MS = 5_000+/** The serving origin is the only connection a browser-hosted Desktop has. */export function requireBrowserConnection(connectionId?: null | string): void {const requested = connectionId?.trim() || LOCAL_CONNECTION_ID@@ -97,6 +103,7 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect| 'getProfileRoutes'| 'oauthLoginConnectionConfig'| 'oauthLogoutConnectionConfig'+ | 'refreshServedProfile'| 'revalidateConnection'| 'testConnectionConfig'> {@@ -238,6 +245,27 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectreturn { connected: false, ok: true }},+ // A profile created since the last inventory read is missing from the cached set, though the+ // multiplexer adopted it before its create returned. Selection reads the inventory once before+ // it routes, so the profile rides the tab's socket; dials keep reading the cache alone.+ refreshServedProfile: async (profile: string) => {+ if (reachesSocket(profile)) {+ return+ }++ let timer: ReturnType<typeof setTimeout> | undefined++ await Promise.race([+ installedProfiles().then(+ () => undefined,+ () => undefined+ ),+ new Promise<void>(resolve => {+ timer = setTimeout(resolve, SERVED_PROFILE_REFRESH_TIMEOUT_MS)+ })+ ])+ clearTimeout(timer)+ },// Runs before every redial of the tab's socket: a gateway that restarted may serve another set.revalidateConnection: async () => {served.invalidate()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.tsindex 5388f2573e4..4a124ba0360 100644--- a/apps/desktop/src/lib/browser-desktop-bridge-served-profiles.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge-served-profiles.test.ts@@ -157,6 +157,30 @@ describe('profiles the serving gateway does not serve', () => {})})+describe('the served set refresh before a pick', () => {+ it('reads the inventory only for a profile the cached set does not serve', async () => {+ const gateway: Gateway = { profiles: ['default', 'solo'], status: reports(['default']) }+ const fetchMock = stubGateway(gateway)+ const desktop = installServedBridge()+ await desktop.getProfileRoutes?.(['solo'])+ const reads = fetchMock.mock.calls.length++ await desktop.refreshServedProfile?.('default')+ expect(fetchMock).toHaveBeenCalledTimes(reads)++ gateway.profiles = [...gateway.profiles, 'fresh']+ gateway.status = reports(['default', 'fresh'])+ await desktop.refreshServedProfile?.('fresh')+ await expect(desktop.getConnection('fresh')).resolves.toMatchObject({ sharedPrimary: true })+ await expect(desktop.getGatewayWsUrl('fresh')).resolves.toMatchObject({ ok: true })++ // Served now, so a second pick reads nothing.+ const after = fetchMock.mock.calls.length+ await desktop.refreshServedProfile?.('fresh')+ expect(fetchMock).toHaveBeenCalledTimes(after)+ })+})+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']) })diff --git a/apps/desktop/src/store/profile-select-webapp-served.test.ts b/apps/desktop/src/store/profile-select-webapp-served.test.tsnew file mode 100644index 00000000000..b1b8009b9ba--- /dev/null+++ b/apps/desktop/src/store/profile-select-webapp-served.test.ts@@ -0,0 +1,140 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'+import { UnservedProfileError } from '@/lib/browser-served-profiles'+import { $gateway, activeGatewayProfileKey, setPrimaryGateway } from '@/store/gateway'+import { $activeGatewayProfile, ensureGatewayProfile } from '@/store/profile'+import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++// Every socket the store builds besides the tab's own (the primary each test installs).+const sockets: Array<{ connect: ReturnType<typeof vi.fn> }> = []++vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ HermesGateway: class {+ connectionState = 'closed'+ connect = vi.fn(async () => {+ this.connectionState = 'open'+ })+ request = vi.fn(async () => ({}))+ close = vi.fn()+ onEvent = vi.fn(() => () => {})+ onState = vi.fn(() => () => {})++ constructor() {+ sockets.push(this)+ }+ }+}))++type ServedWindow = Window & { __HERMES_DASHBOARD_PROFILE__?: string; hermesDesktop?: Window['hermesDesktop'] }++const win = window as unknown as ServedWindow++// One multiplexer: `/api/profiles` lists every installed profile, `/api/status` the ones it serves.+// `holdProfiles` leaves every `/api/profiles` read unanswered until its own deadline aborts it.+interface Gateway {+ holdProfiles?: boolean+ profiles: string[]+ served: string[]+}++function stubGateway(gateway: Gateway) {+ const fetchMock = vi.fn(async (url: URL, init?: RequestInit) => {+ if (url.pathname.endsWith('/api/status')) {+ return new Response(JSON.stringify({ gateway_running: true, gateway_shared_with: gateway.served }), { status: 200 })+ }++ if (url.pathname.endsWith('/api/webapp/socket-ticket')) {+ return new Response(JSON.stringify({ ticket: 'one-use' }), { status: 200 })+ }++ if (gateway.holdProfiles) {+ return new Promise<Response>((_resolve, reject) =>+ init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))+ )+ }++ return new Response(JSON.stringify({ profiles: gateway.profiles.map(name => ({ name })) }), { status: 200 })+ })++ vi.stubGlobal('fetch', fetchMock)++ return fetchMock+}++const callsTo = (fetchMock: ReturnType<typeof stubGateway>, path: string) =>+ fetchMock.mock.calls.filter(([url]) => url.pathname.endsWith(path)).length++// The tab's bridge, its served set already read once (as the profile rail's inventory read does),+// and the tab's own socket open as the primary.+async function openTab(gateway: Gateway) {+ const fetchMock = stubGateway(gateway)+ win.__HERMES_DASHBOARD_PROFILE__ = 'default'+ seedWebappSession('served-token')+ expect(installBrowserDesktopBridge()).toBe(true)+ await win.hermesDesktop!.getProfileRoutes?.(gateway.profiles)++ const primary = { connectionState: 'open', request: vi.fn(async () => ({})) }+ setPrimaryGateway(primary as never, 'default')++ return { fetchMock, primary }+}++afterEach(() => {+ delete win.__HERMES_DASHBOARD_PROFILE__+ clearWebappSession()+ Reflect.deleteProperty(win, 'hermesDesktop')+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('selecting a profile in a Webapp tab', () => {+ it('rides the tab socket for a profile created since the last inventory read', async () => {+ const gateway: Gateway = { profiles: ['default', 'solo'], served: ['default'] }+ const { primary } = await openTab(gateway)+ const built = sockets.length++ // A picker creates the profile and selects it at once: the multiplexer adopted it before the+ // create returned, but the tab's cached set predates it.+ gateway.profiles = [...gateway.profiles, 'fresh']+ gateway.served = ['default', 'fresh']+ await ensureGatewayProfile('fresh')++ expect(sockets).toHaveLength(built)+ expect($gateway.get()).toBe(primary)+ expect(activeGatewayProfileKey()).toBe('default')+ expect($activeGatewayProfile.get()).toBe('fresh')+ expect($connection.get()).toMatchObject({ profile: 'fresh', sharedPrimary: true })+ })++ it('still refuses and parks an unserved profile at once when the inventory read stalls', async () => {+ vi.useFakeTimers()+ const gateway: Gateway = { profiles: ['default', 'solo'], served: ['default'] }+ const { fetchMock } = await openTab(gateway)+ const built = sockets.length++ gateway.holdProfiles = true+ let outcome: unknown = 'pending'+ void ensureGatewayProfile('solo').then(+ () => (outcome = 'activated'),+ (error: unknown) => (outcome = error)+ )++ // The pick waits for the inventory at most 5 s, then routes on the set it has.+ await vi.advanceTimersByTimeAsync(4_900)+ expect(outcome).toBe('pending')+ await vi.advanceTimersByTimeAsync(100)+ expect(outcome).toBeInstanceOf(UnservedProfileError)++ // Parked: nothing redials it, so no ticket is minted and no socket ever connects.+ const reads = callsTo(fetchMock, '/api/profiles')+ await vi.advanceTimersByTimeAsync(120_000)+ expect(callsTo(fetchMock, '/api/profiles')).toBe(reads)+ expect(callsTo(fetchMock, '/api/webapp/socket-ticket')).toBe(0)+ expect(sockets.slice(built).every(socket => socket.connect.mock.calls.length === 0)).toBe(true)+ })+})diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex bdff27e8847..41e2d412c38 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -679,6 +679,12 @@ export async function ensureGatewayProfile($gatewaySwapTarget.set(target)gatewaySwitch = (async () => {+ // A Webapp tab routes on its cached served set, which predates a profile+ // created a moment ago: bring it up to date before either lookup below, so+ // the descriptor and the shared-primary route both see the new profile on+ // the tab's socket. No-op elsewhere, and for a profile the set already has.+ await window.hermesDesktop?.refreshServedProfile?.(target).catch(() => undefined)+// ensureGatewayForProfile opens (or reuses) the target's socket and points// the active gateway at it — without closing the profile you came from.// The descriptor resolves concurrently so nothing awaits between the