Skip to content

The agent that grows with you

fix(webapp): do not mark a standalone profile reachable

Adolaniumb65111aad57f
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index bb69f6cf3e8..35a2a8620ea 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1295,6 +1295,9 @@ export interface DesktopRosterAgent {
profile: string
targetProfile?: string
handle: string
+ // False when this source lists the profile but does not serve it.
+ // Absent means the source's own reachable flag.
+ reachable?: boolean
}
export interface DesktopAgentRoster {
diff --git a/apps/desktop/src/lib/browser-connection.ts b/apps/desktop/src/lib/browser-connection.ts
index fa880424ec3..cce55c498da 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 { browserLaunchProfileOrDefault } from '@/lib/platform'
+import { browserLaunchProfile, browserLaunchProfileOrDefault } from '@/lib/platform'
/** The serving origin is the only connection a browser-hosted Desktop has. */
export function requireBrowserConnection(connectionId?: null | string): void {
@@ -23,13 +23,26 @@ 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.
+// none, as its REST does. Any other name is only a candidate; callers still consult the served set.
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 {
if (!bootstrap.authRequired && !bootstrap.token) {throw webappSignInRequired()}
@@ -122,9 +135,43 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect
return [...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 () => {
+ const profiles = await getProfiles()
+ const served = await servedProfileKeys()
+
+ if (!served) {
+ return profiles
+ }
+
+ return profiles.filter(name => served.has(profileKey(name)))
+ }
+
return {
getAgentRoster: async () => {
const profiles = await getProfiles()
+ const served = await servedProfileKeys()
const connectionLabel = window.location.host
return {
@@ -134,7 +181,8 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect
connectionLabel,
handle: profile === 'default' ? 'hermes' : profile,
profile,
- targetProfile: profile
+ targetProfile: profile,
+ ...(served && !served.has(profileKey(profile)) ? { reachable: false as const } : {})
})),
primaryConnectionId: LOCAL_CONNECTION_ID,
sources: [{
@@ -155,23 +203,39 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect
return ticketedWebsocketUrl(bootstrap, payload.path, payload.profile)
},
- // 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
- }),
+ // 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)
+ }
+ },
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),
connectionId: LOCAL_CONNECTION_ID,
registryScoped: true,
sharedPrimary: false,
- sharedRemote: Boolean(payload.profile)
+ sharedRemote: named && servedHere(payload.profile, served)
}
},
getGatewayWsUrl,
@@ -181,7 +245,7 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect
return getGatewayWsUrl(payload.profile)
},
getProfileRoutes: async (profiles: string[]) => {
- const available = new Set(await getProfiles())
+ const available = new Set(await profilesThisGatewayServes())
return [...new Set(profiles.map(profile => profile.trim() || 'default'))]
.filter(profile => available.has(profile))
diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.ts
index 850d796d70d..e7e092967ac 100644
--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts
+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts
@@ -454,6 +454,130 @@ 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'
@@ -609,7 +733,12 @@ describe('browser-hosted Desktop bridge', () => {
$connection.set({ mode: 'remote', profile: 'switched-profile' } as never)
await expect(pending).resolves.toMatchObject({ saved: true })
- const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]
+ const downloadCall = (fetchMock.mock.calls as [URL, RequestInit][]).find(([input]) =>
+ input.pathname.endsWith('/api/fs/download')
+ )
+
+ expect(downloadCall).toBeTruthy()
+ const [requestUrl, init] = downloadCall!
// 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')
@@ -676,12 +805,16 @@ describe('browser-hosted Desktop bridge', () => {
'https://cdn.example.com/video.mp4'
)
- for (const [input, init] of fetchMock.mock.calls as [URL, RequestInit][]) {
+ const ticketCalls = (fetchMock.mock.calls as [URL, RequestInit][]).filter(([input]) =>
+ input.pathname.endsWith('/api/files/ticket')
+ )
+
+ for (const [input, init] of ticketCalls) {
expect(input.pathname).toBe('/hermes/api/files/ticket')
expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe(token)
}
- expect(fetchMock).toHaveBeenCalledTimes(token ? 5 : 0)
+ expect(ticketCalls).toHaveLength(token ? 5 : 0)
})
it('persists browser image bytes through the existing chat upload API', async () => {
@@ -1212,7 +1345,9 @@ describe('browser-hosted Desktop bridge', () => {
seedWebappSession('served-token')
vi.stubGlobal(
'fetch',
- vi.fn().mockResolvedValue(new Response('{"detail":"gateway unavailable"}', { status: 503 }))
+ vi.fn().mockImplementation(
+ () => new Response('{"detail":"gateway unavailable"}', { status: 503 })
+ )
)
expect(installBrowserDesktopBridge()).toBe(true)
const desktop = win.hermesDesktop!
diff --git a/apps/desktop/src/lib/browser-staged-attachments.test.ts b/apps/desktop/src/lib/browser-staged-attachments.test.ts
index 45ef04ede90..692c6c60ce7 100644
--- a/apps/desktop/src/lib/browser-staged-attachments.test.ts
+++ b/apps/desktop/src/lib/browser-staged-attachments.test.ts
@@ -48,6 +48,10 @@ 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}`)
})
@@ -58,6 +62,10 @@ 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()
@@ -146,8 +154,9 @@ describe('browser staged attachment transport', () => {
})
expect(result.refText).toBe(refText)
expect(result.stagedUpload).toEqual(source)
- expect(fetchMock).toHaveBeenCalledTimes(1)
- const [input, init] = fetchMock.mock.calls[0]
+ const calls = transportCalls(fetchMock)
+ expect(calls).toHaveLength(1)
+ const [input, init] = calls[0]
const uploadUrl = new URL(String(input))
expect(uploadUrl.pathname).toBe('/api/chat/file-upload')
expect(uploadUrl.searchParams.get('profile')).toBe('owner')
@@ -183,7 +192,7 @@ describe('browser staged attachment transport', () => {
}
expect(requestGateway).toHaveBeenCalledTimes(2)
- expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(transportCalls(fetchMock)).toHaveLength(1)
})
it('retains the legacy byte transport when an older upload endpoint supplies only a path', async () => {
@@ -196,7 +205,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(fetchMock).toHaveBeenCalledTimes(2)
+ expect(transportCalls(fetchMock)).toHaveLength(2)
})
it('retries a failed attach from the same source without another upload or download', async () => {
@@ -213,7 +222,7 @@ describe('browser staged attachment transport', () => {
expect(attachment.stagedUpload).toEqual(source)
expect(attachment.attachedSessionId).toBeUndefined()
await expect(uploadComposerAttachment(attachment, opts)).resolves.toMatchObject({ refText })
- expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(transportCalls(fetchMock)).toHaveLength(1)
expect(requestGateway.mock.calls.every(([, params]) => params.staged_upload === source)).toBe(true)
})
@@ -243,7 +252,7 @@ describe('browser staged attachment transport', () => {
expect(requestGateway).toHaveBeenLastCalledWith('file.attach', {
name: sourceName, session_id: 'new-runtime', staged_upload: source
})
- expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(transportCalls(fetchMock)).toHaveLength(1)
})
it.each(['another Hermes backend', 'Profile not found'])(
@@ -256,7 +265,7 @@ describe('browser staged attachment transport', () => {
remote: true, requestGateway, sessionId: 'runtime'
})).rejects.toThrow(message)
expect(requestGateway).toHaveBeenCalledTimes(1)
- expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(transportCalls(fetchMock)).toHaveLength(1)
}
)
diff --git a/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx b/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx
index 2592db92534..ccb54b49c0e 100644
--- a/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx
@@ -60,6 +60,7 @@ interface UnionAgent {
connectionLabel?: string
handle: string
profile: string
+ reachable?: boolean
}
interface Union {
@@ -700,6 +701,33 @@ 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 () => {
+ const rows = await mergedRoster(
+ { profiles: [{ name: 'default' }, { name: 'research' }, { name: 'solo' }] },
+ {
+ agents: [
+ { connectionId: 'local', connectionKind: 'local', handle: 'hermes', profile: 'default' },
+ { connectionId: 'local', connectionKind: 'local', handle: 'research', profile: 'research' },
+ {
+ connectionId: 'local',
+ connectionKind: 'local',
+ handle: 'solo',
+ profile: 'solo',
+ reachable: false
+ }
+ ],
+ primaryConnectionId: 'local',
+ sources: [{ connectionId: 'local', kind: 'local', reachable: true }]
+ }
+ )
+
+ 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)
+ })
+})
+
describe('a launch that never opens the Bots pane', () => {
it('names a remote bot by what its backend reports, not a stale cached title', async () => {
queryClient.clear()
diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.ts
index 46c90a0a39c..0faa7aeccae 100644
--- a/apps/desktop/src/plugins/hermes-bots/data.ts
+++ b/apps/desktop/src/plugins/hermes-bots/data.ts
@@ -723,6 +723,8 @@ interface UnionAgentRow {
* only source of a REMOTE row's title, since profiles.list is asked of the
* active gateway alone. */
profileMetadata?: Pick<RosterRow, 'display_name' | 'has_avatar' | 'title' | 'ui_meta'>
+ /** False when the source lists the profile but does not serve it. */
+ reachable?: boolean
targetProfile?: string
}
@@ -830,7 +832,12 @@ async function fetchRosterSnapshot(activeConnectionId: null | string | undefined
const merged = mergeMultiSourceRoster(local, union, activeConnectionId, previous)
const sources = Array.isArray(union?.sources) ? union.sources : []
traceRosterSnapshot(local, sources, activeConnectionId, merged?.profiles || [])
- const profiles = (merged?.profiles || []).map(row => annotateBotSource(row, sources))
+
+ const profiles = applyUnservedAgents(
+ (merged?.profiles || []).map(row => annotateBotSource(row, sources)),
+ Array.isArray(union?.agents) ? union.agents : []
+ )
+
await reconcileBotMeta(profiles, issuedAt)
return {
@@ -1490,6 +1497,30 @@ 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. */
export function annotateBotSource(bot: RosterRow, sources: GatewaySource[] | null | undefined): RosterRow {
const id = String(bot?.connectionId || '').trim()