Skip to content

The agent that grows with you

28.1 KB
Raw Blame
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()
const openWindow = vi.fn()

vi.mock('react-router', () => ({
  useNavigate: () => navigate
}))

vi.mock('@/i18n', () => ({
  useI18n: () => ({
    t: {
      common: { cancel: 'Cancel', confirm: 'Confirm', delete: 'Delete', done: 'Done', loading: 'Loading' },
      errors: { genericFailure: 'Something went wrong' },
      profiles: {
        actions: 'Actions',
        allProfiles: 'All profiles',
        autoColor: 'Auto',
        color: 'Color…',
        colorFor: 'Color',
        connectGateway: 'Manage gateways…',
        editSoul: 'Edit SOUL.md…',
        openInNewWindow: 'Open in new window',
        setAsDefault: 'Set as default',
        exportProfile: 'Export profile…',
        failedLoadSoul: 'Failed to load SOUL.md',
        failedSaveSoul: 'Failed to save SOUL.md',
        fleet: {
          allOnGateway: 'All profiles on this gateway',
          connectExistingInstead: 'Connect to existing instead',
          deleteOn: (gateway: string) => ` on ${gateway}`,
          gateway: (gateway: string) => `Profiles on ${gateway}`,
          gatewayUnreachable: (gateway: string) => `${gateway} · unreachable`,
          installDeviceConfirm: 'Install locally',
          installDeviceDesc:
            'This will install Hermes locally, then open a fresh session on this computer. Nothing is installed until you confirm.',
          installDeviceTitle: 'Install Hermes on This device?',
          localDevice: 'This device (local backend — installs Hermes if missing, otherwise opens a fresh session)',
          onGateway: (name: string, gateway: string) => `${name} · ${gateway}`,
          switchTo: (name: string, gateway: string) => `Open ${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' } }
    }
  })
}))

const { sortByProfileOrder } = await import('@/lib/profile-order')

vi.mock('@/store/profile', () => ({
  $activeGatewayProfile: atom('default'),
  $profileColors: atom({}),
  $profileCreateRequest: atom(0),
  $profileOrder: atom([]),
  $profiles: atom([{ is_default: true, name: 'default' }]),
  $profileScope: atom('default'),
  // The rail's status summary (profile-dot-state) rides the real session
  // stores, whose import graph reaches $showAllProfiles through layout state.
  $showAllProfiles: atom(false),
  ALL_PROFILES: '*',
  normalizeProfileKey: (name: string) => name,
  prewarmProfilePick: vi.fn(),
  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: Array<{ name: string }>, order: string[]) =>
    sortByProfileOrder(profiles, order, profile => profile.name)
}))

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(), notePointerMove: vi.fn(), startPrewarm: vi.fn() })
}))

vi.mock('./use-profile-rail-refresh-on-active', () => ({
  useProfileRailRefreshOnActive: () => undefined
}))

vi.mock('@/components/remote-setup/first-run', () => ({
  FirstRunRemoteSetup: () => 'Connect to existing Hermes'
}))

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 { $activeGatewayProfile, $profileOrder, $profiles, $profileScope } = await import('@/store/profile')
const activeGatewayProfile = $activeGatewayProfile as ReturnType<typeof atom<string>>
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: '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: 'gateway-a',
  primary: 'gateway-a',
  version: 2
} as DesktopConnectionsRegistry

const roster: DesktopAgentRoster = {
  agents: [
    {
      connectionId: 'gateway-a',
      connectionKind: 'remote',
      connectionLabel: 'Gateway A',
      profile: 'default',
      handle: 'hermes-gateway-a'
    },
    {
      connectionId: 'gateway-a',
      connectionKind: 'remote',
      connectionLabel: 'Gateway A',
      profile: 'scout',
      handle: 'scout'
    },
    {
      connectionId: 'local',
      connectionKind: 'local',
      connectionLabel: 'This device',
      profile: 'default',
      handle: 'hermes'
    },
    {
      connectionId: 'local',
      connectionKind: 'local',
      connectionLabel: 'This device',
      profile: 'builder',
      handle: 'builder'
    }
  ],
  sources: [
    { connectionId: 'gateway-a', kind: 'remote', label: 'Gateway A', reachable: true },
    { connectionId: 'local', kind: 'local', label: 'This device', reachable: true },
    { connectionId: 'gateway-b', kind: 'ssh', label: 'Gateway B', reachable: false, error: 'timed out' }
  ]
}

function armFleet() {
  hasMultipleConnections.set(true)
  connectionsRegistry.set(registry)
  activeConnectionId.set('gateway-a')
  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
}

const probeLocalBackend = vi.fn(async () => ({ bootstrapNeeded: false }))

beforeEach(() => {
  getAgentRoster.mockResolvedValue(roster)
  probeLocalBackend.mockResolvedValue({ bootstrapNeeded: false })
  selectConnection.mockResolvedValue(undefined)
  openWindow.mockResolvedValue({ ok: true })
  ;(window as { hermesDesktop?: unknown }).hermesDesktop = { getAgentRoster, openWindow, probeLocalBackend }
})

afterEach(() => {
  cleanup()
  $profileOrder.set([])
  vi.clearAllMocks()
  vi.restoreAllMocks()
  _resetFleetRosterForTests()
  hasMultipleConnections.set(false)
  connectionsRegistry.set(null)
  activeConnectionId.set(null)
  activeGatewayProfile.set('default')
  profileScope.set('default')
  profiles.set([{ is_default: true, name: 'default' }])
  delete (window as { hermesDesktop?: unknown }).hermesDesktop
})

describe('ProfileRail overflow', () => {
  // jsdom drops valid gradient values containing calc(); observe the real DOM
  // style assignment instead. Actual layout, resize and painting run in Chromium.
  const observeMask = () => vi.spyOn(Object.getPrototypeOf(document.createElement('div').style), 'maskImage', 'set')
  let mask: ReturnType<typeof observeMask>

  beforeEach(() => {
    mask = observeMask()
  })

  it('marks only clipped edges and leaves create/import outside the scrolling profiles', () => {
    profiles.set(
      Array.from({ length: 8 }, (_, index) => ({ is_default: index === 0, name: index ? `agent${index}` : 'default' }))
    )
    const { container } = render(<ProfileRail />)
    const square = screen.getByRole('button', { name: 'agent1' })
    const scroller = square.closest('.overflow-x-auto') as HTMLDivElement
    expect(scroller).not.toBeNull()
    Object.defineProperties(scroller, {
      clientWidth: { configurable: true, value: 100 },
      scrollWidth: { configurable: true, value: 200 }
    })
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toContain('to right, black,')
    expect(mask.mock.calls.at(-1)?.[0]).toContain('transparent)')
    expect(scroller.contains(screen.getByRole('button', { name: 'New profile' }))).toBe(false)
    expect(scroller.contains(screen.getByRole('button', { name: 'Import profile…' }))).toBe(false)

    scroller.scrollLeft = 50
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toContain('to right, transparent,')
    expect(mask.mock.calls.at(-1)?.[0]).toContain('transparent)')
    scroller.scrollLeft = 100
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toContain('to right, transparent,')
    expect(mask.mock.calls.at(-1)?.[0]).toMatch(/, black\)$/)

    Object.defineProperty(scroller, 'clientWidth', { configurable: true, value: 300 })
    scroller.scrollLeft = 0
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toBe('')
    expect(container.querySelector('[data-slot="profile-dropdown"]')).toBeNull()
  })

  it('maps negative RTL offsets to physical clipped edges and scrolls toward hidden profiles', () => {
    profiles.set(
      Array.from({ length: 8 }, (_, index) => ({ is_default: index === 0, name: index ? `agent${index}` : 'default' }))
    )
    render(<ProfileRail />)
    const scroller = screen.getByRole('button', { name: 'agent1' }).closest('.overflow-x-auto') as HTMLDivElement
    scroller.style.direction = 'rtl'
    Object.defineProperties(scroller, {
      clientWidth: { configurable: true, value: 100 },
      scrollWidth: { configurable: true, value: 200 }
    })
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toContain('to right, transparent,')
    expect(mask.mock.calls.at(-1)?.[0]).toMatch(/, black\)$/)
    scroller.dispatchEvent(new WheelEvent('wheel', { cancelable: true, deltaY: 30 }))
    expect(scroller.scrollLeft).toBe(-30)
    scroller.scrollLeft = -100
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toContain('to right, black,')
    expect(mask.mock.calls.at(-1)?.[0]).toContain('transparent)')
  })

  it('restores wheel navigation and edge feedback after leaving the condensed menu', () => {
    profiles.set(
      Array.from({ length: 14 }, (_, index) => ({ is_default: index === 0, name: index ? `agent${index}` : 'default' }))
    )
    const { container } = render(<ProfileRail />)
    expect(container.querySelector('[data-slot="profile-dropdown"]')).not.toBeNull()
    act(() => profiles.set(profiles.get().slice(0, 8)))
    const scroller = screen.getByRole('button', { name: 'agent1' }).closest('.overflow-x-auto') as HTMLDivElement
    Object.defineProperties(scroller, {
      clientWidth: { configurable: true, value: 100 },
      scrollWidth: { configurable: true, value: 200 }
    })
    const wheel = new WheelEvent('wheel', { cancelable: true, deltaY: 30 })
    scroller.dispatchEvent(wheel)
    expect(wheel.defaultPrevented).toBe(true)
    expect(scroller.scrollLeft).toBe(30)
    fireEvent.scroll(scroller)
    expect(mask.mock.calls.at(-1)?.[0]).toContain('transparent')
    fireEvent.click(screen.getByRole('button', { name: 'agent1' }))
    expect(selectProfile).toHaveBeenCalledWith('agent1')
  })
})

describe('ProfileRail fleet mode', () => {
  it.each([false, true])(
    'keeps right-click launch routes exact without selecting a profile (condensed=%s)',
    async condensed => {
      armFleet()
      activeConnectionId.set('local')
      profiles.set([
        { is_default: true, name: 'default' },
        { is_default: false, name: 'builder' },
        ...(condensed ? Array.from({ length: 12 }, (_, index) => ({ is_default: false, name: `p${index}` })) : [])
      ])
      await renderFleet()

      for (const target of [
        { label: 'builder', connectionId: null, profile: 'builder' },
        { label: 'scout · Gateway A', connectionId: 'gateway-a', profile: 'scout' },
        { label: 'default · Gateway A', connectionId: 'gateway-a', profile: 'default' }
      ]) {
        if (condensed) {
          fireEvent.pointerDown(screen.getByRole('button', { name: 'Profiles' }), { button: 0, ctrlKey: false })
        }

        fireEvent.contextMenu(
          screen.getByRole(condensed ? (target.connectionId ? 'menuitem' : 'menuitemradio') : 'button', {
            name: target.label
          })
        )
        await act(async () => fireEvent.click(screen.getByRole('menuitem', { name: 'Open in new window' })))
        expect(openWindow).toHaveBeenLastCalledWith({ connectionId: target.connectionId, profile: target.profile })
        expect(selectProfile).not.toHaveBeenCalled()
        expect(selectConnection).not.toHaveBeenCalled()
        fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
      }
    }
  )

  it('keeps the custom named-profile order when a source becomes inactive', async () => {
    armFleet()
    profiles.set([...profiles.get(), { name: 'editor', is_default: false }])
    getAgentRoster.mockResolvedValue({
      ...roster,
      agents: [
        ...roster.agents,
        {
          connectionId: 'gateway-a',
          connectionKind: 'remote',
          connectionLabel: 'Gateway A',
          profile: 'editor',
          handle: 'editor'
        }
      ]
    })
    $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('never renders the outgoing source’s squares under an incoming source whose profile read failed', async () => {
    armFleet()
    const container = await renderFleet()

    await act(async () => {
      activeConnectionId.set('local')
      profiles.set([]) // No successful REST result on the incoming source (e.g. 401).
    })

    const active = container.querySelector('[data-active="true"][data-connection-id="local"]') as HTMLElement
    expect(within(active).queryByRole('button', { name: /scout/ })).toBeNull()
    // The outgoing gateway keeps its own roster squares, at rest.
    expect(screen.getByRole('button', { name: 'scout · Gateway A' })).toBeTruthy()
  })

  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 (Gateway A) in ITS slot,
    // never pulled to the front.
    expect(groups).toEqual([
      ['local', false],
      ['gateway-a', true],
      ['gateway-b', 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', 'gateway-a', 'gateway-b'])

    const local = screen.getByRole('group', { name: 'Profiles on This device' })

    const localDevice = within(local).getByRole('button', {
      name: 'This device (local backend — installs Hermes if missing, otherwise opens a fresh session)'
    })

    expect(within(local).getByRole('button', { name: 'builder · This device' })).toBeTruthy()

    // This device is a backend switch that may install (#102826), so its
    // default pill must not share the home glyph other gateways' defaults use.
    expect(localDevice.querySelector('.codicon-device-desktop')).toBeTruthy()
    expect(localDevice.querySelector('.codicon-home')).toBeNull()

    const gatewayB = container.querySelector(
      '[data-slot="profile-rail-gateway"][data-connection-id="gateway-b"]'
    ) as HTMLElement

    const gatewayBHome = within(gatewayB).getByRole('button', { name: 'default · Gateway B' })
    expect(gatewayBHome.querySelector('.codicon-home')).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 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="gateway-b"] [data-slot="profile-rail-unreachable"]'
      )
    ).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 () => {
    armFleet()
    await renderFleet()

    let settle: () => void = () => undefined
    selectConnection.mockImplementationOnce(() => new Promise<void>(resolve => (settle = resolve)))

    const builder = screen.getByRole('button', { name: 'builder · This device' })
    fireEvent.click(builder)

    await act(async () => {
      await Promise.resolve()
    })

    expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'builder' })
    expect(selectProfile).not.toHaveBeenCalled()
    // The dial spinner sits on the clicked square, not in the statusbar.
    expect(builder.getAttribute('aria-busy')).toBe('true')

    await act(async () => {
      settle()
      await Promise.resolve()
    })

    expect(builder.getAttribute('aria-busy')).toBeNull()
  })

  it('opens an installed This device with no prompt', async () => {
    armFleet()
    await renderFleet()

    fireEvent.click(
      screen.getByRole('button', {
        name: 'This device (local backend — installs Hermes if missing, otherwise opens a fresh session)'
      })
    )

    await vi.waitFor(() => expect(selectConnection).toHaveBeenCalledWith('local', { profile: 'default' }))
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('confirms before installing and offers connect-to-existing inline', async () => {
    armFleet()
    probeLocalBackend.mockResolvedValue({ bootstrapNeeded: true })
    await renderFleet()

    fireEvent.click(
      screen.getByRole('button', {
        name: 'This device (local backend — installs Hermes if missing, otherwise opens a fresh session)'
      })
    )

    expect(selectConnection).not.toHaveBeenCalled()
    expect(
      await screen.findByText(
        'This will install Hermes locally, then open a fresh session on this computer. Nothing is installed until you confirm.'
      )
    ).toBeTruthy()

    fireEvent.click(screen.getByRole('button', { name: 'Connect to existing instead' }))

    expect(selectConnection).not.toHaveBeenCalled()
    expect(await screen.findByText('Connect to existing Hermes')).toBeTruthy()
  })

  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: 'builder' }
    ])
    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],
      ['gateway-a', false],
      ['gateway-b', false]
    ])
    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 () => {
    armFleet()
    profiles.set([
      { is_default: true, name: 'default' },
      ...Array.from({ length: 11 }, (_, index) => ({ is_default: false, name: `p${index + 1}` }))
    ])
    // 11 named on Gateway A + local (default, builder) + gateway-b (default) = 14 > 13.
    const container = await renderFleet()

    expect(screen.getByRole('button', { name: 'Profiles' })).toBeTruthy()
    expect(container.querySelector('[data-slot="profile-rail-rest-square"]')).toBeNull()
  })

  it('keeps the device glyph on the This device row once the rail condenses', async () => {
    armFleet()
    profiles.set([
      { is_default: true, name: 'default' },
      ...Array.from({ length: 11 }, (_, index) => ({ is_default: false, name: `p${index + 1}` }))
    ])
    await renderFleet()

    fireEvent.pointerDown(screen.getByRole('button', { name: 'Profiles' }), { button: 0, ctrlKey: false })

    const localDevice = await screen.findByRole('menuitem', {
      name: 'This device (local backend — installs Hermes if missing, otherwise opens a fresh session)'
    })

    expect(localDevice.querySelector('.codicon-device-desktop')).toBeTruthy()
    expect(localDevice.querySelector('.codicon-home')).toBeNull()

    const gatewayBHome = screen.getByRole('menuitem', { name: 'default · Gateway B' })
    expect(gatewayBHome.querySelector('.codicon-home')).toBeTruthy()
  })

  // Regression for #106017 / #131632: the condensed menu listed every at-rest gateway's
  // default but dropped the ACTIVE gateway's own — This device's, in the usual
  // case — leaving it reachable only by hotkey.
  it.each(['local', 'gateway-a'])(
    'lists the active gateway default in the condensed menu (%s active)',
    async active => {
      armFleet()
      activeConnectionId.set(active)
      profiles.set([
        { display_name: 'Arya', is_default: true, name: 'default' } as { is_default: boolean; name: string },
        ...Array.from({ length: 11 }, (_, index) => ({ is_default: false, name: `p${index + 1}` }))
      ])
      await renderFleet()

      const trigger = screen.getByRole('button', { name: 'Profiles' })
      expect(trigger.textContent).toContain('Arya')

      fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false })

      const home = await screen.findByRole('menuitemradio', { name: 'Arya' })
      expect(home.querySelector('.codicon-home')).toBeTruthy()
      expect(home.getAttribute('aria-checked')).toBe('true')

      fireEvent.click(home)
      expect(selectProfile).toHaveBeenCalledWith('default')
    }
  )
})

// Every rail layout must keep a pointer door back to the ACTIVE gateway's
// default. Each layout renders that door through its own code path (single-
// gateway pill, fleet home square, condensed menu); the condensed fleet menu
// dropped it (#106017, #131632). A new layout that drops it fails here.
describe('ProfileRail: the active default is always one click away', () => {
  const ARYA = { display_name: 'Arya', is_default: true, name: 'default' } as { is_default: boolean; name: string }

  const named = (count: number) =>
    Array.from({ length: count }, (_, index) => ({ is_default: false, name: `p${index + 1}` }))

  // Profile counts sit either side of the condensed threshold (13), counting
  // the fleet's at-rest squares: 3 on the other gateways in armFleet's roster.
  const layouts = [
    { fleet: false, condensed: false, active: null, count: 2 },
    { fleet: false, condensed: true, active: null, count: 13 },
    { fleet: true, condensed: false, active: 'local', count: 2 },
    { fleet: true, condensed: true, active: 'local', count: 11 },
    { fleet: true, condensed: false, active: 'gateway-a', count: 2 },
    { fleet: true, condensed: true, active: 'gateway-a', count: 11 }
  ] as const

  const cases = layouts.flatMap(layout => (['named', 'all'] as const).map(from => ({ ...layout, from })))

  it.each(cases)(
    'fleet=$fleet condensed=$condensed active=$active, from $from',
    async ({ active, condensed, count, fleet, from }) => {
      if (fleet) {
        armFleet()
        activeConnectionId.set(active)
      }

      profiles.set([ARYA, ...named(count)])
      activeGatewayProfile.set('p1')
      profileScope.set(from === 'all' ? '*' : 'p1')
      await renderFleet()

      expect(Boolean(screen.queryByRole('button', { name: 'Profiles' })), 'layout under test').toBe(condensed)

      // A visible control named for the default (home pill / home square)…
      const pill = screen
        .queryAllByRole('button')
        .find(button => /\bArya\b/.test(button.getAttribute('aria-label') ?? ''))

      if (pill) {
        fireEvent.click(pill)
      } else {
        // …or its row in the condensed menu.
        fireEvent.pointerDown(screen.getByRole('button', { name: 'Profiles' }), { button: 0, ctrlKey: false })
        fireEvent.click(await screen.findByRole('menuitemradio', { name: 'Arya' }))
      }

      expect(selectProfile).toHaveBeenCalledWith('default')
      expect(selectConnection).not.toHaveBeenCalled()
    }
  )
})