The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): fleet profile rail — every registered gateway's agents on one strip
Zeus-Deusfd565c80e914
diff --git a/apps/desktop/e2e/fleet-profile-rail.spec.ts b/apps/desktop/e2e/fleet-profile-rail.spec.tsnew file mode 100644index 00000000000..c54c619af65--- /dev/null+++ b/apps/desktop/e2e/fleet-profile-rail.spec.ts@@ -0,0 +1,360 @@+/**+ * E2E: the fleet profile rail with two registered gateways.+ *+ * "This device" is the Electron-managed local backend (mock inference). The+ * second gateway, "Homelab", is a REAL second `hermes serve` this spec spawns+ * with its own HERMES_HOME, profiles and session token, registered in the v2+ * connections.json as a remote URL connection. A click on an at-rest square+ * therefore performs the same dial → commit → re-home the statusbar switcher+ * does, against a real backend — not a stub.+ *+ * Prerequisite: `npm run build` must have been run so dist/ exists, and the+ * repo's Python venv (`.venv`) must exist for both backends.+ */++import { type ChildProcess, spawn, spawnSync } from 'node:child_process'+import * as fs from 'node:fs'+import * as net from 'node:net'+import * as path from 'node:path'++import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,+ type Sandbox,+ waitForAppReady,+ writeEnvFile,+ writeMockProviderConfig,+} from './fixtures'+import { startMockServer } from './mock-server'+import { type ElectronApplication, expect, type Page, test } from './test'++const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')+const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')++const REMOTE_LABEL = 'Homelab'+const REMOTE_ID = 'homelab'+const REMOTE_TOKEN = 'e2e-fleet-homelab-token'++interface RemoteGateway {+ url: string+ home: string+ close: () => Promise<void>+}++function findHermesBinary(): string {+ const venv = path.join(REPO_ROOT, '.venv', 'bin', 'hermes')++ if (fs.existsSync(venv)) {+ return venv+ }++ const result = spawnSync('which', ['hermes'], { encoding: 'utf8' })++ if (result.status === 0 && result.stdout.trim()) {+ return result.stdout.trim()+ }++ throw new Error('hermes binary not found: create the repo venv (uv sync) or put hermes on PATH')+}++async function freePort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = net.createServer()+ server.unref()+ server.on('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address() as net.AddressInfo+ server.close(() => resolve(port))+ })+ })+}++/** Seed `<home>/profiles/<name>/` so the backend's /api/profiles lists it. */+function seedProfiles(home: string, names: string[]): void {+ for (const name of names) {+ const dir = path.join(home, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ fs.writeFileSync(path.join(dir, 'config.yaml'), '', 'utf8')+ }+}++/**+ * Spawn a second, fully real `hermes serve` as the remote gateway. Its+ * session token is pinned through HERMES_DASHBOARD_SESSION_TOKEN so the+ * registry entry can carry a plaintext token envelope.+ */+async function startRemoteGateway(root: string, mockUrl: string, profiles: string[]): Promise<RemoteGateway> {+ const home = path.join(root, 'homelab-home')+ fs.mkdirSync(home, { recursive: true })+ writeMockProviderConfig(home, mockUrl)+ writeEnvFile(home)+ seedProfiles(home, profiles)++ const port = await freePort()+ const url = `http://127.0.0.1:${port}`++ const child: ChildProcess = spawn(+ findHermesBinary(),+ ['serve', '--host', '127.0.0.1', '--port', String(port), '--skip-build'],+ {+ cwd: REPO_ROOT,+ detached: true,+ env: {+ ...process.env,+ HERMES_HOME: home,+ HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ )++ let log = ''+ child.stdout?.on('data', (chunk: Buffer) => {+ log += chunk.toString()+ })+ child.stderr?.on('data', (chunk: Buffer) => {+ log += chunk.toString()+ })++ const deadline = Date.now() + 90_000++ while (Date.now() < deadline) {+ if (child.exitCode !== null) {+ throw new Error(`remote hermes serve exited early (${child.exitCode}):\n${log}`)+ }++ try {+ const response = await fetch(`${url}/api/status`, {+ headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN },+ })++ if (response.ok) {+ break+ }+ } catch {+ // not up yet+ }++ await new Promise(resolve => setTimeout(resolve, 500))+ }++ if (Date.now() >= deadline) {+ throw new Error(`remote hermes serve never became ready:\n${log}`)+ }++ return {+ url,+ home,+ close: async () => {+ if (child.pid && child.exitCode === null) {+ try {+ process.kill(-child.pid, 'SIGTERM')+ } catch {+ child.kill('SIGTERM')+ }+ }++ await new Promise(resolve => setTimeout(resolve, 500))+ },+ }+}++function writeConnectionsRegistry(sandbox: Sandbox, remoteUrl: string): void {+ fs.writeFileSync(+ path.join(sandbox.userDataDir, 'connections.json'),+ JSON.stringify(+ {+ version: 2,+ primary: 'local',+ launchMode: 'primary',+ lastUsed: 'local',+ connections: [+ { id: 'local', kind: 'local', label: 'This device' },+ {+ id: REMOTE_ID,+ kind: 'remote',+ label: REMOTE_LABEL,+ url: remoteUrl,+ authMode: 'token',+ token: { encoding: 'plain', value: REMOTE_TOKEN },+ },+ ],+ },+ null,+ 2,+ ),+ { encoding: 'utf8', mode: 0o600 },+ )+}++// FLEET_RAIL_SCREENSHOT_DIR=<dir> saves full-window captures at the key+// states — handy for design review; never part of the assertions.+async function capture(page: Page, name: string): Promise<void> {+ const dir = process.env.FLEET_RAIL_SCREENSHOT_DIR++ if (!dir) {+ return+ }++ fs.mkdirSync(dir, { recursive: true })+ await page.screenshot({ path: path.join(dir, `${name}.png`) })+}++const rail = (page: Page) => page.locator('[data-slot="profile-rail"]')+const gatewayGroup = (page: Page, id: string) => rail(page).locator(`[data-slot="profile-rail-gateway"][data-connection-id="${id}"]`)+const activeGatewayLabel = (page: Page) => page.getByRole('button', { name: /^Registered gateways: / })++async function groupOrder(page: Page): Promise<Array<[string, boolean]>> {+ return rail(page).locator('[data-slot="profile-rail-gateway"]').evaluateAll(nodes =>+ nodes.map(node => [node.getAttribute('data-connection-id') ?? '', node.getAttribute('data-active') === 'true'] as [string, boolean]),+ )+}++test.describe('fleet profile rail — two registered gateways', () => {+ test.describe.configure({ mode: 'serial' })++ let mock: Awaited<ReturnType<typeof startMockServer>>+ let sandbox: Sandbox+ let remote: RemoteGateway+ let app: ElectronApplication+ let page: Page++ test.beforeAll(async () => {+ test.setTimeout(240_000)+ mock = await startMockServer()+ sandbox = createSandbox('fleet')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ // A named profile on This device too, so the active group has a square+ // beside its home pill. "research" exists on BOTH gateways on purpose: the+ // rail must keep the two apart by gateway, never by name alone.+ seedProfiles(sandbox.hermesHome, ['research'])++ remote = await startRemoteGateway(sandbox.root, mock.url, ['inbox', 'research'])+ writeConnectionsRegistry(sandbox, remote.url)++ ;({ app, page } = await launchDesktop(buildAppEnv(sandbox)))+ await waitForAppReady({ app, page } as MockBackendFixture, 120_000)+ // Let boot settle fully (the gateway health item reports "ready" once the+ // primary socket is open) so the boot-time launch-mode restore has run+ // before any click — the rail must then hold whatever the user picks.+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 120_000 })+ await page.waitForTimeout(2_000)+ })++ test.afterAll(async () => {+ await app?.close().catch(() => undefined)+ await remote?.close()+ await mock?.close()+ sandbox?.cleanup()+ })++ test('lays both gateways on one strip, active gateway in its registry slot', async () => {+ // The statusbar readout names the gateway the workspace is on.+ await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Registered gateways: This device', { timeout: 60_000 })++ // The remote gateway's group appears once the roster has enumerated it.+ const homelab = gatewayGroup(page, REMOTE_ID)+ await expect(homelab).toBeVisible({ timeout: 60_000 })+ await expect(homelab.getByRole('button', { name: `default · ${REMOTE_LABEL}` })).toBeVisible()+ await expect(homelab.getByRole('button', { name: `inbox · ${REMOTE_LABEL}` })).toBeVisible()+ await expect(homelab.getByRole('button', { name: `research · ${REMOTE_LABEL}` })).toBeVisible()+ await expect(homelab).toHaveAttribute('data-reachable', 'true')++ // Its marker carries the remote (network) glyph.+ await expect(+ rail(page).locator(`[data-slot="profile-rail-divider"][data-connection-id="${REMOTE_ID}"] [data-connection-kind="remote"]`),+ ).toBeVisible()++ // This device is the active group: its squares are unqualified, as before.+ const local = gatewayGroup(page, 'local')+ await expect(local).toHaveAttribute('data-active', 'true')+ await expect(local.getByRole('button', { name: 'research', exact: true })).toBeVisible()++ // Registry order: This device first, Homelab second.+ expect(await groupOrder(page)).toEqual([+ ['local', true],+ [REMOTE_ID, false],+ ])++ // Fleet pill replaces the default↔all toggle; the single-gateway plug is gone.+ await expect(rail(page).getByRole('button', { name: 'All profiles on this gateway' })).toBeVisible()+ await expect(rail(page).getByRole('button', { name: 'Manage gateways…' })).toHaveCount(0)++ await gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }).hover()+ await capture(page, '1-on-this-device-hover-inbox-homelab')+ })++ test('clicking an at-rest square re-homes onto that exact gateway and profile', async () => {+ test.setTimeout(180_000)+ await gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }).click()++ // The workspace follows the agent: statusbar readout flips to Homelab…+ await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', `Registered gateways: ${REMOTE_LABEL}`, { timeout: 120_000 })++ // …Homelab's group is now the active one, on the clicked profile…+ const homelab = gatewayGroup(page, REMOTE_ID)+ await expect(homelab).toHaveAttribute('data-active', 'true', { timeout: 30_000 })+ await expect(homelab.getByRole('button', { name: 'inbox', exact: true })).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 })++ // …This device is at rest with qualified squares…+ const local = gatewayGroup(page, 'local')+ await expect(local).toHaveAttribute('data-active', 'false')+ await expect(local.getByRole('button', { name: 'research · This device' })).toBeVisible()++ // …and nothing moved: the order is still This device, then Homelab.+ expect(await groupOrder(page)).toEqual([+ ['local', false],+ [REMOTE_ID, true],+ ])++ await capture(page, '2-re-homed-on-homelab-inbox')+ })++ test('an at-rest square offers gateway-scoped actions, never the legacy remote override', async () => {+ const square = gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' })+ await square.click({ button: 'right' })++ const menu = page.getByRole('menu', { name: 'Actions' })+ await expect(menu).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: 'Switch to research on This device' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: 'Rename…' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: 'Edit SOUL.md…' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: 'Delete' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: 'Connect to a remote host…' })).toHaveCount(0)++ await capture(page, '3-at-rest-square-context-menu')+ await page.keyboard.press('Escape')+ await expect(menu).toBeHidden()+ })++ test('editing SOUL.md on an at-rest square reads the owning gateway, not the foreground one', async () => {+ const square = gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' })+ await square.click({ button: 'right' })+ await page.getByRole('menu', { name: 'Actions' }).getByRole('menuitem', { name: 'Edit SOUL.md…' }).click()++ const dialog = page.getByRole('dialog')+ await expect(dialog).toBeVisible()+ await expect(dialog.getByText('research · This device · SOUL.md')).toBeVisible()+ await page.keyboard.press('Escape')+ await expect(dialog).toBeHidden()+ })++ test('switching back lands on the clicked profile of This device and keeps the order', async () => {+ test.setTimeout(180_000)+ await gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' }).click()++ await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Registered gateways: This device', { timeout: 120_000 })+ const local = gatewayGroup(page, 'local')+ await expect(local).toHaveAttribute('data-active', 'true', { timeout: 30_000 })+ await expect(local.getByRole('button', { name: 'research', exact: true })).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 })+ await expect(gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` })).toBeVisible()++ expect(await groupOrder(page)).toEqual([+ ['local', true],+ [REMOTE_ID, false],+ ])+ })+})diff --git a/apps/desktop/src/api/profiles.ts b/apps/desktop/src/api/profiles.tsindex b021639ab99..12b2f6cd20e 100644--- a/apps/desktop/src/api/profiles.ts+++ b/apps/desktop/src/api/profiles.ts@@ -23,8 +23,23 @@ export function createProfile(body: ProfileCreatePayload): Promise<{ name: strin})}-export function renameProfile(name: string, newName: string): Promise<{ name: string; ok: boolean; path: string }> {+// Explicit (connection, profile) pin for a profile that lives on a gateway+// other than the foreground one — the fleet profile rail edits a remote+// square's SOUL/name in place. Same contract as deleteProfile's scope.+function profileOwnerScoped(scope?: ProfileScope): { connectionId?: string; profile?: string } {+ return {+ ...capabilityScoped(scope),+ ...(scope && typeof scope === 'object' && scope.connectionId?.trim() === 'local' ? { connectionId: 'local' } : {})+ }+}++export function renameProfile(+ name: string,+ newName: string,+ scope?: ProfileScope+): Promise<{ name: string; ok: boolean; path: string }> {return hermesApi<{ name: string; ok: boolean; path: string }>({+ ...profileOwnerScoped(scope),path: `/api/profiles/${encodeURIComponent(name)}`,method: 'PATCH',body: { new_name: newName }@@ -44,21 +59,22 @@ export function deleteProfile(name: string, scope?: ProfileScope): Promise<{ ok:}return hermesApi<{ ok: boolean; path: string }>({- ...capabilityScoped(scope),- ...(scope && typeof scope === 'object' && scope.connectionId?.trim() === 'local' ? { connectionId: 'local' } : {}),+ ...profileOwnerScoped(scope),path: `/api/profiles/${encodeURIComponent(normalized)}`,method: 'DELETE'})}-export function getProfileSoul(name: string): Promise<ProfileSoul> {+export function getProfileSoul(name: string, scope?: ProfileScope): Promise<ProfileSoul> {return hermesApi<ProfileSoul>({+ ...profileOwnerScoped(scope),path: `/api/profiles/${encodeURIComponent(name)}/soul`})}-export function updateProfileSoul(name: string, content: string): Promise<{ ok: boolean }> {+export function updateProfileSoul(name: string, content: string, scope?: ProfileScope): Promise<{ ok: boolean }> {return hermesApi<{ ok: boolean }>({+ ...profileOwnerScoped(scope),path: `/api/profiles/${encodeURIComponent(name)}/soul`,method: 'PUT',body: { content }diff --git a/apps/desktop/src/app/chat/sidebar/connection-glyph.tsx b/apps/desktop/src/app/chat/sidebar/connection-glyph.tsxnew file mode 100644index 00000000000..f553d7f6f09--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/connection-glyph.tsx@@ -0,0 +1,28 @@+import type { DesktopRegistryConnection } from '@/global'+import { Cloud, Monitor, Network, Terminal } from '@/lib/icons'++// One glyph per connection kind — device, cloud, network, terminal — shared by+// the statusbar switcher, its menu, and the fleet profile rail so a gateway+// looks the same wherever it is named. Dependency-free on purpose (icons and+// a type only) so light components can use it without pulling in stores.+export function ConnectionGlyph({ connection }: { connection: Pick<DesktopRegistryConnection, 'kind'> }) {+ const Icon =+ connection.kind === 'local'+ ? Monitor+ : connection.kind === 'cloud'+ ? Cloud+ : connection.kind === 'ssh'+ ? Terminal+ : Network++ return (+ <span+ aria-hidden="true"+ className="grid size-3.5 shrink-0 place-items-center text-(--ui-text-quaternary)"+ data-connection-kind={connection.kind}+ data-slot="connection-glyph"+ >+ <Icon className="size-3" />+ </span>+ )+}diff --git a/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx b/apps/desktop/src/app/chat/sidebar/connection-switcher.tsxindex ce0e56b801b..563ded9a526 100644--- a/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/connection-switcher.tsx@@ -23,7 +23,7 @@ import {sortConnectionsForDisplay} from '@/lib/connection-display'import { triggerHaptic } from '@/lib/haptics'-import { Cloud, Loader2, Monitor, Network, Terminal } from '@/lib/icons'+import { Loader2 } from '@/lib/icons'import { cn } from '@/lib/utils'import { $desktopBoot } from '@/store/boot'import {@@ -38,6 +38,8 @@ import { closeFindBar } from '@/store/find-in-page'import { notifyError } from '@/store/notifications'import { isAuxiliaryWindow, isPeerInstanceWindow } from '@/store/windows'+import { ConnectionGlyph } from './connection-glyph'+export function ConnectionSwitcher({ compact = false, onConnect }: { compact?: boolean; onConnect: () => void }) {const { t } = useI18n()const registry = useStore($connectionsRegistry)@@ -293,28 +295,6 @@ function ManageGatewaysLabel({ label }: { label: string }) {)}-function ConnectionGlyph({ connection }: { connection: DesktopRegistryConnection }) {- const Icon =- connection.kind === 'local'- ? Monitor- : connection.kind === 'cloud'- ? Cloud- : connection.kind === 'ssh'- ? Terminal- : Network-- return (- <span- aria-hidden="true"- className="grid size-3.5 shrink-0 place-items-center text-(--ui-text-quaternary)"- data-connection-kind={connection.kind}- data-slot="connection-glyph"- >- <Icon className="size-3" />- </span>- )-}-function ConnectionLabel({ connection }: { connection: DesktopRegistryConnection }) {return (<span className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden" title={connectionTooltip(connection)}>diff --git a/apps/desktop/src/app/chat/sidebar/fleet-rail.test.ts b/apps/desktop/src/app/chat/sidebar/fleet-rail.test.tsnew file mode 100644index 00000000000..0b786c2a5ad--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/fleet-rail.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest'++import type { DesktopAgentRoster, DesktopRegistryConnection } from '@/global'++import { buildRestGroups, countRestAgents, fleetRouteKey } from './fleet-rail'++const connections: DesktopRegistryConnection[] = [+ { id: 'pandora', kind: 'remote', label: 'Pandora', url: 'https://pandora.example' },+ { id: 'local', kind: 'local', label: 'This device' },+ { id: 'vps', kind: 'ssh', label: 'VPS', host: 'vps.example' }+] as DesktopRegistryConnection[]++const roster: DesktopAgentRoster = {+ agents: [+ { connectionId: 'pandora', connectionKind: 'remote', connectionLabel: 'Pandora', profile: 'default', handle: 'hermes-pandora' },+ { connectionId: 'pandora', connectionKind: 'remote', connectionLabel: 'Pandora', profile: 'scout', handle: 'scout' },+ { connectionId: 'pandora', connectionKind: 'remote', connectionLabel: 'Pandora', profile: 'omer', handle: 'omer-pandora' },+ { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'default', handle: 'hermes' },+ { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'omer', handle: 'omer-this-device' }+ ],+ sources: [+ { connectionId: 'pandora', kind: 'remote', label: 'Pandora', reachable: true },+ { connectionId: 'local', kind: 'local', label: 'This device', reachable: true },+ { connectionId: 'vps', kind: 'ssh', label: 'VPS', reachable: false, error: 'ssh: connect timed out' }+ ]+}++describe('buildRestGroups', () => {+ it('lists every gateway except the active one, in switcher order, regardless of which is active', () => {+ const fromPandora = buildRestGroups({ activeConnectionId: 'pandora', connections, roster })+ const fromLocal = buildRestGroups({ activeConnectionId: 'local', connections, roster })++ // This device first (switcher order), then by label — never "active first".+ expect(fromPandora.map(group => group.connectionId)).toEqual(['local', 'vps'])+ expect(fromLocal.map(group => group.connectionId)).toEqual(['pandora', 'vps'])+ })++ it('carries each gateway default as its own square plus named profiles alphabetically', () => {+ const [local] = buildRestGroups({ activeConnectionId: 'pandora', connections, roster })++ expect(local.defaultAgent).toMatchObject({ connectionId: 'local', profile: 'default', isDefault: true, handle: 'hermes' })+ expect(local.named.map(agent => agent.profile)).toEqual(['omer'])+ expect(local.named[0]).toMatchObject({ connectionLabel: 'This device', handle: 'omer-this-device', isDefault: false })++ const [pandora] = buildRestGroups({ activeConnectionId: 'local', connections, roster })+ expect(pandora.named.map(agent => agent.profile)).toEqual(['omer', 'scout'])+ })++ it('keeps an unreachable gateway on the strip with its default square and marks it', () => {+ const groups = buildRestGroups({ activeConnectionId: 'pandora', connections, roster })+ const vps = groups.find(group => group.connectionId === 'vps')++ expect(vps).toBeDefined()+ expect(vps?.reachable).toBe(false)+ expect(vps?.defaultAgent.profile).toBe('default')+ expect(vps?.named).toEqual([])+ })++ it('shows every gateway with just its default before the roster has loaded', () => {+ const groups = buildRestGroups({ activeConnectionId: 'pandora', connections, roster: null })++ expect(groups.map(group => [group.connectionId, group.reachable, group.named.length])).toEqual([+ ['local', true, 0],+ ['vps', true, 0]+ ])+ })++ it('skips a registration the roster collapsed into another (same backend, two addresses)', () => {+ const twin: DesktopRegistryConnection = { id: 'pandora-lan', kind: 'remote', label: 'Pandora LAN', url: 'http://10.0.0.2' } as DesktopRegistryConnection+ const groups = buildRestGroups({ activeConnectionId: 'local', connections: [...connections, twin], roster })++ expect(groups.map(group => group.connectionId)).toEqual(['pandora', 'vps'])+ })++ it('counts every at-rest square for the condensed threshold', () => {+ const groups = buildRestGroups({ activeConnectionId: 'pandora', connections, roster })++ // local: default + omer; vps: default+ expect(countRestAgents(groups)).toBe(3)+ expect(fleetRouteKey('local', 'omer')).toBe('local::omer')+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/fleet-rail.ts b/apps/desktop/src/app/chat/sidebar/fleet-rail.tsnew file mode 100644index 00000000000..f0bdc16d0d6--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/fleet-rail.ts@@ -0,0 +1,106 @@+import type { DesktopAgentRoster, DesktopConnectionKind, DesktopRegistryConnection } from '@/global'+import { sortConnectionsForDisplay } from '@/lib/connection-display'++// 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+// React and stores so the ordering/collapse rules are unit-testable.++export interface FleetAgent {+ connectionId: string+ connectionKind: DesktopConnectionKind+ connectionLabel: string+ /** Profile name as the owning gateway knows it. */+ profile: string+ /** Pre-computed @name-device mention handle from the roster. */+ handle: string+ isDefault: boolean+}++export interface FleetGroup {+ connectionId: string+ kind: DesktopConnectionKind+ label: string+ reachable: boolean+ /** The gateway's default profile — every Hermes home has one, so a group+ * always carries it even before the roster has been enumerated. */+ defaultAgent: FleetAgent+ /** Named (non-default) profiles, alphabetical for a stable strip. */+ named: FleetAgent[]+}++export const DEFAULT_PROFILE = 'default'++export function fleetRouteKey(connectionId: string, profile: string): string {+ return `${connectionId}::${profile}`+}++const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })++/**+ * Groups for every registered gateway EXCEPT the active one, in the same order+ * the connection switcher lists them (This device first, then by label), so the+ * rail and the readout agree. Positions never depend on which gateway is+ * active — a square must not move under the pointer when it is clicked.+ *+ * - No roster yet → each gateway still shows its default square, so the strip+ * is complete on first paint and only gains named squares later.+ * - A gateway the roster neither lists as a source nor attributes agents to+ * was collapsed into another registration of the same backend (install_id+ * match) → skipped, never shown twice.+ */+export function buildRestGroups({+ activeConnectionId,+ connections,+ roster+}: {+ activeConnectionId: null | string+ connections: readonly DesktopRegistryConnection[]+ roster: DesktopAgentRoster | null+}): FleetGroup[] {+ const groups: FleetGroup[] = []++ for (const connection of sortConnectionsForDisplay(connections)) {+ if (connection.id === activeConnectionId) {+ continue+ }++ const source = roster?.sources.find(candidate => candidate.connectionId === connection.id)+ const rows = roster?.agents.filter(agent => agent.connectionId === connection.id) ?? []++ if (roster && !source && rows.length === 0) {+ continue+ }++ const toAgent = (profile: string, handle?: string): FleetAgent => ({+ connectionId: connection.id,+ connectionKind: connection.kind,+ connectionLabel: connection.label,+ profile,+ handle: handle ?? profile,+ isDefault: profile === DEFAULT_PROFILE+ })++ const defaultRow = rows.find(row => row.profile === DEFAULT_PROFILE)++ const named = rows+ .filter(row => row.profile !== DEFAULT_PROFILE)+ .map(row => toAgent(row.profile, row.handle))+ .sort((left, right) => collator.compare(left.profile, right.profile))++ groups.push({+ connectionId: connection.id,+ kind: connection.kind,+ label: connection.label,+ reachable: source?.reachable ?? true,+ defaultAgent: toAgent(DEFAULT_PROFILE, defaultRow?.handle),+ named+ })+ }++ return groups+}++/** Every square on the rest side, for the condensed-menu threshold. */+export function countRestAgents(groups: readonly FleetGroup[]): number {+ return groups.reduce((total, group) => total + 1 + group.named.length, 0)+}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.tsxindex a559609564a..dc008fac1bc 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@@ -61,7 +61,12 @@ vi.mock('@/store/profile', () => ({sortByProfileOrder: (profiles: unknown[]) => profiles}))-vi.mock('@/store/connections', () => ({ $hasMultipleConnections: atom(false) }))+vi.mock('@/store/connections', () => ({+ $activeConnectionId: atom(null),+ $connectionsRegistry: atom(null),+ $hasMultipleConnections: atom(false),+ selectConnection: vi.fn()+}))vi.mock('@/store/profile-share', () => ({runExportProfileFlow: vi.fn(),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.tsxnew file mode 100644index 00000000000..d2bc44f0729--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx@@ -0,0 +1,338 @@+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { atom } from 'nanostores'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { DesktopAgentRoster, DesktopConnectionsRegistry } from '@/global'++import { ProfileRail } from './profile-switcher'++// The fleet rail: with several registered gateways, every gateway's agents sit+// on the one strip — the active gateway's squares exactly as before, the rest+// as at-rest groups behind a hairline + kind glyph. Clicking an at-rest square+// performs the same re-home the statusbar switcher does, on that exact+// (gateway, profile). Single-gateway rendering must stay byte-identical.++const navigate = vi.fn()+const selectConnection = vi.fn()+const selectProfile = vi.fn()+const getAgentRoster = vi.fn()++vi.mock('react-router', () => ({+ useNavigate: () => navigate+}))++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ common: { cancel: 'Cancel', delete: 'Delete' },+ profiles: {+ actions: 'Actions',+ allProfiles: 'All profiles',+ autoColor: 'Auto',+ color: 'Color…',+ colorFor: 'Color',+ connectGateway: 'Manage gateways…',+ editSoul: 'Edit SOUL.md…',+ exportProfile: 'Export profile…',+ failedLoadSoul: 'Failed to load SOUL.md',+ failedSaveSoul: 'Failed to save SOUL.md',+ fleet: {+ allOnGateway: 'All profiles on this gateway',+ deleteOn: (gateway: string) => ` on ${gateway}`,+ gateway: (gateway: string) => `Profiles on ${gateway}`,+ gatewayUnreachable: (gateway: string) => `${gateway} · unreachable`,+ onGateway: (name: string, gateway: string) => `${name} · ${gateway}`,+ switchTo: (name: string, gateway: string) => `Switch to ${name} on ${gateway}`+ },+ importProfile: 'Import profile…',+ manageProfiles: 'Manage profiles…',+ newProfile: 'New profile',+ remoteOverride: {+ badge: (host: string) => `Runs on ${host}`,+ menuItem: 'Connect to a remote host…'+ },+ renameMenu: 'Rename…',+ saveSoul: 'Save',+ saving: 'Saving…',+ setColor: (color: string) => `Set color ${color}`,+ showAllProfiles: 'Show all profiles',+ soulSaved: 'SOUL.md saved',+ switchConnectionFailed: (name: string) => `Could not connect to ${name}`,+ switchToProfile: (name: string) => `Switch to ${name}`,+ title: 'Profiles'+ },+ settings: { connections: { kindCloud: 'Cloud', kindLocal: 'This device', kindRemote: 'Remote', kindSsh: 'SSH' } }+ }+ })+}))++vi.mock('@/store/profile', () => ({+ $activeGatewayProfile: atom('default'),+ $profileColors: atom({}),+ $profileCreateRequest: atom(0),+ $profileOrder: atom([]),+ $profiles: atom([{ is_default: true, name: 'default' }]),+ $profileScope: atom('default'),+ ALL_PROFILES: '*',+ normalizeProfileKey: (name: string) => name,+ profileLabel: (profile: { display_name?: string; name: string }) =>+ (profile.display_name ?? '').trim() || profile.name,+ refreshActiveProfile: vi.fn().mockResolvedValue(undefined),+ selectProfile: (name: string) => selectProfile(name),+ setProfileColor: vi.fn(),+ setProfileOrder: vi.fn(),+ setShowAllProfiles: vi.fn(),+ sortByProfileOrder: (profiles: unknown[]) => profiles+}))++vi.mock('@/store/connections', () => ({+ $activeConnectionId: atom<null | string>(null),+ $connectionsRegistry: atom<DesktopConnectionsRegistry | null>(null),+ $hasMultipleConnections: atom(false),+ selectConnection: (...args: unknown[]) => selectConnection(...args)+}))++vi.mock('@/store/profile-share', () => ({+ runExportProfileFlow: vi.fn(),+ runImportProfileFlow: vi.fn()+}))++vi.mock('./use-profile-prewarm', () => ({+ useProfilePrewarm: () => ({ cancelPrewarm: vi.fn(), startPrewarm: vi.fn() })+}))++vi.mock('./use-profile-rail-refresh-on-active', () => ({+ useProfileRailRefreshOnActive: () => undefined+}))++vi.mock('@/hermes', () => ({+ getProfileSoul: vi.fn().mockResolvedValue({ content: '' }),+ updateProfileSoul: vi.fn()+}))++vi.mock('@/components/chat/code-editor', () => ({ CodeEditor: () => null }))+vi.mock('../../profiles/create-profile-dialog', () => ({ CreateProfileDialog: () => null }))+vi.mock('../../profiles/delete-profile-dialog', () => ({ DeleteProfileDialog: () => null }))+vi.mock('../../profiles/rename-profile-dialog', () => ({ RenameProfileDialog: () => null }))++const connectionsStore = await import('@/store/connections')+const hasMultipleConnections = connectionsStore.$hasMultipleConnections as ReturnType<typeof atom<boolean>>+const activeConnectionId = connectionsStore.$activeConnectionId as ReturnType<typeof atom<null | string>>++const connectionsRegistry = connectionsStore.$connectionsRegistry as ReturnType<+ typeof atom<DesktopConnectionsRegistry | null>+>++const { $profiles, $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')++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' }+ ],+ launchMode: 'primary',+ lastUsed: 'pandora',+ primary: 'pandora',+ version: 2+} as DesktopConnectionsRegistry++const roster: DesktopAgentRoster = {+ agents: [+ { connectionId: 'pandora', connectionKind: 'remote', connectionLabel: 'Pandora', profile: 'default', handle: 'hermes-pandora' },+ { connectionId: 'pandora', connectionKind: 'remote', connectionLabel: 'Pandora', profile: 'scout', handle: 'scout' },+ { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'default', handle: 'hermes' },+ { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'omer', handle: 'omer' }+ ],+ sources: [+ { connectionId: 'pandora', kind: 'remote', label: 'Pandora', reachable: true },+ { connectionId: 'local', kind: 'local', label: 'This device', reachable: true },+ { connectionId: 'vps', kind: 'ssh', label: 'VPS', reachable: false, error: 'timed out' }+ ]+}++function armFleet() {+ hasMultipleConnections.set(true)+ connectionsRegistry.set(registry)+ activeConnectionId.set('pandora')+ profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'scout' }+ ])+}++async function renderFleet() {+ const view = render(<ProfileRail />)++ // The roster arrives asynchronously via the Electron bridge.+ await act(async () => {+ await Promise.resolve()+ await Promise.resolve()+ })++ return view.container+}++beforeEach(() => {+ getAgentRoster.mockResolvedValue(roster)+ selectConnection.mockResolvedValue(undefined)+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = { getAgentRoster }+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ _resetFleetRosterForTests()+ hasMultipleConnections.set(false)+ connectionsRegistry.set(null)+ activeConnectionId.set(null)+ profileScope.set('default')+ profiles.set([{ is_default: true, name: 'default' }])+ delete (window as { hermesDesktop?: unknown }).hermesDesktop+})++describe('ProfileRail fleet mode', () => {+ it('stays on the single-gateway path with one registered gateway', async () => {+ const container = await renderFleet()++ expect(getAgentRoster).not.toHaveBeenCalled()+ expect(screen.queryByRole('group', { name: /^Profiles on/ })).toBeNull()+ expect(container.querySelector('[data-slot="profile-rail-divider"]')).toBeNull()+ expect(screen.getByRole('button', { name: 'Manage gateways…' })).toBeTruthy()+ })++ it('lays every other gateway on the strip as an at-rest group, in switcher order', async () => {+ armFleet()+ const container = await renderFleet()++ expect(getAgentRoster).toHaveBeenCalledTimes(1)++ const groups = Array.from(container.querySelectorAll('[data-slot="profile-rail-gateway"]')).map(node => [+ node.getAttribute('data-connection-id'),+ node.getAttribute('data-active') === 'true'+ ])++ // Registry order for the whole strip — This device first (switcher+ // order), then by label — with the active gateway (Pandora) in ITS slot,+ // never pulled to the front.+ expect(groups).toEqual([+ ['local', false],+ ['pandora', true],+ ['vps', false]+ ])++ // Every group is headed by its kind glyph; hairlines only between groups.+ const dividers = Array.from(container.querySelectorAll('[data-slot="profile-rail-divider"]')).map(node =>+ node.getAttribute('data-connection-id')+ )++ expect(dividers).toEqual(['local', 'pandora', 'vps'])++ 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()++ // The active gateway's own squares are unchanged and unqualified.+ expect(screen.getByRole('button', { name: 'scout' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'default' })).toBeTruthy()++ // Fleet pill: "all on this gateway" replaces the default↔all toggle.+ expect(screen.getByRole('button', { name: 'All profiles on this gateway' })).toBeTruthy()+ expect(screen.queryByRole('button', { name: 'Manage gateways…' })).toBeNull()+ })++ it('marks an unreachable gateway but never hides it', async () => {+ 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')+ expect(+ container.querySelector(+ '[data-slot="profile-rail-divider"][data-connection-id="vps"] [data-slot="profile-rail-unreachable"]'+ )+ ).toBeTruthy()+ expect(within(vps as HTMLElement).getByRole('button', { name: 'default · VPS' })).toBeTruthy()+ })++ it('re-homes onto the exact (gateway, profile) when an at-rest square is clicked', async () => {+ armFleet()+ await renderFleet()++ let settle: () => void = () => undefined+ selectConnection.mockImplementationOnce(() => new Promise<void>(resolve => (settle = resolve)))++ const omer = screen.getByRole('button', { name: 'omer · This device' })+ fireEvent.click(omer)++ expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'omer' })+ expect(selectProfile).not.toHaveBeenCalled()+ // The dial spinner sits on the clicked square, not in the statusbar.+ expect(omer.getAttribute('aria-busy')).toBe('true')++ await act(async () => {+ settle()+ await Promise.resolve()+ })++ expect(omer.getAttribute('aria-busy')).toBeNull()+ })++ it('re-homes onto another gateway default from its home square', async () => {+ armFleet()+ await renderFleet()++ fireEvent.click(screen.getByRole('button', { name: 'default · This device' }))++ expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'default' })+ })++ it('keeps the active gateway click on the plain profile path', async () => {+ armFleet()+ await renderFleet()++ fireEvent.click(screen.getByRole('button', { name: 'scout' }))++ expect(selectProfile).toHaveBeenCalledWith('scout')+ expect(selectConnection).not.toHaveBeenCalled()+ })++ it('keeps every group in its slot when a different gateway is active', async () => {+ armFleet()+ activeConnectionId.set('local')+ profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'omer' }+ ])+ const container = await renderFleet()++ const groups = Array.from(container.querySelectorAll('[data-slot="profile-rail-gateway"]')).map(node => [+ node.getAttribute('data-connection-id'),+ node.getAttribute('data-active') === 'true'+ ])++ expect(groups).toEqual([+ ['local', true],+ ['pandora', false],+ ['vps', false]+ ])+ expect(screen.getByRole('button', { name: 'scout · Pandora' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'omer' })).toBeTruthy()+ })++ it('counts the whole fleet toward the condensed threshold and sections the menu by gateway', async () => {+ armFleet()+ profiles.set([+ { 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.+ const container = await renderFleet()++ expect(screen.getByRole('button', { name: 'Profiles' })).toBeTruthy()+ expect(container.querySelector('[data-slot="profile-rail-rest-square"]')).toBeNull()+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsxindex a29e75453aa..53fa1b5c109 100644--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx@@ -19,9 +19,10 @@ import {} from '@dnd-kit/sortable'import { CSS } from '@dnd-kit/utilities'import { useStore } from '@nanostores/react'-import { useEffect, useRef, useState } from 'react'+import { Fragment, useEffect, useMemo, useRef, useState } from 'react'import { useNavigate } from 'react-router'+import type { ProfileScope } from '@/api/client'import { CodeEditor } from '@/components/chat/code-editor'import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'@@ -32,17 +33,22 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuLabel,DropdownMenuRadioGroup,DropdownMenuRadioItem,+ dropdownMenuSectionLabel,DropdownMenuSeparator,DropdownMenuTrigger} from '@/components/ui/dropdown-menu'import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover'import { ProfileGlyph } from '@/components/ui/profile-glyph'import { Tip, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'+import type { DesktopRegistryConnection } from '@/global'import { getProfileSoul, updateProfileSoul } from '@/hermes'import { useI18n } from '@/i18n'+import { sortConnectionsForDisplay } from '@/lib/connection-display'import { triggerHaptic } from '@/lib/haptics'+import { Loader2 } from '@/lib/icons'import { PROFILE_SWATCHES, profileColorSoft, resolveProfileColor } from '@/lib/profile-color'import {REORDER_DRAG_TRANSITION_CSS,@@ -51,7 +57,13 @@ import {reorderStepHaptic} from '@/lib/reorder'import { cn } from '@/lib/utils'-import { $hasMultipleConnections } from '@/store/connections'+import {+ $activeConnectionId,+ $connectionsRegistry,+ $hasMultipleConnections,+ selectConnection+} from '@/store/connections'+import { $fleetRoster, refreshFleetRoster } from '@/store/fleet-roster'import { notify, notifyError } from '@/store/notifications'import {$activeGatewayProfile,@@ -83,7 +95,10 @@ import { DeleteProfileDialog } from '../../profiles/delete-profile-dialog'import { RenameProfileDialog } from '../../profiles/rename-profile-dialog'import { PROFILES_ROUTE, SETTINGS_ROUTE } from '../../routes'+import { ConnectionGlyph } from './connection-glyph'+import { buildRestGroups, countRestAgents, type FleetAgent, type FleetGroup, fleetRouteKey } from './fleet-rail'import { ProfileRemoteOverrideDialog } from './profile-remote-override-dialog'+import { useFleetRoster } from './use-fleet-roster'import { useProfilePrewarm } from './use-profile-prewarm'import { useProfileRailRefreshOnActive } from './use-profile-rail-refresh-on-active'@@ -119,9 +134,17 @@ const stepThroughCells: Modifier = ({ containerNodeRect, draggingNodeRect, trans// Arc-Spaces-style profile rail at the sidebar foot: a default↔all toggle pinned// left, the colored named profiles scrolling between, and Manage pinned right.-// The active profile pops in its own color — the "where am I" cue. Gateway-// identity lives in the statusbar, so this strip remains entirely available to-// profiles regardless of how many backends are registered.+// The active profile pops in its own color — the "where am I" cue.+//+// With one registered gateway this is the whole story. With several, the rail+// becomes the FLEET rail: the active gateway's profiles stay exactly as they+// are, and every other registered gateway follows on the same strip as an+// at-rest group — a hairline, that gateway's kind glyph, its default home+// square and its named squares, dimmed. Clicking an at-rest square performs+// the same re-home the statusbar switcher does, landing on that exact+// (gateway, profile); the workspace still lives on one gateway at a time, only+// the picker spans the fleet. Groups keep registry order regardless of which+// one is active, so a square never moves under the pointer that clicked it.export function ProfileRail() {const { t } = useI18n()const p = t.profiles@@ -132,17 +155,88 @@ export function ProfileRail() {const colors = useStore($profileColors)const remoteOverrides = useStore($profileRemoteOverrides)const multipleConnections = useStore($hasMultipleConnections)+ const registry = useStore($connectionsRegistry)+ const activeConnectionId = useStore($activeConnectionId)+ const roster = useStore($fleetRoster)const navigate = useNavigate()-const [createOpen, setCreateOpen] = useState(false)const [pendingRename, setPendingRename] = useState<null | ProfileInfo>(null)const [pendingDelete, setPendingDelete] = useState<null | ProfileInfo>(null)const [pendingSoul, setPendingSoul] = useState<null | string>(null)+ // Fleet-side counterparts: the at-rest square being acted on. Its route is+ // the dialog's scope, so the edit executes on the owning gateway.+ const [pendingRestRename, setPendingRestRename] = useState<null | FleetAgent>(null)+ const [pendingRestDelete, setPendingRestDelete] = useState<null | FleetAgent>(null)+ const [pendingRestSoul, setPendingRestSoul] = useState<null | FleetAgent>(null)+ // Route key of the at-rest square whose switch is dialing (spinner on that+ // square, not in the statusbar — the previous source stays painted).+ const [pendingRoute, setPendingRoute] = useState<null | string>(null)const scrollRef = useRef<HTMLDivElement>(null)+ useFleetRoster(multipleConnections)++ const connections = registry?.connections++ const restGroups = useMemo(+ () =>+ multipleConnections ? buildRestGroups({ activeConnectionId, connections: connections ?? [], roster }) : [],+ [activeConnectionId, connections, multipleConnections, roster]+ )++ // 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.+ const fleet = restGroups.length > 0++ // Registry order for the whole strip, active group included — the active+ // gateway keeps its slot instead of jumping to the front on a switch.+ const activeConnection = connections?.find(connection => connection.id === activeConnectionId) ?? null++ const fleetSequence = useMemo(() => {+ const byId = new Map(restGroups.map(group => [group.connectionId, group]))+ const ordered = sortConnectionsForDisplay(connections ?? [])+ const sequence: Array<{ kind: 'active' } | { group: FleetGroup; kind: 'rest' }> = []+ let activePlaced = false++ for (const connection of ordered) {+ if (connection.id === activeConnectionId) {+ sequence.push({ kind: 'active' })+ activePlaced = true+ } else {+ const group = byId.get(connection.id)++ if (group) {+ sequence.push({ group, kind: 'rest' })+ }+ }+ }++ // Legacy primary path publishes no connection id: the active gateway is+ // unknown to the registry, so it leads the strip.+ if (!activePlaced) {+ sequence.unshift({ kind: 'active' })+ }++ return sequence+ }, [activeConnectionId, connections, restGroups])+// Too many profiles for the square strip → collapse to the select. Declared// ahead of the wheel effect, which re-binds when the strip mounts/unmounts.- const condensed = profiles.length > PROFILE_DROPDOWN_THRESHOLD+ // The threshold counts the whole fleet: fourteen squares are fourteen+ // squares wherever they live.+ const condensed = profiles.length + countRestAgents(restGroups) > PROFILE_DROPDOWN_THRESHOLD++ const switchToRest = (agent: FleetAgent) => {+ const key = fleetRouteKey(agent.connectionId, agent.profile)+ triggerHaptic('selection')+ setPendingRoute(key)++ void selectConnection(agent.connectionId, { profile: agent.profile })+ .catch((error: unknown) => notifyError(error, p.switchConnectionFailed(agent.connectionLabel)))+ .finally(() => setPendingRoute(current => (current === key ? null : current)))+ }++ const restScope = (agent: FleetAgent): ProfileScope => ({ connectionId: agent.connectionId, profile: agent.profile })// A plain mouse wheel only emits deltaY; map it to horizontal scroll so the// rail is navigable without a trackpad. Trackpad x-scroll (deltaX) passes@@ -255,12 +349,62 @@ export function ProfileRail() {setCreateOpen(true)}, [createRequest])+ // The sortable strip of the active gateway's named profiles (unchanged+ // from the single-gateway rail; fleet mode only decides where it sits).+ const activeStrip = (+ <>+ {multiProfile && (+ <DndContext+ collisionDetection={closestCenter}+ modifiers={[stepThroughCells]}+ onDragEnd={handleDragEnd}+ onDragOver={handleDragOver}+ onDragStart={handleDragStart}+ sensors={sensors}+ >+ <SortableContext items={named.map(profile => profile.name)} strategy={horizontalListSortingStrategy}>+ {/* relative → the strip is the dragged square's offsetParent, so the+ clamp modifier bounds drags to the occupied cells (not the +). */}+ <div className="relative flex items-center gap-1">+ {named.map(profile => (+ <ProfileSquare+ active={!isAll && normalizeProfileKey(profile.name) === activeKey}+ color={resolveProfileColor(profile.name, colors)}+ key={profile.name}+ label={profileLabel(profile)}+ // The legacy per-profile remote override predates the+ // gateway registry; once the rail shows machines directly+ // it only confuses, so it is offered on single-gateway+ // setups only.+ onConnectRemote={multipleConnections ? undefined : () => openRemoteOverrideDialog(profile.name)}+ onDelete={() => setPendingDelete(profile)}+ onEditSoul={() => setPendingSoul(profile.name)}+ onRecolor={color => setProfileColor(profile.name, color)}+ onRename={() => setPendingRename(profile)}+ onSelect={() => selectProfile(profile.name)}+ remoteHost={remoteOverrides[normalizeProfileKey(profile.name)]?.host ?? null}+ />+ ))}+ </div>+ </SortableContext>+ </DndContext>+ )}+ </>+ )+return (<div aria-label={p.title} className="flex min-w-0 items-center gap-0.5" data-slot="profile-rail" role="group">+ {/* Fleet: every gateway carries its own home square inside its group, so+ the pinned pill is purely the "all profiles on this gateway" toggle. */}+ {fleet && (+ <ProfilePill active={isAll} glyph="layers" label={p.fleet.allOnGateway} onSelect={() => setShowAllProfiles(true)} />+ )}+{/* One button toggles default ↔ all: home face when scoped to a profile,layers face when showing everything. Pinned left like Manage is right.Hidden until a second profile exists. */}- {multiProfile &&+ {!fleet &&+ multiProfile &&(defaultProfile ? (// On default → toggle to all. Anywhere else (all view or a named// profile) → return to default. So leaving a profile never lands on all.@@ -275,7 +419,7 @@ export function ProfileRail() {))}{/* Single-profile: the active default's home icon next to the create +. */}- {!multiProfile && defaultProfile && (+ {!fleet && !multiProfile && defaultProfile && (<ProfilePillactiveglyph="home"@@ -295,7 +439,9 @@ export function ProfileRail() {onCreate={() => setCreateOpen(true)}onImport={() => void runImportProfileFlow()}onSelect={selectProfile}+ onSelectRest={switchToRest}profiles={named}+ restGroups={restGroups}/></div>) : (@@ -303,37 +449,55 @@ export function ProfileRail() {className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"ref={scrollRef}>- {multiProfile && (- <DndContext- collisionDetection={closestCenter}- modifiers={[stepThroughCells]}- onDragEnd={handleDragEnd}- onDragOver={handleDragOver}- onDragStart={handleDragStart}- sensors={sensors}- >- <SortableContext items={named.map(profile => profile.name)} strategy={horizontalListSortingStrategy}>- {/* relative → the strip is the dragged square's offsetParent, so the- clamp modifier bounds drags to the occupied cells (not the +). */}- <div className="relative flex items-center gap-1">- {named.map(profile => (- <ProfileSquare- active={!isAll && normalizeProfileKey(profile.name) === activeKey}- color={resolveProfileColor(profile.name, colors)}- key={profile.name}- label={profileLabel(profile)}- onConnectRemote={() => openRemoteOverrideDialog(profile.name)}- onDelete={() => setPendingDelete(profile)}- onEditSoul={() => setPendingSoul(profile.name)}- onRecolor={color => setProfileColor(profile.name, color)}- onRename={() => setPendingRename(profile)}- onSelect={() => selectProfile(profile.name)}- remoteHost={remoteOverrides[normalizeProfileKey(profile.name)]?.host ?? null}- />- ))}- </div>- </SortableContext>- </DndContext>+ {/* The active gateway's squares. In fleet mode they sit in the+ gateway's registry slot with a home square at their head, so the+ strip keeps one shape whichever gateway is active. */}+ {fleet ? (+ fleetSequence.map((entry, index) =>+ entry.kind === 'active' ? (+ <Fragment key="active">+ <FleetDivider+ connection={activeConnection}+ first={index === 0}+ label={activeConnection ? p.fleet.gateway(activeConnection.label) : null}+ reachable+ />+ <span+ aria-label={activeConnection ? p.fleet.gateway(activeConnection.label) : undefined}+ className="flex shrink-0 items-center gap-1"+ data-active="true"+ data-connection-id={activeConnection?.id}+ data-slot="profile-rail-gateway"+ role="group"+ >+ {defaultProfile && (+ <ProfilePill+ active={onDefault}+ glyph="home"+ label={profileLabel(defaultProfile)}+ onSelect={() => selectProfile(defaultProfile.name)}+ />+ )}+ {activeStrip}+ </span>+ </Fragment>+ ) : (+ <FleetRestGroup+ colors={colors}+ first={index === 0}+ group={entry.group}+ key={entry.group.connectionId}+ onDelete={setPendingRestDelete}+ onEditSoul={setPendingRestSoul}+ onRecolor={(agent, color) => setProfileColor(agent.profile, color)}+ onRename={setPendingRestRename}+ onSelect={switchToRest}+ pendingRoute={pendingRoute}+ />+ )+ )+ ) : (+ activeStrip)}<AddProfileButton label={p.newProfile} onClick={() => setCreateOpen(true)} />@@ -388,6 +552,32 @@ export function ProfileRail() {<EditSoulDialog onClose={() => setPendingSoul(null)} profileName={pendingSoul} />+ {/* Fleet-side dialogs: scoped to the at-rest square's owning gateway, and+ they refresh the roster (not the active profile list) on success. */}+ <RenameProfileDialog+ currentName={pendingRestRename?.profile ?? ''}+ onClose={() => setPendingRestRename(null)}+ onRenamed={() => refreshFleetRoster({ force: true })}+ open={pendingRestRename !== null}+ scope={pendingRestRename ? restScope(pendingRestRename) : undefined}+ />++ <DeleteProfileDialog+ gatewayLabel={pendingRestDelete?.connectionLabel}+ onClose={() => setPendingRestDelete(null)}+ onDeleted={() => refreshFleetRoster({ force: true })}+ open={pendingRestDelete !== null}+ profile={pendingRestDelete ? { name: pendingRestDelete.profile, path: pendingRestDelete.handle } : null}+ scope={pendingRestDelete ? restScope(pendingRestDelete) : undefined}+ />++ <EditSoulDialog+ gatewayLabel={pendingRestSoul?.connectionLabel}+ onClose={() => setPendingRestSoul(null)}+ profileName={pendingRestSoul?.profile ?? null}+ scope={pendingRestSoul ? restScope(pendingRestSoul) : undefined}+ />+<ProfileRemoteOverrideDialog profileNames={profileNames} /></div>)@@ -396,7 +586,17 @@ export function ProfileRail() {// Right-click → Edit SOUL.md for a sidebar profile — the same in-app markdown// editor as the memory-graph node edit, so a profile's persona is editable// without opening the Manage overlay.-function EditSoulDialog({ onClose, profileName }: { onClose: () => void; profileName: null | string }) {+function EditSoulDialog({+ gatewayLabel,+ onClose,+ profileName,+ scope+}: {+ gatewayLabel?: string+ onClose: () => void+ profileName: null | string+ scope?: ProfileScope+}) {const { t } = useI18n()const p = t.profilesconst [content, setContent] = useState('')@@ -412,13 +612,13 @@ function EditSoulDialog({ onClose, profileName }: { onClose: () => void; profilesetLoading(true)setContent('')- getProfileSoul(profileName)+ getProfileSoul(profileName, scope).then(soul => !cancelled && setContent(soul.content)).catch(err => !cancelled && notifyError(err, p.failedLoadSoul)).finally(() => !cancelled && setLoading(false))return () => void (cancelled = true)- }, [p, profileName])+ }, [p, profileName, scope])const save = async () => {if (!profileName) {@@ -428,7 +628,7 @@ function EditSoulDialog({ onClose, profileName }: { onClose: () => void; profilesetSaving(true)try {- await updateProfileSoul(profileName, content)+ await updateProfileSoul(profileName, content, scope)notify({ kind: 'success', title: p.soulSaved, message: profileName })onClose()} catch (err) {@@ -442,7 +642,9 @@ function EditSoulDialog({ onClose, profileName }: { onClose: () => void; profile<Dialog onOpenChange={open => !open && !saving && onClose()} open={profileName !== null}><DialogContent className="max-w-2xl"><DialogHeader>- <DialogTitle>{profileName} · SOUL.md</DialogTitle>+ <DialogTitle>+ {gatewayLabel && profileName ? p.fleet.onGateway(profileName, gatewayLabel) : profileName} · SOUL.md+ </DialogTitle></DialogHeader><div className="h-80">{!loading && profileName && (@@ -513,14 +715,19 @@ function ProfileDropdown({onCreate,onImport,onSelect,- profiles+ onSelectRest,+ profiles,+ restGroups}: {activeKey: null | stringcolors: Record<string, string>onCreate: () => voidonImport: () => voidonSelect: (name: string) => void+ onSelectRest: (agent: FleetAgent) => voidprofiles: ProfileInfo[]+ // Fleet: the other gateways' agents, each under its own section header.+ restGroups: readonly FleetGroup[]}) {const { t } = useI18n()const p = t.profiles@@ -577,6 +784,34 @@ function ProfileDropdown({/>))}</DropdownMenuRadioGroup>+ {restGroups.map(group => (+ <div data-connection-id={group.connectionId} data-slot="profile-dropdown-gateway" key={group.connectionId}>+ <DropdownMenuSeparator />+ <DropdownMenuLabel className={cn(dropdownMenuSectionLabel, 'flex items-center gap-1.5')}>+ <ConnectionGlyph connection={group} />+ <span className="truncate">{group.label}</span>+ {!group.reachable && <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-amber-500" />}+ </DropdownMenuLabel>+ {[group.defaultAgent, ...group.named].map(agent => (+ <DropdownMenuItem+ aria-label={p.fleet.onGateway(agent.profile, group.label)}+ className="min-w-0"+ key={agent.profile}+ onSelect={() => onSelectRest(agent)}+ >+ <span className="flex min-w-0 items-center gap-1.5">+ <ProfileGlyph+ aria-hidden="true"+ color={resolveProfileColor(agent.profile, colors)}+ isDefault={agent.isDefault}+ name={agent.profile}+ />+ <span className="truncate">{agent.profile}</span>+ </span>+ </DropdownMenuItem>+ ))}+ </div>+ ))}</DropdownMenuContent></DropdownMenu>)@@ -608,29 +843,270 @@ interface ProfilePillProps {glyph: stringlabel: stringonSelect: () => void+ // Fleet at-rest: dimmed until hovered, like the at-rest squares beside it.+ muted?: boolean+ pending?: boolean+ slot?: string+ connectionId?: string}-function ProfilePill({ active, glyph, label, onSelect }: ProfilePillProps) {+function ProfilePill({ active, connectionId, glyph, label, muted = false, onSelect, pending = false, slot }: ProfilePillProps) {return (<Tip label={label}><Button+ aria-busy={pending || undefined}aria-label={label}aria-pressed={active}className={cn('bg-transparent text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground',- active && 'bg-(--ui-control-active-background) text-foreground'+ active && 'bg-(--ui-control-active-background) text-foreground',+ muted && 'opacity-40 hover:opacity-100')}+ data-connection-id={connectionId}+ data-slot={slot}onClick={onSelect}size="icon-xs"type="button"variant="ghost">- <Codicon name={glyph} size="0.875rem" />+ {pending ? (+ <Loader2 aria-hidden="true" className="size-3 animate-spin" />+ ) : (+ <Codicon name={glyph} size="0.875rem" />+ )}</Button></Tip>)}+// The gateway marker that heads every group on the fleet rail: its kind glyph+// (device / network / terminal / cloud — the same glyph the statusbar readout+// uses), an amber dot when the roster last found it unreachable, and a hairline+// separating it from the previous group. The first group gets no hairline.+function FleetDivider({+ connection,+ first,+ label,+ reachable+}: {+ connection: null | Pick<FleetGroup, 'connectionId' | 'kind'> | Pick<DesktopRegistryConnection, 'id' | 'kind'>+ first: boolean+ label: null | string+ reachable: boolean+}) {+ if (!connection) {+ return null+ }++ const connectionId = 'connectionId' in connection ? connection.connectionId : connection.id++ const marker = (+ <span+ aria-hidden="true"+ className={cn('flex h-5 shrink-0 items-center gap-0.5', first ? 'mr-0.5' : 'mx-0.5')}+ data-connection-id={connectionId}+ data-reachable={reachable}+ data-slot="profile-rail-divider"+ >+ {!first && <span className="h-3 w-px bg-(--ui-stroke-tertiary)" />}+ <ConnectionGlyph connection={connection} />+ {!reachable && <span className="size-1.5 rounded-full bg-amber-500" data-slot="profile-rail-unreachable" />}+ </span>+ )++ return label ? <Tip label={label}>{marker}</Tip> : marker+}++// One at-rest gateway on the fleet rail: hairline + kind glyph (amber dot when+// the roster last found it unreachable — never hidden, a sleeping box is still+// yours), then its home square and named squares, dimmed. Clicking any of+// them re-homes onto that exact (gateway, profile).+function FleetRestGroup({+ colors,+ first,+ group,+ onDelete,+ onEditSoul,+ onRecolor,+ onRename,+ onSelect,+ pendingRoute+}: {+ colors: Record<string, string>+ first: boolean+ group: FleetGroup+ onDelete: (agent: FleetAgent) => void+ onEditSoul: (agent: FleetAgent) => void+ onRecolor: (agent: FleetAgent, color: null | string) => void+ onRename: (agent: FleetAgent) => void+ onSelect: (agent: FleetAgent) => void+ pendingRoute: null | string+}) {+ const { t } = useI18n()+ const p = t.profiles+ const dividerLabel = group.reachable ? p.fleet.gateway(group.label) : p.fleet.gatewayUnreachable(group.label)+ const defaultKey = fleetRouteKey(group.connectionId, group.defaultAgent.profile)++ return (+ <>+ <FleetDivider connection={group} first={first} label={dividerLabel} reachable={group.reachable} />+ <span+ aria-label={p.fleet.gateway(group.label)}+ className="flex shrink-0 items-center gap-1"+ data-active="false"+ data-connection-id={group.connectionId}+ data-reachable={group.reachable}+ data-slot="profile-rail-gateway"+ role="group"+ >+ <ProfilePill+ active={false}+ connectionId={group.connectionId}+ glyph="home"+ label={p.fleet.onGateway(group.defaultAgent.profile, group.label)}+ muted+ onSelect={() => onSelect(group.defaultAgent)}+ pending={pendingRoute === defaultKey}+ slot="profile-rail-rest-home"+ />+ {group.named.map(agent => (+ <RestSquare+ agent={agent}+ color={resolveProfileColor(agent.profile, colors)}+ key={agent.profile}+ onDelete={() => onDelete(agent)}+ onEditSoul={() => onEditSoul(agent)}+ onRecolor={color => onRecolor(agent, color)}+ onRename={() => onRename(agent)}+ onSelect={() => onSelect(agent)}+ pending={pendingRoute === fleetRouteKey(agent.connectionId, agent.profile)}+ />+ ))}+ </span>+ </>+ )+}++// An at-rest square: the same tile as ProfileSquare, minus drag-reorder and+// hold-to-recolor (the strip it lives in is not sortable across machines).+// Tooltip and accessible name carry the gateway so two same-named profiles on+// different machines never read alike; the right-click actions run against+// the square's owning gateway.+function RestSquare({+ agent,+ color,+ onDelete,+ onEditSoul,+ onRecolor,+ onRename,+ onSelect,+ pending+}: {+ agent: FleetAgent+ color: null | string+ onDelete: () => void+ onEditSoul: () => void+ onRecolor: (color: null | string) => void+ onRename: () => void+ onSelect: () => void+ pending: boolean+}) {+ const { t } = useI18n()+ const p = t.profiles+ const hue = color ?? 'var(--ui-text-quaternary)'+ const [pickerOpen, setPickerOpen] = useState(false)+ const label = p.fleet.onGateway(agent.profile, agent.connectionLabel)++ const pickColor = (next: null | string) => {+ onRecolor(next)+ setPickerOpen(false)+ triggerHaptic('selection')+ }++ return (+ <Popover onOpenChange={setPickerOpen} open={pickerOpen}>+ <ContextMenu>+ <TooltipProvider delayDuration={0}>+ <Tooltip>+ <PopoverAnchor asChild>+ <ContextMenuTrigger asChild>+ <TooltipTrigger asChild>+ <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"+ data-connection-id={agent.connectionId}+ data-profile={agent.profile}+ data-slot="profile-rail-rest-square"+ onClick={onSelect}+ style={{ backgroundColor: profileColorSoft(hue, 22), color: color ?? undefined }}+ type="button"+ >+ {pending ? (+ <Loader2 aria-hidden="true" className="size-3 animate-spin" />+ ) : (+ agent.profile.replace(/[^a-z0-9]/gi, '').charAt(0) || '?'+ )}+ </button>+ </TooltipTrigger>+ </ContextMenuTrigger>+ </PopoverAnchor>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ </TooltipProvider>++ <ContextMenuContent+ aria-label={p.actions}+ className="w-44"+ collisionPadding={{ bottom: 44, left: 8, right: 8, top: 8 }}+ onCloseAutoFocus={event => event.preventDefault()}+ >+ <ContextMenuItem onSelect={onSelect}>+ <Codicon name="arrow-right" size="0.875rem" />+ <span className="truncate">{p.fleet.switchTo(agent.profile, agent.connectionLabel)}</span>+ </ContextMenuItem>+ <ContextMenuItem onSelect={() => setPickerOpen(true)}>+ <Codicon name="symbol-color" size="0.875rem" />+ <span>{p.color}</span>+ </ContextMenuItem>+ <ContextMenuItem onSelect={onRename}>+ <Codicon name="text-size" size="0.875rem" />+ <span>{p.renameMenu}</span>+ </ContextMenuItem>+ <ContextMenuItem onSelect={onEditSoul}>+ <Codicon name="edit" size="0.875rem" />+ <span>{p.editSoul}</span>+ </ContextMenuItem>+ <ContextMenuItem+ className="text-destructive focus:text-destructive"+ onSelect={onDelete}+ variant="destructive"+ >+ <Codicon name="trash" size="0.875rem" />+ <span>{t.common.delete}</span>+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>++ <PopoverContent+ aria-label={p.colorFor}+ className="w-auto p-2"+ collisionPadding={{ bottom: 44, left: 8, right: 8, top: 8 }}+ side="top"+ >+ <ColorSwatches+ clearIcon="sync"+ clearLabel={p.autoColor}+ onChange={pickColor}+ swatches={PROFILE_SWATCHES}+ swatchLabel={p.setColor}+ value={color}+ />+ </PopoverContent>+ </Popover>+ )+}+interface ProfileSquareProps {active: booleancolor: null | string@@ -639,7 +1115,9 @@ interface ProfileSquareProps {onRecolor: (color: null | string) => voidonRename: () => voidonEditSoul: () => void- onConnectRemote: () => void+ // Absent on multi-gateway setups: the legacy per-profile remote override+ // is superseded by the fleet rail there.+ onConnectRemote?: () => voidonDelete: () => void// hostname[:port] of this profile's remote override, or null when the// profile runs locally. Drives the "remote" badge on the square.@@ -822,10 +1300,12 @@ function ProfileSquare({<Codicon name="package" size="0.875rem" /><span>{p.exportProfile}</span></ContextMenuItem>- <ContextMenuItem onSelect={onConnectRemote}>- <Codicon name="globe" size="0.875rem" />- <span>{remoteHost ? p.remoteOverride.badge(remoteHost) : p.remoteOverride.menuItem}</span>- </ContextMenuItem>+ {onConnectRemote && (+ <ContextMenuItem onSelect={onConnectRemote}>+ <Codicon name="globe" size="0.875rem" />+ <span>{remoteHost ? p.remoteOverride.badge(remoteHost) : p.remoteOverride.menuItem}</span>+ </ContextMenuItem>+ )}<ContextMenuItemclassName="text-destructive focus:text-destructive"onSelect={onDelete}diff --git a/apps/desktop/src/app/chat/sidebar/use-fleet-roster.ts b/apps/desktop/src/app/chat/sidebar/use-fleet-roster.tsnew file mode 100644index 00000000000..018c7cac981--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/use-fleet-roster.ts@@ -0,0 +1,38 @@+import { useEffect } from 'react'++import { refreshFleetRoster } from '@/store/fleet-roster'++/**+ * Keep the fleet roster fresh for the profile rail while more than one+ * gateway is registered: pull on mount, when the window regains focus or+ * visibility, and immediately when the connection registry changes. No timer+ * — the multi-connection contract rules out periodic fleet polling from the+ * sidebar, and a 60s stale window in the store absorbs focus churn.+ */+export function useFleetRoster(enabled: boolean): void {+ useEffect(() => {+ if (!enabled) {+ return+ }++ void refreshFleetRoster()++ const onFocus = () => void refreshFleetRoster()++ const onVisibility = () => {+ if (document.visibilityState === 'visible') {+ void refreshFleetRoster()+ }+ }++ window.addEventListener('focus', onFocus)+ document.addEventListener('visibilitychange', onVisibility)+ const offRegistry = window.hermesDesktop?.connections?.onChanged?.(() => void refreshFleetRoster({ force: true }))++ return () => {+ window.removeEventListener('focus', onFocus)+ document.removeEventListener('visibilitychange', onVisibility)+ offRegistry?.()+ }+ }, [enabled])+}diff --git a/apps/desktop/src/app/profiles/delete-profile-dialog.tsx b/apps/desktop/src/app/profiles/delete-profile-dialog.tsxindex 6f02d630b5a..dd6f43640df 100644--- a/apps/desktop/src/app/profiles/delete-profile-dialog.tsx+++ b/apps/desktop/src/app/profiles/delete-profile-dialog.tsx@@ -1,3 +1,4 @@+import type { ProfileScope } from '@/api/client'import { ConfirmDialog } from '@/components/ui/confirm-dialog'import { deleteProfile } from '@/hermes'import { useI18n } from '@/i18n'@@ -8,15 +9,23 @@ import { $activeGatewayProfile, normalizeProfileKey, selectProfile, setActivePro// Enter-to-confirm + busy/done/error from the shared dialog. The single choke// point for every delete entry point (rail + Profiles view).export function DeleteProfileDialog({+ gatewayLabel,profile,onClose,onDeleted,- open+ open,+ scope}: {+ /** Names the owning machine in the copy when the profile lives on a gateway+ * other than the foreground one — two "omer"s must never read the same. */+ gatewayLabel?: stringprofile: { name: string; path: string } | nullonClose: () => voidonDeleted?: () => Promise<void> | voidopen: boolean+ /** Explicit (connection, profile) owner for a remote-gateway profile. The+ * delete then executes on THAT gateway and never touches local backends. */+ scope?: ProfileScope}) {const { t } = useI18n()const p = t.profiles@@ -30,6 +39,7 @@ export function DeleteProfileDialog({<>{p.deleteDescPrefix}<span className="font-medium text-foreground">{profile.name}</span>+ {gatewayLabel ? p.fleet.deleteOn(gatewayLabel) : null}{p.deleteDescMid}<span className="font-mono text-xs">{profile.path}</span>{p.deleteDescSuffix}@@ -48,9 +58,17 @@ export function DeleteProfileDialog({// backend. Capture that before the delete; reset *after* the host's// onDeleted refresh so our reset is the last write — a refreshActiveProfile// racing the (still-dying) backend can't clobber the pill back to it.- const wasActive = normalizeProfileKey(profile.name) === normalizeProfileKey($activeGatewayProfile.get())- retireLocalProfileGateways(profile.name)- await deleteProfile(profile.name)+ const remote = scope !== undefined && scope !== null++ const wasActive =+ !remote && normalizeProfileKey(profile.name) === normalizeProfileKey($activeGatewayProfile.get())++ if (!remote) {+ retireLocalProfileGateways(profile.name)+ }++ // Legacy arity when unscoped: callers and tests pin the one-arg call.+ await (remote ? deleteProfile(profile.name, scope) : deleteProfile(profile.name))await onDeleted?.()if (wasActive) {diff --git a/apps/desktop/src/app/profiles/rename-profile-dialog.tsx b/apps/desktop/src/app/profiles/rename-profile-dialog.tsxindex 9cb72359f14..94e035750f4 100644--- a/apps/desktop/src/app/profiles/rename-profile-dialog.tsx+++ b/apps/desktop/src/app/profiles/rename-profile-dialog.tsx@@ -1,5 +1,6 @@import { useEffect, useState } from 'react'+import type { ProfileScope } from '@/api/client'import { ActionStatus } from '@/components/ui/action-status'import { Button } from '@/components/ui/button'import {@@ -30,7 +31,8 @@ export function RenameProfileDialog({isDefault = false,onClose,onRenamed,- open+ open,+ scope}: {currentName: string/** Default profile: sets a presentation-only display name (Unicode ok);@@ -39,6 +41,9 @@ export function RenameProfileDialog({onClose: () => voidonRenamed?: (name: string) => Promise<void> | voidopen: boolean+ /** Explicit (connection, profile) owner for a remote-gateway profile: the+ * rename executes there and no local backend is retired. */+ scope?: ProfileScope}) {const { t } = useI18n()const p = t.profiles@@ -85,11 +90,11 @@ export function RenameProfileDialog({// backend teardown as a transient drop and redial, resurrecting the// old-name backend whose ensure_hermes_home() recreates the directory// the rename just moved (same class as the delete path, #88638).- if (!isDefault) {+ if (!isDefault && scope == null) {retireLocalProfileGateways(currentName)}- await renameProfile(currentName, trimmed)+ await (scope == null ? renameProfile(currentName, trimmed) : renameProfile(currentName, trimmed, scope))await onRenamed?.(trimmed)setStatus('done')window.setTimeout(onClose, 800)diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0d2c9a335bf..198d66a2c0b 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1825,6 +1825,14 @@ export const en: Translations = {switchConnectionFailed: name => `Could not connect to ${name}`,manageProfiles: 'Manage profiles…',connectGateway: 'Manage gateways…',+ fleet: {+ allOnGateway: 'All profiles on this gateway',+ gateway: gateway => `Profiles on ${gateway}`,+ gatewayUnreachable: gateway => `${gateway} · unreachable`,+ onGateway: (name, gateway) => `${name} · ${gateway}`,+ switchTo: (name, gateway) => `Switch to ${name} on ${gateway}`,+ deleteOn: gateway => ` on ${gateway}`+ },remoteOverride: {menuItem: 'Connect to a remote host…',badge: (host: string) => `Runs on ${host}`,diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 5df1bf0f00e..47ab2df7f8c 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1542,6 +1542,14 @@ export interface Translations {switchConnectionFailed: (name: string) => stringmanageProfiles: stringconnectGateway: string+ fleet: {+ allOnGateway: string+ gateway: (gateway: string) => string+ gatewayUnreachable: (gateway: string) => string+ onGateway: (name: string, gateway: string) => string+ switchTo: (name: string, gateway: string) => string+ deleteOn: (gateway: string) => string+ }remoteOverride: {menuItem: stringbadge: (host: string) => stringdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 2bc19f44a2d..edd6f9b2b98 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2010,6 +2010,14 @@ export const zh: Translations = {switchConnectionFailed: name => `无法连接到 ${name}`,manageProfiles: '管理配置档案…',connectGateway: '管理网关…',+ fleet: {+ allOnGateway: '此网关上的全部配置档案',+ gateway: gateway => `${gateway} 上的配置档案`,+ gatewayUnreachable: gateway => `${gateway} · 无法连接`,+ onGateway: (name, gateway) => `${name} · ${gateway}`,+ switchTo: (name, gateway) => `切换到 ${gateway} 上的 ${name}`,+ deleteOn: gateway => `(位于 ${gateway})`+ },remoteOverride: {menuItem: '连接到远程主机…',badge: (host: string) => `运行于 ${host}`,diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.tsindex b0ef4622220..edd9764dd8d 100644--- a/apps/desktop/src/store/connections.test.ts+++ b/apps/desktop/src/store/connections.test.ts@@ -185,6 +185,24 @@ describe('connection registry cache', () => {expect(setLastUsed).toHaveBeenCalledWith('homelab')})+ it('boot restore yields to a source the user already picked while boot was settling', async () => {+ // Primary is local, launch mode is primary. The user clicks a fleet-rail+ // square on the homelab gateway before the boot-time restore runs. The+ // restore must not "return" the window to the primary over that choice.+ list.mockResolvedValue({ ...registry, primary: 'local', launchMode: 'primary' })+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })++ await selectConnection('homelab', { profile: 'omer' })+ expect($activeConnectionId.get()).toBe('homelab')+ ensureGatewayAgent.mockClear()++ await initializeConnectionsRegistry()++ expect(ensureGatewayAgent).not.toHaveBeenCalled()+ expect($activeConnectionId.get()).toBe('homelab')+ })+it('uses only the resolved descriptor identity for the active gateway', () => {setConnectionsRegistry({ ...registry, primary: 'homelab' })$connection.set({ connectionId: 'work-vps', mode: 'remote' })@@ -269,6 +287,22 @@ describe('selectConnection', () => {expect($gatewaySwitching.get()).toBe(false)})+ it('lands on an explicit profile instead of the one last used on that source', async () => {+ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })++ // Remember "scout" on homelab by activating it once…+ await selectConnection('homelab', { profile: 'scout' })+ expect(ensureGatewayAgent).toHaveBeenLastCalledWith('homelab', 'scout', expect.anything())++ // …then pick a different square on the same source: the click wins over+ // whatever was last used there, and the fresh draft targets that profile.+ await selectConnection('local')+ await selectConnection('homelab', { profile: 'omer' })+ expect(ensureGatewayAgent).toHaveBeenLastCalledWith('homelab', 'omer', expect.anything())+ expect($newChatProfile.get()).toBe('omer')+ })+it('restores the last profile used on each source', async () => {setConnectionsRegistry(registry)$connection.set({ connectionId: 'local', mode: 'local', profile: 'research', registryScoped: true })diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsindex 30ad08546e7..7951e3bbe2c 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -198,6 +198,14 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnectionrestoreAttempted = trueawait waitForInitialConnection()+ // The user got there first: a source they picked while boot was settling+ // (statusbar switcher, fleet profile rail) is not drift to "restore" over.+ // The launch preference only decides where a window lands when nobody has+ // said otherwise yet.+ if (switchRevision > 0 || pendingTarget !== null) {+ return registry+ }+// Residual drift: a window can be live on a source the registry cannot name// (a v1-configured remote that reconciliation has not repaired yet, e.g. a// read-only userData that rejected the healed write). $activeConnectionId is@@ -252,7 +260,13 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnection* switch. Every await is bounded; a commit that stalls after the wipe lowers* the barrier and repaints the source that is still active.*/-export async function selectConnection(connectionId: string): Promise<void> {+export interface SelectConnectionOptions {+ /** Land on this profile of the target source instead of the one last used+ * there. The fleet profile rail passes the exact square the user clicked. */+ profile?: null | string+}++export async function selectConnection(connectionId: string, options: SelectConnectionOptions = {}): Promise<void> {const registry = $connectionsRegistry.get()const targetConnection = registry?.connections.find(connection => connection.id === connectionId)@@ -268,7 +282,12 @@ export async function selectConnection(connectionId: string): Promise<void> {const currentConnectionId = $activeConnectionId.get()const currentProfile = normalizeProfileKey($activeGatewayProfile.get())- const targetProfile = normalizeProfileKey($lastProfileByConnection.get()[connectionId] ?? 'default')+ const explicitProfile = String(options.profile ?? '').trim()++ const targetProfile = normalizeProfileKey(+ explicitProfile || ($lastProfileByConnection.get()[connectionId] ?? 'default')+ )+const targetKey = `${connectionId}::${targetProfile}`const targetIsActive = () => {diff --git a/apps/desktop/src/store/fleet-roster.ts b/apps/desktop/src/store/fleet-roster.tsnew file mode 100644index 00000000000..9669fdfd0b4--- /dev/null+++ b/apps/desktop/src/store/fleet-roster.ts@@ -0,0 +1,55 @@+import { atom } from 'nanostores'++import type { DesktopAgentRoster } from '@/global'++// The union agent roster — every profile on every registered gateway — as+// Electron enumerates it over REST/SSH (`hermes:agents:roster`). Bot Mode and+// the Capabilities scope selector already read it; the Sessions profile rail+// is its third consumer. Fetched on demand only (mount / focus / registry+// change), never on a timer: the multi-connection docs rule out periodic+// fleet polling from the sidebar.+export const $fleetRoster = atom<DesktopAgentRoster | null>(null)++const FLEET_ROSTER_STALE_MS = 60_000++let fetchedAt = 0+let inflight: null | Promise<void> = null++export async function refreshFleetRoster(options: { force?: boolean } = {}): Promise<void> {+ const bridge = window.hermesDesktop?.getAgentRoster++ if (!bridge) {+ return+ }++ if (!options.force && $fleetRoster.get() && Date.now() - fetchedAt < FLEET_ROSTER_STALE_MS) {+ return+ }++ if (inflight) {+ return inflight+ }++ inflight = bridge()+ .then(roster => {+ $fleetRoster.set(roster)+ fetchedAt = Date.now()+ })+ .catch((error: unknown) => {+ // A failed enumeration keeps the last roster: the rail should not lose+ // a machine's squares because one refresh hit a sleeping box.+ console.warn('[fleet-roster] enumeration failed; keeping the previous roster', error)+ })+ .finally(() => {+ inflight = null+ })++ return inflight+}++/** @internal */+export function _resetFleetRosterForTests(): void {+ $fleetRoster.set(null)+ fetchedAt = 0+ inflight = null+}diff --git a/website/docs/user-guide/multi-connection-desktop.md b/website/docs/user-guide/multi-connection-desktop.mdindex 06262129799..13ce2e88b61 100644--- a/website/docs/user-guide/multi-connection-desktop.md+++ b/website/docs/user-guide/multi-connection-desktop.md@@ -170,10 +170,31 @@ that live on one gateway.avatars remain a separate control after the divider. The same selector scalesfrom two gateways to a larger fleet without turning backends into profile-likeglyphs or crowding profile actions out of the rail.-- Selecting a gateway restores the last profile used there. The profile rail- then shows only that gateway's profiles; the home pill returns to its default- profile and the layers pill shows **All profiles on this gateway**.- **Cmd/Ctrl+1–9** continue to switch profiles within the active gateway.+- Selecting a gateway restores the last profile used there. The home pill+ returns to its default profile and the layers pill shows **All profiles on+ this gateway**. **Cmd/Ctrl+1–9** continue to switch profiles within the+ active gateway.+- With several gateways the profile rail is a **fleet rail**: every registered+ gateway's profiles sit on the one strip, each group headed by that gateway's+ kind glyph (device, network, terminal, cloud) — the same glyph the gateway+ selector uses. The active gateway's squares look exactly as they do on a+ single-gateway Desktop; the other gateways' squares are dimmed ("at rest").+ Hovering an at-rest square names its machine (`omer · This device`), so two+ same-named profiles on different machines never read alike.+- Clicking an at-rest square performs the same switch as the gateway selector,+ landing on that exact `(gateway, profile)`: the square spins while the+ target is dialed, the previous gateway stays painted until the target+ answers, and a dead target fails the click with a message rather than+ leaving the window half-switched. Groups keep registry order whichever+ gateway is active, so a square never moves under the pointer that clicked+ it. Right-click on an at-rest square offers **Switch to**, **Color**,+ **Rename**, **Edit SOUL.md** and **Delete**, all executed on the square's+ own gateway; the delete confirmation names the machine.+- A gateway the last enumeration could not reach keeps its squares, marked+ with an amber dot on its glyph — a sleeping box is still yours. Two+ registrations of one backend collapse to a single group. Past thirteen+ squares across the fleet, the strip condenses into one menu sectioned by+ gateway.- The selected gateway survives a quit and relaunch only when **Settings →Gateways → At startup, return to Sessions on the last-used gateway** is on.The preference and gateway id live in the app's user-data registry, so@@ -211,10 +232,11 @@ home, not a second add flow.Sessions intentionally show one active gateway at a time: this keeps files,tools, channels, cron, and session history in one understandable execution-context. Bot Mode serves a different job and may present the union roster,-grouped by gateway, so a user can open one agent on a NAS and another on a VPS-from one surface. Opening a bot still activates its exact `(gateway, profile)`-route.+context. The fleet profile rail widens only the *picker* — the workspace still+lives on exactly one `(gateway, profile)` after every click. Bot Mode serves a+different job and may present the union roster, grouped by gateway, so a user+can open one agent on a NAS and another on a VPS from one surface. Opening a+bot still activates its exact `(gateway, profile)` route.Direct bot mentions and delegation remain gateway-local by default. Crossing abackend boundary changes filesystem, credentials, tools, and trust context, so