Skip to content

The agent that grows with you

fix(desktop): keep profile switches on the selected gateway

Zeus-Deus5b4905127614
diff --git a/apps/desktop/src/api/profiles.ts b/apps/desktop/src/api/profiles.ts
index cdade9099cc..84788f31d3b 100644
--- a/apps/desktop/src/api/profiles.ts
+++ b/apps/desktop/src/api/profiles.ts
@@ -8,8 +8,9 @@ import type {
import { capabilityScoped, hermesApi, type ProfileScope, STARTUP_REQUEST_TIMEOUT_MS } from './client'
-export function getProfiles(): Promise<ProfilesResponse> {
+export function getProfiles(scope?: ProfileScope): Promise<ProfilesResponse> {
return hermesApi<ProfilesResponse>({
+ ...(scope === undefined ? {} : capabilityScoped(scope)),
path: '/api/profiles',
timeoutMs: STARTUP_REQUEST_TIMEOUT_MS
})
diff --git a/apps/desktop/src/app/chat/sidebar/fleet-rail.ts b/apps/desktop/src/app/chat/sidebar/fleet-rail.ts
index f0bdc16d0d6..5c2a3c70ad8 100644
--- a/apps/desktop/src/app/chat/sidebar/fleet-rail.ts
+++ b/apps/desktop/src/app/chat/sidebar/fleet-rail.ts
@@ -1,5 +1,6 @@
import type { DesktopAgentRoster, DesktopConnectionKind, DesktopRegistryConnection } from '@/global'
import { sortConnectionsForDisplay } from '@/lib/connection-display'
+import type { ProfileInfo } from '@/types/hermes'
// Pure grouping for the fleet profile rail: which gateways sit "at rest"
// beside the active one, and which agents each of them carries. Kept free of
@@ -51,11 +52,13 @@ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'bas
export function buildRestGroups({
activeConnectionId,
connections,
+ profilesByConnection,
roster
}: {
activeConnectionId: null | string
connections: readonly DesktopRegistryConnection[]
roster: DesktopAgentRoster | null
+ profilesByConnection?: ReadonlyMap<string, ProfileInfo[]>
}): FleetGroup[] {
const groups: FleetGroup[] = []
@@ -82,7 +85,16 @@ export function buildRestGroups({
const defaultRow = rows.find(row => row.profile === DEFAULT_PROFILE)
- const named = rows
+ const cached = profilesByConnection?.get(connection.id)
+
+ const profiles = cached
+ ? cached.map(profile => ({
+ profile: profile.name,
+ handle: rows.find(row => row.profile === profile.name)?.handle
+ }))
+ : rows
+
+ const named = profiles
.filter(row => row.profile !== DEFAULT_PROFILE)
.map(row => toAgent(row.profile, row.handle))
.sort((left, right) => collator.compare(left.profile, right.profile))
diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx
index dc008fac1bc..4f8e3b286a5 100644
--- a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx
+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx
@@ -48,6 +48,7 @@ vi.mock('@/store/profile', () => ({
$profileCreateRequest: atom(0),
$profileOrder: atom([]),
$profiles: atom([{ is_default: true, name: 'default' }]),
+ $profilesByConnection: atom(new Map()),
$profileScope: atom('default'),
ALL_PROFILES: '*',
normalizeProfileKey: (name: string) => name,
diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx
index a8d80ffa308..9f867dc067c 100644
--- a/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx
+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx
@@ -3,6 +3,7 @@ import { atom } from 'nanostores'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { DesktopAgentRoster, DesktopConnectionsRegistry } from '@/global'
+import type * as ProfileStore from '@/store/profile'
import { ProfileRail } from './profile-switcher'
@@ -66,12 +67,17 @@ vi.mock('@/i18n', () => ({
})
}))
-vi.mock('@/store/profile', () => ({
+vi.mock('@/store/gateway', () => ({ $gateway: atom(null) }))
+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+
+vi.mock('@/store/profile', async importOriginal => ({
$activeGatewayProfile: atom('default'),
$profileColors: atom({}),
$profileCreateRequest: atom(0),
$profileOrder: atom([]),
$profiles: atom([{ is_default: true, name: 'default' }]),
+ $profilesByConnection: atom(new Map()),
$profileScope: atom('default'),
ALL_PROFILES: '*',
normalizeProfileKey: (name: string) => name,
@@ -82,7 +88,7 @@ vi.mock('@/store/profile', () => ({
setProfileColor: vi.fn(),
setProfileOrder: vi.fn(),
setShowAllProfiles: vi.fn(),
- sortByProfileOrder: (profiles: unknown[]) => profiles
+ sortByProfileOrder: (await importOriginal<typeof ProfileStore>()).sortByProfileOrder
}))
vi.mock('@/store/connections', () => ({
@@ -106,6 +112,7 @@ vi.mock('./use-profile-rail-refresh-on-active', () => ({
}))
vi.mock('@/hermes', () => ({
+ setApiRequestProfile: vi.fn(),
getProfileSoul: vi.fn().mockResolvedValue({ content: '' }),
updateProfileSoul: vi.fn()
}))
@@ -123,7 +130,7 @@ const connectionsRegistry = connectionsStore.$connectionsRegistry as ReturnType<
typeof atom<DesktopConnectionsRegistry | null>
>
-const { $profiles, $profileScope } = await import('@/store/profile')
+const { $profileOrder, $profiles, $profilesByConnection, $profileScope } = await import('@/store/profile')
const profiles = $profiles as ReturnType<typeof atom<Array<{ is_default: boolean; name: string }>>>
const profileScope = $profileScope as ReturnType<typeof atom<string>>
const { _resetFleetRosterForTests } = await import('@/store/fleet-roster')
@@ -131,28 +138,28 @@ const { _resetFleetRosterForTests } = await import('@/store/fleet-roster')
const registry: DesktopConnectionsRegistry = {
connections: [
{ id: 'local', kind: 'local', label: 'This device' },
- { id: 'pandora', kind: 'remote', label: 'Pandora', url: 'https://pandora.example' },
- { id: 'vps', kind: 'ssh', label: 'VPS', host: 'vps.example' }
+ { id: 'gateway-a', kind: 'remote', label: 'Gateway A', url: 'https://gateway-a.example.com' },
+ { id: 'gateway-b', kind: 'ssh', label: 'Gateway B', host: 'gateway-b.example.com' }
],
launchMode: 'primary',
- lastUsed: 'pandora',
- primary: 'pandora',
+ lastUsed: 'gateway-a',
+ primary: 'gateway-a',
version: 2
} as DesktopConnectionsRegistry
const roster: DesktopAgentRoster = {
agents: [
{
- connectionId: 'pandora',
+ connectionId: 'gateway-a',
connectionKind: 'remote',
- connectionLabel: 'Pandora',
+ connectionLabel: 'Gateway A',
profile: 'default',
- handle: 'hermes-pandora'
+ handle: 'hermes-gateway-a'
},
{
- connectionId: 'pandora',
+ connectionId: 'gateway-a',
connectionKind: 'remote',
- connectionLabel: 'Pandora',
+ connectionLabel: 'Gateway A',
profile: 'scout',
handle: 'scout'
},
@@ -163,19 +170,25 @@ const roster: DesktopAgentRoster = {
profile: 'default',
handle: 'hermes'
},
- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'omer', handle: 'omer' }
+ {
+ connectionId: 'local',
+ connectionKind: 'local',
+ connectionLabel: 'This device',
+ profile: 'builder',
+ handle: 'builder'
+ }
],
sources: [
- { connectionId: 'pandora', kind: 'remote', label: 'Pandora', reachable: true },
+ { connectionId: 'gateway-a', kind: 'remote', label: 'Gateway A', reachable: true },
{ connectionId: 'local', kind: 'local', label: 'This device', reachable: true },
- { connectionId: 'vps', kind: 'ssh', label: 'VPS', reachable: false, error: 'timed out' }
+ { connectionId: 'gateway-b', kind: 'ssh', label: 'Gateway B', reachable: false, error: 'timed out' }
]
}
function armFleet() {
hasMultipleConnections.set(true)
connectionsRegistry.set(registry)
- activeConnectionId.set('pandora')
+ activeConnectionId.set('gateway-a')
profiles.set([
{ is_default: true, name: 'default' },
{ is_default: false, name: 'scout' }
@@ -202,6 +215,8 @@ beforeEach(() => {
afterEach(() => {
cleanup()
+ $profileOrder.set([])
+ $profilesByConnection.set(new Map())
vi.clearAllMocks()
_resetFleetRosterForTests()
hasMultipleConnections.set(false)
@@ -213,6 +228,56 @@ afterEach(() => {
})
describe('ProfileRail fleet mode', () => {
+ it('keeps the custom named-profile order when a source becomes inactive', async () => {
+ armFleet()
+ profiles.set([...profiles.get(), { name: 'editor', is_default: false }])
+ $profilesByConnection.set(new Map([['gateway-a', $profiles.get()]]))
+ $profileOrder.set(['scout', 'editor'])
+ const container = await renderFleet()
+
+ const labels = () =>
+ Array.from(
+ container.querySelectorAll('[data-connection-id="gateway-a"][data-slot="profile-rail-gateway"] button')
+ ).map(button => button.getAttribute('aria-label')?.split(' · ')[0])
+
+ const activeOrder = labels()
+
+ await act(async () => {
+ activeConnectionId.set('local')
+ profiles.set([])
+ })
+
+ expect(labels()).toEqual(activeOrder)
+ })
+
+ it('keeps each source’s known squares in place when the incoming profile read has no result', async () => {
+ armFleet()
+ // A newly discovered outgoing profile is newer than the fleet roster.
+ profiles.set([...profiles.get(), { name: 'editor', is_default: false }])
+ $profilesByConnection.set(new Map([['gateway-a', $profiles.get()]]))
+ const container = await renderFleet()
+ const groups = () => Array.from(container.querySelectorAll('[data-slot="profile-rail-gateway"]'))
+
+ const before = groups().map(group => [
+ group.getAttribute('data-connection-id'),
+ group.querySelectorAll('button').length
+ ])
+
+ await act(async () => {
+ activeConnectionId.set('local')
+ profiles.set([]) // No successful REST result on the incoming source (e.g. 401).
+ })
+
+ expect(
+ groups().map(group => [group.getAttribute('data-connection-id'), group.querySelectorAll('button').length])
+ ).toEqual(before)
+ const active = container.querySelector('[data-active="true"][data-connection-id="local"]') as HTMLElement
+ expect(within(active).queryByRole('button', { name: /scout|editor/ })).toBeNull()
+ expect(within(active).getByRole('button', { name: /builder/ })).toBeTruthy()
+ fireEvent.click(within(active).getByRole('button', { name: /builder/ }))
+ expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'builder' })
+ })
+
it('stays on the single-gateway path with one registered gateway', async () => {
const container = await renderFleet()
@@ -234,12 +299,12 @@ describe('ProfileRail fleet mode', () => {
])
// Registry order for the whole strip — This device first (switcher
- // order), then by label — with the active gateway (Pandora) in ITS slot,
+ // order), then by label — with the active gateway (Gateway A) in ITS slot,
// never pulled to the front.
expect(groups).toEqual([
['local', false],
- ['pandora', true],
- ['vps', false]
+ ['gateway-a', true],
+ ['gateway-b', false]
])
// Every group is headed by its kind glyph; hairlines only between groups.
@@ -247,11 +312,11 @@ describe('ProfileRail fleet mode', () => {
node.getAttribute('data-connection-id')
)
- expect(dividers).toEqual(['local', 'pandora', 'vps'])
+ expect(dividers).toEqual(['local', 'gateway-a', 'gateway-b'])
const local = screen.getByRole('group', { name: 'Profiles on This device' })
expect(within(local).getByRole('button', { name: 'default · This device' })).toBeTruthy()
- expect(within(local).getByRole('button', { name: 'omer · This device' })).toBeTruthy()
+ expect(within(local).getByRole('button', { name: 'builder · This device' })).toBeTruthy()
// The active gateway's own squares are unchanged and unqualified.
expect(screen.getByRole('button', { name: 'scout' })).toBeTruthy()
@@ -266,14 +331,14 @@ describe('ProfileRail fleet mode', () => {
armFleet()
const container = await renderFleet()
- const vps = container.querySelector('[data-slot="profile-rail-gateway"][data-connection-id="vps"]')
- expect(vps?.getAttribute('data-reachable')).toBe('false')
+ const gatewayB = container.querySelector('[data-slot="profile-rail-gateway"][data-connection-id="gateway-b"]')
+ expect(gatewayB?.getAttribute('data-reachable')).toBe('false')
expect(
container.querySelector(
- '[data-slot="profile-rail-divider"][data-connection-id="vps"] [data-slot="profile-rail-unreachable"]'
+ '[data-slot="profile-rail-divider"][data-connection-id="gateway-b"] [data-slot="profile-rail-unreachable"]'
)
).toBeTruthy()
- expect(within(vps as HTMLElement).getByRole('button', { name: 'default · VPS' })).toBeTruthy()
+ expect(within(gatewayB as HTMLElement).getByRole('button', { name: 'default · Gateway B' })).toBeTruthy()
})
it('re-homes onto the exact (gateway, profile) when an at-rest square is clicked', async () => {
@@ -283,20 +348,20 @@ describe('ProfileRail fleet mode', () => {
let settle: () => void = () => undefined
selectConnection.mockImplementationOnce(() => new Promise<void>(resolve => (settle = resolve)))
- const omer = screen.getByRole('button', { name: 'omer · This device' })
- fireEvent.click(omer)
+ const builder = screen.getByRole('button', { name: 'builder · This device' })
+ fireEvent.click(builder)
- expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'omer' })
+ expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'builder' })
expect(selectProfile).not.toHaveBeenCalled()
// The dial spinner sits on the clicked square, not in the statusbar.
- expect(omer.getAttribute('aria-busy')).toBe('true')
+ expect(builder.getAttribute('aria-busy')).toBe('true')
await act(async () => {
settle()
await Promise.resolve()
})
- expect(omer.getAttribute('aria-busy')).toBeNull()
+ expect(builder.getAttribute('aria-busy')).toBeNull()
})
it('re-homes onto another gateway default from its home square', async () => {
@@ -323,7 +388,7 @@ describe('ProfileRail fleet mode', () => {
activeConnectionId.set('local')
profiles.set([
{ is_default: true, name: 'default' },
- { is_default: false, name: 'omer' }
+ { is_default: false, name: 'builder' }
])
const container = await renderFleet()
@@ -334,11 +399,11 @@ describe('ProfileRail fleet mode', () => {
expect(groups).toEqual([
['local', true],
- ['pandora', false],
- ['vps', false]
+ ['gateway-a', false],
+ ['gateway-b', false]
])
- expect(screen.getByRole('button', { name: 'scout · Pandora' })).toBeTruthy()
- expect(screen.getByRole('button', { name: 'omer' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'scout · Gateway A' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'builder' })).toBeTruthy()
})
it('counts the whole fleet toward the condensed threshold and sections the menu by gateway', async () => {
@@ -347,7 +412,7 @@ describe('ProfileRail fleet mode', () => {
{ is_default: true, name: 'default' },
...Array.from({ length: 11 }, (_, index) => ({ is_default: false, name: `p${index + 1}` }))
])
- // 11 named on Pandora + local (default, omer) + vps (default) = 14 > 13.
+ // 11 named on Gateway A + local (default, builder) + gateway-b (default) = 14 > 13.
const container = await renderFleet()
expect(screen.getByRole('button', { name: 'Profiles' })).toBeTruthy()
diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx
index f9c53042c60..b40fa951176 100644
--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx
+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx
@@ -71,6 +71,7 @@ import {
$profileCreateRequest,
$profileOrder,
$profiles,
+ $profilesByConnection,
$profileScope,
ALL_PROFILES,
normalizeProfileKey,
@@ -149,6 +150,7 @@ export function ProfileRail() {
const { t } = useI18n()
const p = t.profiles
const profiles = useStore($profiles)
+ const profilesByConnection = useStore($profilesByConnection)
const scope = useStore($profileScope)
const gatewayProfile = useStore($activeGatewayProfile)
const order = useStore($profileOrder)
@@ -177,11 +179,32 @@ export function ProfileRail() {
const connections = registry?.connections
+ const groups = useMemo(
+ () =>
+ buildRestGroups({ activeConnectionId: null, connections: connections ?? [], profilesByConnection, roster }).map(
+ group => ({
+ ...group,
+ named: sortByProfileOrder(
+ group.named.map(agent => ({ name: agent.profile, agent })),
+ order
+ ).map(({ agent }) => agent)
+ })
+ ),
+ [connections, order, profilesByConnection, roster]
+ )
+
const restGroups = useMemo(
- () => (multipleConnections ? buildRestGroups({ activeConnectionId, connections: connections ?? [], roster }) : []),
- [activeConnectionId, connections, multipleConnections, roster]
+ () => (multipleConnections ? groups.filter(group => group.connectionId !== activeConnectionId) : []),
+ [activeConnectionId, groups, multipleConnections]
)
+ // Until this source has served its first list, retain the roster's exact
+ // routes rather than borrowing outgoing profiles or collapsing its squares.
+ const activeFallback =
+ profiles.length === 0 && activeConnectionId && !profilesByConnection.has(activeConnectionId)
+ ? groups.find(group => group.connectionId === activeConnectionId)
+ : undefined
+
// Fleet mode needs something to show beside the active gateway. Two
// registrations of one backend collapse to a single roster source, which
// keeps the rail on its single-gateway path.
@@ -223,7 +246,9 @@ export function ProfileRail() {
// ahead of the wheel effect, which re-binds when the strip mounts/unmounts.
// The threshold counts the whole fleet: fourteen squares are fourteen
// squares wherever they live.
- const condensed = profiles.length + countRestAgents(restGroups) > PROFILE_DROPDOWN_THRESHOLD
+ const condensed =
+ profiles.length + countRestAgents(activeFallback ? [...restGroups, activeFallback] : restGroups) >
+ PROFILE_DROPDOWN_THRESHOLD
const switchToRest = (agent: FleetAgent) => {
const key = fleetRouteKey(agent.connectionId, agent.profile)
@@ -456,7 +481,7 @@ export function ProfileRail() {
onSelect={selectProfile}
onSelectRest={switchToRest}
profiles={named}
- restGroups={restGroups}
+ restGroups={activeFallback ? [activeFallback, ...restGroups] : restGroups}
/>
</div>
) : (
@@ -469,7 +494,21 @@ export function ProfileRail() {
strip keeps one shape whichever gateway is active. */}
{fleet
? fleetSequence.map((entry, index) =>
- entry.kind === 'active' ? (
+ entry.kind === 'active' && activeFallback ? (
+ <FleetRestGroup
+ activeProfile={isAll ? null : activeKey}
+ colors={colors}
+ first={index === 0}
+ group={activeFallback}
+ key={activeFallback.connectionId}
+ onDelete={setPendingRestDelete}
+ onEditSoul={setPendingRestSoul}
+ onRecolor={(agent, color) => setProfileColor(agent.profile, color)}
+ onRename={setPendingRestRename}
+ onSelect={switchToRest}
+ pendingRoute={pendingRoute}
+ />
+ ) : entry.kind === 'active' ? (
<Fragment key="active">
<FleetDivider
connection={activeConnection}
@@ -944,6 +983,7 @@ function FleetDivider({
// yours), then its home square and named squares, dimmed. Clicking any of
// them re-homes onto that exact (gateway, profile).
function FleetRestGroup({
+ activeProfile,
colors,
first,
group,
@@ -957,6 +997,7 @@ function FleetRestGroup({
colors: Record<string, string>
first: boolean
group: FleetGroup
+ activeProfile?: null | string
onDelete: (agent: FleetAgent) => void
onEditSoul: (agent: FleetAgent) => void
onRecolor: (agent: FleetAgent, color: null | string) => void
@@ -975,24 +1016,25 @@ function FleetRestGroup({
<span
aria-label={p.fleet.gateway(group.label)}
className="flex shrink-0 items-center gap-1"
- data-active="false"
+ data-active={activeProfile !== undefined}
data-connection-id={group.connectionId}
data-reachable={group.reachable}
data-slot="profile-rail-gateway"
role="group"
>
<ProfilePill
- active={false}
+ active={activeProfile === group.defaultAgent.profile}
connectionId={group.connectionId}
glyph="home"
label={p.fleet.onGateway(group.defaultAgent.profile, group.label)}
- muted
+ muted={activeProfile === undefined}
onSelect={() => onSelect(group.defaultAgent)}
pending={pendingRoute === defaultKey}
slot="profile-rail-rest-home"
/>
{group.named.map(agent => (
<RestSquare
+ active={activeProfile === agent.profile}
agent={agent}
color={resolveProfileColor(agent.profile, colors)}
key={agent.profile}
@@ -1015,6 +1057,7 @@ function FleetRestGroup({
// different machines never read alike; the right-click actions run against
// the square's owning gateway.
function RestSquare({
+ active,
agent,
color,
onDelete,
@@ -1024,6 +1067,7 @@ function RestSquare({
onSelect,
pending
}: {
+ active: boolean
agent: FleetAgent
color: null | string
onDelete: () => void
@@ -1056,7 +1100,8 @@ function RestSquare({
<button
aria-busy={pending || undefined}
aria-label={label}
- className="relative grid size-5 shrink-0 select-none place-items-center rounded-[3px] text-[0.5625rem] font-semibold uppercase leading-none opacity-35 transition-opacity hover:opacity-100 aria-busy:opacity-100"
+ aria-pressed={active}
+ className="aria-pressed:opacity-100 relative grid size-5 shrink-0 select-none place-items-center rounded-[3px] text-[0.5625rem] font-semibold uppercase leading-none opacity-35 transition-opacity hover:opacity-100 aria-busy:opacity-100"
data-connection-id={agent.connectionId}
data-profile={agent.profile}
data-slot="profile-rail-rest-square"
diff --git a/apps/desktop/src/app/skills/index.tsx b/apps/desktop/src/app/skills/index.tsx
index f98e548f8a5..a363be5e84d 100644
--- a/apps/desktop/src/app/skills/index.tsx
+++ b/apps/desktop/src/app/skills/index.tsx
@@ -290,7 +290,7 @@ export function SkillsView({
const { data: profilesData } = useQuery({
queryKey: ['capabilities-profiles'],
- queryFn: getProfiles,
+ queryFn: () => getProfiles(),
staleTime: 60_000,
// Pinned scope never shows the selector, so don't fetch the roster for it.
enabled: !fixedProfile
diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.ts
index ec9b94ada61..441190d54a7 100644
--- a/apps/desktop/src/hermes.test.ts
+++ b/apps/desktop/src/hermes.test.ts
@@ -30,6 +30,7 @@ import {
setApiRequestConnection,
setApiRequestProfile,
speakText,
+ STARTUP_REQUEST_TIMEOUT_MS,
transcribeAudio,
triggerCronJob
} from './hermes'
@@ -178,17 +179,19 @@ describe('Hermes REST helpers', () => {
)
})
- it('does not stamp ambient profile onto unscoped helpers', async () => {
+ it('pins profile-list reads only when explicitly scoped, without changing unscoped requests', async () => {
+ setApiRequestConnection('remote-a')
setApiRequestProfile('iris')
await getProfiles()
-
- expect(api).toHaveBeenCalledWith(
- expect.objectContaining({
- path: '/api/profiles'
- })
- )
- expect(api.mock.calls[0][0]).not.toHaveProperty('profile')
+ await getProfiles({ connectionId: 'remote-b', profile: 'scout' })
+ await getProfiles({ connectionId: 'local', profile: 'default' })
+
+ expect(api.mock.calls).toEqual([
+ [{ connectionId: 'remote-a', path: '/api/profiles', timeoutMs: STARTUP_REQUEST_TIMEOUT_MS }],
+ [{ connectionId: 'remote-b', profile: 'scout', path: '/api/profiles', timeoutMs: STARTUP_REQUEST_TIMEOUT_MS }],
+ [{ connectionId: 'local', profile: 'default', path: '/api/profiles', timeoutMs: STARTUP_REQUEST_TIMEOUT_MS }]
+ ])
})
it('preserves ambient and explicit-local ownership for session and profile requests', async () => {
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index edd9764dd8d..0070fdcb93d 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -1,6 +1,7 @@
import { atom } from 'nanostores'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'
import type { DesktopConnectionsRegistry } from '@/global'
import { deferred } from '../test/deferred'
@@ -101,6 +102,7 @@ const registry: DesktopConnectionsRegistry = {
}
const list = vi.fn(async () => registry)
+const api = vi.fn(async () => ({ profiles: [] }))
const setLastUsed = vi.fn(async (id: string) => ({ ok: true, registry: { ...registry, lastUsed: id } }))
beforeEach(() => {
@@ -139,7 +141,11 @@ beforeEach(() => {
$gatewaySwitching.set(false)
list.mockClear()
setLastUsed.mockClear()
- vi.stubGlobal('window', { hermesDesktop: { connections: { list, setLastUsed } }, localStorage })
+ api.mockReset()
+ api.mockResolvedValue({ profiles: [] })
+ setApiRequestConnection(null)
+ setApiRequestProfile(null)
+ vi.stubGlobal('window', { hermesDesktop: { api, connections: { list, setLastUsed } }, localStorage })
})
afterEach(() => vi.unstubAllGlobals())
@@ -225,6 +231,7 @@ describe('selectConnection', () => {
expect(openGatewayAgent).toHaveBeenCalledWith('homelab', 'default')
expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default', expect.anything())
+ expect(api).not.toHaveBeenCalled()
expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
expect(requestFreshSession).toHaveBeenCalledTimes(1)
expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)
@@ -250,6 +257,7 @@ describe('selectConnection', () => {
await selectConnection('local')
expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'default', expect.anything())
+ expect(api).not.toHaveBeenCalled()
})
it('lets a later source choice win while an earlier dial is still pending', async () => {
@@ -361,6 +369,77 @@ describe('selectConnection', () => {
expect($connection.get()?.connectionId).toBe('local')
})
+ it.each(['remote', 'cloud'] as const)(
+ 'requires protected REST auth on a warm %s socket before discarding the current workspace',
+ async kind => {
+ const oauthRegistry: DesktopConnectionsRegistry = {
+ ...registry,
+ connections: registry.connections.map(connection =>
+ connection.id === 'homelab' ? { ...connection, kind, authMode: 'oauth' } : connection
+ )
+ }
+
+ setConnectionsRegistry(oauthRegistry)
+ const source = { connectionId: 'work-vps', mode: 'remote' as const, profile: 'research', registryScoped: true }
+ $connection.set(source)
+ $activeGatewayProfile.set('research')
+ $activeSessionId.set('source-runtime')
+ $newChatProfile.set('research')
+ $showAllProfiles.set(true)
+ setApiRequestConnection('work-vps')
+ setApiRequestProfile('research')
+ setLastUsed.mockImplementationOnce(async id => ({ ok: true, registry: { ...oauthRegistry, lastUsed: id } }))
+
+ // A retained socket already passed its handshake; opening it succeeds
+ // even though fresh REST requests no longer authenticate. Connectivity
+ // errors must also preserve the workspace, without being called sign-in.
+ const expired = new Error(kind === 'remote' ? '401 Unauthorized: no_cookie' : '403 Forbidden: session expired')
+ const offline = new Error('net::ERR_CONNECTION_RESET')
+ api.mockRejectedValueOnce(expired).mockRejectedValueOnce(offline)
+
+ for (const error of [expired, offline]) {
+ await expect(selectConnection('homelab', { profile: 'scout' })).rejects.toBe(error)
+ expect($connection.get()).toBe(source)
+ expect($activeConnectionId.get()).toBe('work-vps')
+ expect($activeGatewayProfile.get()).toBe('research')
+ expect($activeSessionId.get()).toBe('source-runtime')
+ expect($newChatProfile.get()).toBe('research')
+ expect($showAllProfiles.get()).toBe(true)
+ expect($pendingConnectionId.get()).toBeNull()
+ expect($gatewaySwitching.get()).toBe(false)
+ expect(ensureGatewayAgent).not.toHaveBeenCalled()
+ expect(beginGatewaySwitch).not.toHaveBeenCalled()
+ expect(wipeSessionListsForGatewaySwitch).not.toHaveBeenCalled()
+ expect(requestFreshSession).not.toHaveBeenCalled()
+ expect(refreshActiveProfile).not.toHaveBeenCalled()
+ expect(setLastUsed).not.toHaveBeenCalled()
+ }
+
+ // Auth is refreshed externally; the very next click must work with the
+ // same module and warm socket, without a cached failed readiness result.
+ await selectConnection('homelab', { profile: 'scout' })
+ expect(api.mock.calls).toEqual(
+ Array.from({ length: 3 }, () => [
+ {
+ connectionId: 'homelab',
+ profile: 'scout',
+ path: '/api/profiles',
+ timeoutMs: 60_000
+ }
+ ])
+ )
+ expect(openGatewayAgent.mock.calls).toEqual(Array.from({ length: 3 }, () => ['homelab', 'scout']))
+ expect(ensureGatewayAgent).toHaveBeenCalledTimes(1)
+ expect(beginGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect(api.mock.invocationCallOrder[2]).toBeLessThan(beginGatewaySwitch.mock.invocationCallOrder[0])
+ expect($activeConnectionId.get()).toBe('homelab')
+ expect($newChatProfile.get()).toBe('scout')
+ expect($showAllProfiles.get()).toBe(false)
+ expect($activeSessionId.get()).toBeNull()
+ expect(setLastUsed).toHaveBeenCalledWith('homelab')
+ }
+ )
+
it('an activation that does not land after the wipe lowers the barrier and repaints the still-active source', async () => {
setConnectionsRegistry(registry)
$connection.set({ connectionId: 'local', mode: 'local' })
@@ -552,6 +631,33 @@ describe('selectConnection', () => {
expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default', expect.anything())
expect($connection.get()?.connectionId).toBe('homelab')
+
+ // REST readiness shares the dial budget, rather than adding a second
+ // full timeout. A late response has no activation rights after failure.
+ setConnectionsRegistry({
+ ...registry,
+ connections: registry.connections.map(connection =>
+ connection.id === 'work-vps' ? { ...connection, authMode: 'oauth' } : connection
+ )
+ })
+ const dial = deferred()
+ const rest = deferred<{ profiles: never[] }>()
+ openGatewayAgent.mockImplementationOnce(() => dial.promise)
+ api.mockImplementationOnce(() => rest.promise)
+ $activeSessionId.set('homelab-runtime')
+ const restOutcome = selectConnection('work-vps').catch((error: Error) => error.message)
+ await vi.advanceTimersByTimeAsync(10_000)
+ dial.resolve()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(api).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(await restOutcome).toMatch(/Timed out connecting to "Work VPS"/)
+ expect($activeSessionId.get()).toBe('homelab-runtime')
+ expect($pendingConnectionId.get()).toBeNull()
+ rest.resolve({ profiles: [] })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(beginGatewaySwitch).toHaveBeenCalledTimes(1)
+ expect($activeConnectionId.get()).toBe('homelab')
} finally {
vi.useRealTimers()
}
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index 7951e3bbe2c..bc7a2436cbe 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -1,5 +1,6 @@
import { atom, computed } from 'nanostores'
+import { getProfiles } from '@/api/profiles'
import type { DesktopConnectionsRegistry } from '@/global'
import { persistStringRecord, storedStringRecord } from '@/lib/storage'
import { BACKEND_BOOT_WAIT_TIMEOUT_MS, isTimeoutError, withTimeout } from '@/lib/with-timeout'
@@ -242,8 +243,8 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnection
* never probes or opens remote gateways.
*
* Two phases, same commit contract as a Settings → Gateway apply (softSwitch):
- * 1. Dial the target WITHOUT activating it. The previous source stays fully
- * bound and painted, so a dead target fails with nothing lost.
+ * 1. Prove target socket/REST readiness WITHOUT activating it. The previous
+ * source stays fully bound and painted, so a dead target loses nothing.
* 2. Commit: beginGatewaySwitch() — barrier up, machine-context reset,
* session bindings wiped — then activate the already-open socket. The
* wipe runs inside the activation's serialized section, synchronously
@@ -334,6 +335,7 @@ export async function selectConnection(connectionId: string, options: SelectConn
let token = null as GatewaySwitchToken | null
try {
+ const preflightDeadline = Date.now() + SWITCH_DIAL_TIMEOUT_MS
// Phase 1 — open the target's socket; the active route is untouched.
// Always use the explicit registry route. `local` must mean This device,
// and a registry primary can differ from a legacy per-profile override.
@@ -350,6 +352,25 @@ export async function selectConnection(connectionId: string, options: SelectConn
return
}
+ if (
+ targetConnection.authMode === 'oauth' &&
+ (targetConnection.kind === 'remote' || targetConnection.kind === 'cloud')
+ ) {
+ // Retained sockets can outlive cookie/native OAuth REST auth. Prove a
+ // protected read on the destination before wiping; a socket alone is
+ // enough for the unchanged local/long-lived-token path. Keep the exact
+ // failure for caller UX (network failures must not become sign-in errors).
+ await withTimeout(
+ getProfiles({ connectionId, profile: targetProfile }),
+ Math.max(0, preflightDeadline - Date.now()),
+ `Timed out connecting to "${targetConnection.label}".`
+ )
+
+ if (revision !== switchRevision) {
+ return
+ }
+ }
+
// Phase 2 — commit. The hook runs inside the activation's serialized
// section, right before the socket is activated: sever the previous
// backend's bindings, then publish, with nothing in between. A click that
diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.ts
index b16cb95d293..04fcc887410 100644
--- a/apps/desktop/src/store/gateway-profile-request.test.ts
+++ b/apps/desktop/src/store/gateway-profile-request.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { deferred } from '../test/deferred'
+
const secondaryGateways: Array<{
close: ReturnType<typeof vi.fn>
connect: ReturnType<typeof vi.fn>
@@ -567,20 +569,24 @@ describe('retainGatewayForAgent (#93602)', () => {
describe('attached shared-remote group turns (#96493)', () => {
function installAttachedSharedRemote() {
+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
+ connectionId,
+ port: 9119,
+ profile,
+ sharedRemote: true
+ }))
+
;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
getConnection: vi.fn(async (profile: null | string) => ({ port: 4242, profile, token: 't' })),
- getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
- connectionId,
- port: 9119,
- profile,
- sharedRemote: true
- })),
+ getConnectionFor,
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
})),
touchBackend: vi.fn(async () => undefined)
}
+
+ return getConnectionFor
}
it('reuses the primary socket for a named profile on the attached shared remote', async () => {
@@ -656,7 +662,7 @@ describe('attached shared-remote group turns (#96493)', () => {
expect(primary.request).toHaveBeenCalledOnce()
})
- it('openGatewayForAgent and ensureGatewayForAgent do not dial a secondary', async () => {
+ it('returning to an attached shared remote activates its socket without closing the other source', async () => {
const primary = makePrimary()
setPrimaryGateway(primary as never, 'default')
setPrimaryGatewayConnection({ connectionId: 'homelab' })
@@ -666,6 +672,35 @@ describe('attached shared-remote group turns (#96493)', () => {
await openGatewayForAgent('homelab', 'voter')
expect(await ensureGatewayForAgent('homelab', 'voter')).toBe(true)
expect(secondaryGateways).toHaveLength(0)
+
+ expect(await ensureGatewayForAgent('local', 'worker')).toBe(true)
+ const local = secondaryGateways[0]
+ expect($gateway.get()).toBe(local)
+
+ await openGatewayForAgent('homelab', 'voter')
+ expect(await ensureGatewayForAgent('homelab', 'voter')).toBe(true)
+ expect($gateway.get()).toBe(primary)
+ expect(secondaryGateways).toHaveLength(1)
+ expect(local.close).not.toHaveBeenCalled()
+ })
+
+ it('a delayed shared-remote probe cannot reclaim the foreground from a newer activation', async () => {
+ const primary = makePrimary()
+ setPrimaryGateway(primary as never, 'default')
+ setPrimaryGatewayConnection({ connectionId: 'homelab' })
+ const getConnectionFor = installAttachedSharedRemote()
+ await ensureGatewayForProfile('default')
+ expect(await ensureGatewayForAgent('local', 'worker')).toBe(true)
+ const local = $gateway.get()
+
+ const probe = deferred<Awaited<ReturnType<typeof getConnectionFor>>>()
+ getConnectionFor.mockReturnValueOnce(probe.promise)
+ const staleActivation = ensureGatewayForAgent('homelab', 'voter')
+ expect(await ensureGatewayForAgent('local', 'worker')).toBe(true)
+ probe.resolve({ connectionId: 'homelab', port: 9119, profile: 'voter', sharedRemote: true })
+
+ expect(await staleActivation).toBe(false)
+ expect($gateway.get()).toBe(local)
})
it('ensureGatewayForAgent is false when the attached primary socket is closed', async () => {
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 204a631932f..a150bf680e7 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -1520,16 +1520,18 @@ export async function ensureGatewayForAgent(
return !signal?.aborted
}
+ const activationEpoch = beginGatewayActivation()
+
if (await isAttachedSharedRemote(connectionId, profile, 'foreground')) {
- return Boolean(isOpen(g.primaryGateway) && !signal?.aborted)
+ // A retained primary can be open while the foreground still points at a
+ // different source. Reusing its socket must also move the active route.
+ return Boolean(isOpen(g.primaryGateway) && !signal?.aborted && applyActive(g.primaryProfile, activationEpoch))
}
if (!window.hermesDesktop?.getConnectionFor) {
throw new Error('This Desktop build cannot dial registry connections. Update Hermes Desktop.')
}
- const activationEpoch = beginGatewayActivation()
-
let entry = g.secondaries.get(scope)
if (!entry) {
diff --git a/apps/desktop/src/store/profile-cache.test.ts b/apps/desktop/src/store/profile-cache.test.ts
new file mode 100644
index 00000000000..cdda7b52d28
--- /dev/null
+++ b/apps/desktop/src/store/profile-cache.test.ts
@@ -0,0 +1,188 @@
+import { atom } from 'nanostores'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { setApiRequestConnection } from '@/api/client'
+import { buildRestGroups } from '@/app/chat/sidebar/fleet-rail'
+import type { DesktopAgentRoster, DesktopRegistryConnection, HermesConnection } from '@/global'
+import { $fleetRoster, _resetFleetRosterForTests, refreshFleetRoster } from '@/store/fleet-roster'
+import type { ProfileInfo } from '@/types/hermes'
+
+vi.mock('@/store/gateway', () => ({ $gateway: atom(null) }))
+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+
+const { $profiles, $profilesByConnection, invalidateProfileListFetches, refreshActiveProfile, refreshProfiles } =
+ await import('./profile')
+
+const { $connection } = await import('./session')
+
+const profile = (name: string): ProfileInfo => ({
+ name,
+ is_default: name === 'default',
+ path: '',
+ has_env: false,
+ model: null,
+ provider: null,
+ skill_count: 0
+})
+
+const descriptor = (connectionId: string): HermesConnection =>
+ ({
+ connectionId,
+ baseUrl: `https://${connectionId}.example.com`,
+ mode: 'remote',
+ profile: 'default'
+ }) as HermesConnection
+
+function activate(connectionId: string) {
+ setApiRequestConnection(connectionId)
+ $connection.set(descriptor(connectionId))
+}
+
+afterEach(() => {
+ _resetFleetRosterForTests()
+ invalidateProfileListFetches()
+ $connection.set(null)
+ $profilesByConnection.set(new Map())
+ $profiles.set([])
+ setApiRequestConnection(null)
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+it('keeps failed incoming profile reads isolated while retaining the outgoing connection cache', async () => {
+ const outgoing = [profile('default'), profile('writer')]
+ const api = vi.fn(async () => ({ profiles: outgoing }))
+ vi.stubGlobal('window', { hermesDesktop: { api } })
+ activate('source-a')
+ await refreshProfiles()
+
+ // Same profile name on both machines: profile-only invalidation cannot help.
+ invalidateProfileListFetches()
+ activate('source-b')
+ api.mockRejectedValue(new Error('HTTP 401 {"reason":"no_cookie","login_url":"/login"}'))
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ vi.useFakeTimers()
+ const refresh = refreshActiveProfile()
+ await vi.runAllTimersAsync()
+ await refresh
+
+ expect($profiles.get()).not.toContain(outgoing[1])
+ activate('source-a')
+ expect($profiles.get()).toBe(outgoing)
+})
+
+it('lets only a subsequent successful roster supersede cached rail names', async () => {
+ const connections: DesktopRegistryConnection[] = ['source-a', 'source-b'].map(id => ({
+ id,
+ kind: 'remote',
+ label: id,
+ tokenSet: false,
+ tokenPreview: null
+ }))
+
+ const roster = (names: string[], reachable = true): DesktopAgentRoster => ({
+ agents: names.map(name => ({
+ connectionId: 'source-a',
+ connectionKind: 'remote',
+ connectionLabel: 'source-a',
+ profile: name,
+ handle: `${name}-source-a`
+ })),
+ sources: connections.map(connection => ({
+ connectionId: connection.id,
+ kind: connection.kind,
+ label: connection.label,
+ reachable: connection.id === 'source-a' ? reachable : true
+ }))
+ })
+
+ const restNames = () =>
+ buildRestGroups({
+ activeConnectionId: $connection.get()?.connectionId ?? null,
+ connections,
+ roster: $fleetRoster.get(),
+ profilesByConnection: $profilesByConnection.get()
+ })
+ .find(group => group.connectionId === 'source-a')!
+ .named.map(agent => agent.profile)
+
+ const outgoing = [profile('default'), profile('old')]
+ const incoming = [profile('default'), profile('builder')]
+ const api = vi.fn().mockResolvedValue({ profiles: outgoing })
+ const getAgentRoster = vi.fn().mockResolvedValue(roster([]))
+ vi.stubGlobal('window', { hermesDesktop: { api, getAgentRoster } })
+ await refreshFleetRoster({ force: true })
+ activate('source-a')
+ await refreshProfiles()
+ activate('source-b')
+ api.mockResolvedValue({ profiles: incoming })
+ await refreshProfiles()
+ expect(restNames()).toEqual(['old']) // The older roster must not hide a newly discovered profile.
+
+ getAgentRoster.mockRejectedValueOnce(new Error('enumeration failed'))
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ await refreshFleetRoster({ force: true })
+ expect(restNames()).toEqual(['old'])
+ getAgentRoster.mockResolvedValue(roster([], false))
+ await refreshFleetRoster({ force: true })
+ expect(restNames()).toEqual(['old']) // A partial roster failure is not a deletion.
+ expect($profiles.get()).toBe(incoming)
+
+ for (const error of ['HTTP 401', 'connect-on-demand']) {
+ // The main-process registry restores cached names but retains the probe error.
+ const cachedFailure = roster(['stale'], true)
+ cachedFailure.sources[0].error = error
+ getAgentRoster.mockResolvedValue(cachedFailure)
+ await refreshFleetRoster({ force: true })
+ expect(restNames()).toEqual(['old']) // Cached names are reachable, not freshly enumerated.
+ }
+
+ for (const names of [['renamed'], ['created', 'renamed'], []]) {
+ getAgentRoster.mockResolvedValue(roster(names))
+ await refreshFleetRoster({ force: true })
+ expect(restNames()).toEqual(names)
+ expect($profiles.get()).toBe(incoming)
+ }
+
+ // A roster refresh while this source is active must not clear its foreground
+ // list, but an older HTTP response must not resurrect its invalidated cache.
+ activate('source-a')
+ api.mockResolvedValue({ profiles: outgoing })
+ await refreshProfiles()
+ let resolve!: (value: { profiles: ProfileInfo[] }) => void
+ api.mockReturnValueOnce(
+ new Promise(done => {
+ resolve = done
+ })
+ )
+ const stale = refreshProfiles()
+ getAgentRoster.mockResolvedValue(roster(['latest']))
+ await refreshFleetRoster({ force: true })
+ expect($profiles.get()).toBe(outgoing)
+ resolve({ profiles: outgoing })
+ await stale
+ activate('source-b')
+ expect(restNames()).toEqual(['latest'])
+})
+
+it('strands a retry during a same-profile source change without retargeting it to the incoming source', async () => {
+ vi.useFakeTimers()
+ const incoming = [profile('default'), profile('builder')]
+ const unavailable = new Error('HTTP 503')
+ const api = vi.fn().mockRejectedValueOnce(unavailable).mockResolvedValue({ profiles: incoming })
+ vi.stubGlobal('window', { hermesDesktop: { api } })
+ activate('source-a')
+ const old = refreshProfiles().catch(error => error)
+ await vi.advanceTimersByTimeAsync(0) // A is in backoff, not awaiting HTTP.
+
+ activate('source-b') // Direct activation: no beginGatewaySwitch invalidator.
+ await refreshProfiles()
+ await vi.runAllTimersAsync()
+
+ expect(await old).toBe(unavailable)
+ expect(api.mock.calls.map(([request]) => request.connectionId)).toEqual(['source-a', 'source-b'])
+ expect($profiles.get()).toBe(incoming)
+ expect($profilesByConnection.get().get('source-b')).toBe(incoming)
+})
diff --git a/apps/desktop/src/store/profile-switch-failure.test.ts b/apps/desktop/src/store/profile-switch-failure.test.ts
index 30a2dd41f2e..51207f3de1d 100644
--- a/apps/desktop/src/store/profile-switch-failure.test.ts
+++ b/apps/desktop/src/store/profile-switch-failure.test.ts
@@ -1,3 +1,4 @@
+import { atom } from 'nanostores'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// Profile-door activation failure surfacing (#81094): when a secondary's
@@ -36,6 +37,7 @@ vi.mock('@/hermes', () => ({
}
}))
vi.mock('@/store/session', () => ({
+ $connection: atom(null),
setConnection: vi.fn(),
setGatewayState: vi.fn()
}))
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index 61595ba8a92..c397930a96e 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -15,6 +15,7 @@ import {
} from '@/lib/storage'
import { withTimeout } from '@/lib/with-timeout'
import { invalidateCronModelImpactScopeState } from '@/store/cron-model-impact-scope'
+import { $fleetRoster } from '@/store/fleet-roster'
import {
$gateway,
activeGatewayConnectionId,
@@ -58,6 +59,15 @@ export const $activeProfile = atom<string>('default')
// re-fetches on open so a profile created elsewhere shows up.
export const $profiles = atom<ProfileInfo[]>([])
+// Successful lists belong to their source, not whichever gateway is active
+// when a rail renders. Keep them on re-home; a failed incoming read must not
+// borrow the outgoing source's profiles (or discard its cached squares).
+export const $profilesByConnection = atom<ReadonlyMap<string, ProfileInfo[]>>(new Map())
+
+function profileListSource(connection: HermesConnection | null): string {
+ return connection?.connectionId ?? JSON.stringify(['legacy', connection?.mode, connection?.baseUrl])
+}
+
export function setActiveProfile(name: string): void {
$activeProfile.set(name || 'default')
}
@@ -95,6 +105,7 @@ export function refreshProfiles(): Promise<ProfileInfo[]> {
const flight = (async () => {
const epoch = profileListEpoch
+ const source = profileListSource($connection.get())
const MAX_RETRIES = 2
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
@@ -102,7 +113,10 @@ export function refreshProfiles(): Promise<ProfileInfo[]> {
const { profiles } = await getProfiles()
if (epoch === profileListEpoch) {
- $profiles.set(profiles)
+ batch(() => {
+ $profilesByConnection.set(new Map($profilesByConnection.get()).set(source, profiles))
+ $profiles.set(profiles)
+ })
}
return profiles
@@ -120,6 +134,12 @@ export function refreshProfiles(): Promise<ProfileInfo[]> {
// a window to finish routing after WebSocket-ready but pre-HTTP-proxy
// states (global remote mode, #70679).
await new Promise(resolve => setTimeout(resolve, 500 * (attempt + 1)))
+
+ // A switch during backoff must not send this old flight to the new
+ // ambient REST route, even if its eventual cache write is guarded.
+ if (epoch !== profileListEpoch) {
+ throw error
+ }
}
}
@@ -136,6 +156,46 @@ export function refreshProfiles(): Promise<ProfileInfo[]> {
return flight
}
+// Source changes can keep the same profile name (default → default), including
+// direct agent activations that never run the connection-switch wipe.
+let profileListOwner = profileListSource($connection.get())
+
+$connection.subscribe(connection => {
+ const source = profileListSource(connection)
+
+ if (source === profileListOwner) {
+ return
+ }
+
+ profileListOwner = source
+ invalidateProfileListFetches()
+ $profiles.set($profilesByConnection.get().get(source) ?? [])
+})
+
+// Newly published successful enumerations supersede older per-source lists.
+// Do not consult the existing roster on re-home: it may predate the cached list.
+$fleetRoster.listen(roster => {
+ const cached = $profilesByConnection.get()
+ const next = new Map(cached)
+
+ for (const source of roster?.sources ?? []) {
+ // Main can mark cached names reachable even when enumeration failed.
+ if (source.reachable && !source.error) {
+ next.delete(source.connectionId)
+
+ // A pending older read must not repopulate the cache after invalidation.
+ if (source.connectionId === profileListOwner && refreshInFlight) {
+ invalidateProfileListFetches()
+ }
+ }
+ }
+
+ if (next.size !== cached.size) {
+ $profilesByConnection.set(next)
+ }
+ // Leave the active $profiles view alone; the inactive rail falls back to roster.
+})
+
// ── Rail order ─────────────────────────────────────────────────────────────
// User-defined order for the named (non-default) profile squares in the rail.
// Names absent from the list fall back to alphabetical, appended at the tail —