Skip to content

The agent that grows with you

41.1 KB
Raw Blame
import { act, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { registerTerminalContextMenu } from '@/app/right-sidebar/terminal/terminal-context-menu'
import { setApiRequestConnection, setApiRequestProfile } from '@/hermes'
import { createClientSessionState } from '@/lib/chat-runtime'
import { adoptNewSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
import { $confirmRequest, runConfirm, settleConfirm } from '@/store/confirm'
import { $hubInstalledOverride } from '@/store/hub-actions'
import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'
import { requestPluginCatalogInstallFromDeepLink } from '@/store/plugin-catalog-install'
import { openPluginInstallRequest } from '@/store/plugin-install-request'
import {
  _resetLegacyDiscardForTests,
  _resetSessionOwnerHintsForTests,
  getSessionOwnerHint,
  setSessionOwnerHint
} from '@/store/session'
import { dropSessionState, publishSessionState } from '@/store/session-states'
import type * as WindowsStore from '@/store/windows'
import type { SessionInfo } from '@/types/hermes'

import { makeSessionInfo } from '../../../test/session-info'
import { sessionRoute } from '../../routes'

import { useDesktopIntegrations } from './use-desktop-integrations'

// Mutable HUD-window flag so the restore tests can flip the window kind the
// hook believes it runs in. Default false keeps the pre-existing restore
// coverage exercising the real main-window path.
const { hudWindowMock, peerWindowMock } = vi.hoisted(() => ({
  hudWindowMock: vi.fn(() => false),
  peerWindowMock: vi.fn(() => false)
}))

const closeActiveTab = vi.hoisted(() => vi.fn(() => true))

vi.mock('@/app/chat/close-tab', () => ({ closeActiveTab }))

vi.mock('@/store/mcp-deeplink-install', () => ({
  requestMcpInstallFromDeepLink: vi.fn()
}))

vi.mock('@/store/plugin-catalog-install', () => ({
  requestPluginCatalogInstallFromDeepLink: vi.fn()
}))

vi.mock('@/store/plugin-install-request', () => ({
  openPluginInstallRequest: vi.fn()
}))

vi.mock('@/store/windows', async importOriginal => {
  const actual = await importOriginal<typeof WindowsStore>()

  return {
    ...actual,
    isHudWindow: () => hudWindowMock(),
    isPeerInstanceWindow: () => peerWindowMock()
  }
})

// Pure-jsdom localStorage (no nanostores persistence module needed — the
// production functions write directly to window.localStorage through the
// persistString/storedString helpers in @/lib/storage, which in jsdom resolves
// to the real localStorage global).
// We import the hook and drive it with explicit rx-stores/props to exercise the
// profile-ready gate, ownership validation, and legacy-key discard.

const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }
const initialHermesDesktop = desktopWindow.hermesDesktop

const session = (over: Partial<SessionInfo> = {}): SessionInfo => makeSessionInfo({ id: 'live', ...over })

describe('useDesktopIntegrations', () => {
  let navigate: ReturnType<typeof vi.fn<(...args: unknown[]) => void>>

  beforeEach(() => {
    window.localStorage.clear()
    _resetLegacyDiscardForTests()
    vi.mocked(requestMcpInstallFromDeepLink).mockClear()
    vi.mocked(requestPluginCatalogInstallFromDeepLink).mockClear()
    vi.mocked(openPluginInstallRequest).mockClear()
    navigate = vi.fn()
    // Every test starts as a main window; only the HUD describe flips this.
    hudWindowMock.mockReturnValue(false)
    peerWindowMock.mockReturnValue(false)
    // Isolated owner-hint state per test: persisted hints are global
    // module state that would otherwise leak between restore cases.
    _resetSessionOwnerHintsForTests({ storage: true })

    // Stub the desktop bridge so the hook's useEffect callbacks don't try to
    // reach real Electron IPC. The established desktop-test pattern assigns a
    // plain object to window.hermesDesktop rather than using vi.spyOn.
    desktopWindow.hermesDesktop = {
      setPreviewShortcutActive: vi.fn(),
      onOpenUpdatesRequested: vi.fn(),
      onFocusSession: vi.fn(),
      onNotificationAction: vi.fn(),
      onNotificationActivate: vi.fn(),
      onDeepLink: vi.fn(),
      signalDeepLinkReady: vi.fn(),
      onClosePreviewRequested: vi.fn(),
      onOpenFolderRequested: vi.fn(),
      // getSession() rides hermesDesktop.api; tests that exercise the
      // remembered-session resolution stub this per-test.
      api: vi.fn(async () => {
        throw new Error('no api stub for this test')
      })
    } as unknown as Window['hermesDesktop']
  })

  afterEach(() => {
    if (initialHermesDesktop) {
      desktopWindow.hermesDesktop = initialHermesDesktop
    }

    vi.restoreAllMocks()
    document.body.replaceChildren()
  })

  function render({
    activeProfile = 'default',
    locationPathname = '/',
    profileReady = false,
    resumeExhaustedSessionId = null as string | null,
    // null = config record still loading (the hook takes undefined; null dodges the destructuring default).
    resumeLastSession = true as boolean | null,
    routedSessionId = null as string | null,
    sessions = [] as readonly SessionInfo[]
  } = {}) {
    return renderHook(
      ({
        activeProfile,
        locationPathname,
        profileReady,
        resumeExhaustedSessionId,
        resumeLastSession,
        routedSessionId,
        sessions
      }: {
        activeProfile: string
        locationPathname: string
        profileReady: boolean
        resumeExhaustedSessionId: string | null
        resumeLastSession: boolean | null
        routedSessionId: string | null
        sessions: readonly SessionInfo[]
      }) =>
        useDesktopIntegrations({
          activeProfile,
          chatOpen: false,
          hasPreview: false,
          locationPathname,
          navigate,
          profileReady,
          refreshSessions: vi.fn(),
          resumeExhaustedSessionId,
          resumeLastSession: resumeLastSession ?? undefined,
          routedSessionId,
          runtimeIdByStoredSessionId: { current: new Map() },
          sessions
        }),
      {
        initialProps: {
          activeProfile,
          locationPathname,
          profileReady,
          resumeExhaustedSessionId,
          resumeLastSession,
          routedSessionId,
          sessions
        }
      }
    )
  }

  describe('profile-ready gate', () => {
    it('does NOT restore before profileReady is true', () => {
      // Set remembered state, but profileReady=false.
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')

      render({ profileReady: false })

      // no navigation should have occurred
      expect(navigate).not.toHaveBeenCalled()
    })

    it('restores on profileReady when remembered route exists and owns the session', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')

      const sessions = [session({ id: 'remembered-session', profile: 'default' })]

      render({ profileReady: true, sessions })

      expect(navigate).toHaveBeenCalledWith('/remembered-session', { replace: true })
    })

    it('restores remembered session id when no remembered route exists', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')

      const sessions = [session({ id: 'remembered-session', profile: 'default' })]

      render({ profileReady: true, sessions })

      // sessionRoute('remembered-session') = '/remembered-session'
      expect(navigate).toHaveBeenCalledWith('/remembered-session', { replace: true })
    })

    it('announces the restored session so the pre-session draft follows the cold-start navigation', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')
      // Typed on the fresh chat while the backend was still coming up.
      stashSessionDraft(null, 'typed while booting', [])

      render({ profileReady: true, sessions: [session({ id: 'remembered-session', profile: 'default' })] })

      expect(navigate).toHaveBeenCalledWith('/remembered-session', { replace: true })
      // The composer's scope swap may only carry the draft when the restore announced this key.
      expect(adoptNewSessionDraft('remembered-session')).toBe(true)
      expect(takeSessionDraft('remembered-session').text).toBe('typed while booting')
    })

    it('waits for sessions before validating a remembered session route', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')

      const result = render({ profileReady: true, sessions: [] })

      expect(navigate).not.toHaveBeenCalled()
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBe('/remembered-session')

      result.rerender({
        activeProfile: 'default',
        locationPathname: '/',
        profileReady: true,
        resumeExhaustedSessionId: null,
        resumeLastSession: true,
        routedSessionId: null,
        sessions: [session({ id: 'remembered-session', profile: 'default' })]
      })

      expect(navigate).toHaveBeenCalledWith('/remembered-session', { replace: true })
    })
  })

  describe('peer instance windows (#74948)', () => {
    it("does not restore the primary window's remembered session into a peer window", () => {
      // Ctrl+Shift+N opens a peer that shares the profile's remembered
      // navigation (the primary window writes it continuously), but the peer
      // must boot into its own blank fresh-draft chat, not the session the
      // primary window has open.
      peerWindowMock.mockReturnValue(true)
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')

      render({ profileReady: true, sessions: [session({ id: 'remembered-session', profile: 'default' })] })

      expect(navigate).not.toHaveBeenCalled()
      // The remembered values stay intact for the primary window's next boot.
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBe('/remembered-session')
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('remembered-session')
    })
  })

  describe('display.resume_last_session', () => {
    it('stays on the fresh chat when the setting is off, and keeps remembering the open chat', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')

      const sessions = [session({ id: 'remembered-session', profile: 'default' })]
      const result = render({ profileReady: true, resumeLastSession: false, sessions })

      expect(navigate).not.toHaveBeenCalled()

      // The user opens another chat: it is still remembered for the next launch
      // (and for notifications), so flipping the switch back on resumes it.
      result.rerender({
        activeProfile: 'default',
        locationPathname: '/other-session',
        profileReady: true,
        resumeExhaustedSessionId: null,
        resumeLastSession: false,
        routedSessionId: 'other-session',
        sessions: [...sessions, session({ id: 'other-session', profile: 'default' })]
      })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('other-session')
    })

    it('holds the restore until the config record answers, then restores when on', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')

      const sessions = [session({ id: 'remembered-session', profile: 'default' })]
      const result = render({ profileReady: true, resumeLastSession: null, sessions })

      expect(navigate).not.toHaveBeenCalled()

      result.rerender({
        activeProfile: 'default',
        locationPathname: '/',
        profileReady: true,
        resumeExhaustedSessionId: null,
        resumeLastSession: true,
        routedSessionId: null,
        sessions
      })

      expect(navigate).toHaveBeenCalledWith('/remembered-session', { replace: true })
    })
  })

  describe('delegate subagent sessions', () => {
    const stubGetSession = (row: Partial<SessionInfo>) => {
      vi.mocked(desktopWindow.hermesDesktop!.api as ReturnType<typeof vi.fn>).mockImplementation(
        async (request: { path?: string }) => {
          if (request.path?.startsWith('/api/sessions/')) {
            return session({ profile: 'default', ...row })
          }

          throw new Error(`unexpected api call: ${request.path}`)
        }
      )
    }

    it('repairs a remembered delegate child to its parent on restore', async () => {
      // Written by an older build (or a list slice that served the child).
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'delegate-child')
      stubGetSession({ id: 'delegate-child', parent_session_id: 'parent-session', source: 'subagent' })

      const sessions = [session({ id: 'parent-session', profile: 'default' })]

      render({ profileReady: true, sessions })

      await waitFor(() => expect(navigate).toHaveBeenCalledWith('/parent-session', { replace: true }))
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('parent-session')
    })

    // Pins the reachability contract of the by-id resolve branch: the
    // `sessionBelongsToProfile(sessions, remembered, activeProfile)` gate
    // above the repair uses the SAME `sessions` array and the SAME
    // `sessionMatchesStoredId` predicate as `rowFor`, so whenever
    // `repairOwnerHintsForRestore(remembered)` runs, `rowFor(remembered)`
    // finds the row — an id absent from the list is cleared before the
    // repair, it never reaches it (evidence for the #97809 review reply).
    it('clears an unlisted remembered id instead of restoring it', async () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'unlisted-session')
      stubGetSession({ connection_id: 'ssh-proxmox', id: 'unlisted-session', profile: 'default' })
      setSessionOwnerHint('unlisted-session', { connectionId: 'ssh-proxmox', profile: 'default' })

      render({ profileReady: true, sessions: [session({ id: 'other-session', profile: 'default' })] })

      await waitFor(() =>
        expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBeNull()
      )
      expect(navigate).not.toHaveBeenCalledWith('/unlisted-session', { replace: true })
    })

    it('drops a legacy local owner hint when auto-restoring an untagged delegate parent (#97809)', async () => {
      // The delegate child resolves to its parent, and the parent row (listed,
      // untagged) is what the repair consults: an explicit `local` hint is
      // stale, exactly as on the click path.
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'delegate-child')
      stubGetSession({ id: 'delegate-child', parent_session_id: 'parent-session', source: 'subagent' })
      setSessionOwnerHint('parent-session', { connectionId: 'local', profile: 'default' })

      render({ profileReady: true, sessions: [session({ id: 'parent-session', profile: 'default' })] })

      await waitFor(() => expect(navigate).toHaveBeenCalledWith('/parent-session', { replace: true }))
      expect(getSessionOwnerHint('parent-session')).toBeUndefined()
    })

    it('remembers the parent, never the delegate child, when routed to one', () => {
      // A messaging slice can serve the child row, so list membership alone
      // must not make it rememberable.
      const sessions = [
        session({ id: 'delegate-child', parent_session_id: 'parent-session', profile: 'default', source: 'subagent' })
      ]

      render({ locationPathname: '/delegate-child', profileReady: true, routedSessionId: 'delegate-child', sessions })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('parent-session')
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBe('/parent-session')
    })

    it('keeps remembering a /branch child: source, not parenthood, is the discriminator', () => {
      const sessions = [
        session({ id: 'branch-child', parent_session_id: 'parent-session', profile: 'default', source: 'tui' })
      ]

      render({ locationPathname: '/branch-child', profileReady: true, routedSessionId: 'branch-child', sessions })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('branch-child')
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBe('/branch-child')
    })
  })

  describe('resume-exhausted write barrier (#98467)', () => {
    it('does not re-persist an exhausted session on a session-list refresh', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/exhausted-session')
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'exhausted-session')

      const sessions = [session({ id: 'exhausted-session', profile: 'default' })]

      const result = render({ profileReady: true, sessions })

      // The cleanup effect drops the remembered exhausted session...
      result.rerender({
        activeProfile: 'default',
        locationPathname: '/exhausted-session',
        profileReady: true,
        resumeExhaustedSessionId: 'exhausted-session',
        resumeLastSession: true,
        routedSessionId: 'exhausted-session',
        sessions
      })

      // ...and a routine session-list refresh (same sessions, ordinary re-render)
      // must not write the dead id back into remembered navigation.
      result.rerender({
        activeProfile: 'default',
        locationPathname: '/exhausted-session',
        profileReady: true,
        resumeExhaustedSessionId: 'exhausted-session',
        resumeLastSession: true,
        routedSessionId: 'exhausted-session',
        sessions: [...sessions, session({ id: 'other-session', profile: 'default' })]
      })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBeNull()
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBeNull()
    })
  })

  describe('ownership validation', () => {
    it('refuses to restore a session route owned by another profile', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/ai-session')

      const sessions = [session({ id: 'ai-session', profile: 'ai-engineer' })]

      // The route belongs to ai-engineer; active profile is default.
      // No navigation should happen — wrong owner.
      render({ activeProfile: 'default', profileReady: true, sessions })

      expect(navigate).not.toHaveBeenCalled()
    })

    it('refuses to restore a session id owned by another profile', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'ai-session')
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/ai-session')

      const sessions = [session({ id: 'ai-session', profile: 'ai-engineer' })]

      render({ activeProfile: 'default', profileReady: true, sessions })

      // Both route and fallback session id are owned by another profile.
      expect(navigate).not.toHaveBeenCalled()
    })

    it('clears stale remembered route owned by wrong profile', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.ai-engineer', '/ai-session')

      const sessions = [session({ id: 'ai-session', profile: 'ai-engineer' })]

      render({ activeProfile: 'ai-engineer', profileReady: true, sessions })

      // The route and session match the active profile — should restore.
      expect(navigate).toHaveBeenCalledWith('/ai-session', { replace: true })
    })

    it('drops a legacy local owner hint when auto-restoring an untagged row (#97809)', () => {
      // Older builds persisted a `local` hint for a session whose row carries
      // no connection tag (the legacy primary-SSH path). At click time
      // openStoredSession clears it; the boot auto-restore must too, or the
      // pathname-driven resume routes a remote session to the Mac backend.
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'ssh-session')
      setSessionOwnerHint('ssh-session', { connectionId: 'local', profile: 'default' })

      const sessions = [session({ id: 'ssh-session', profile: 'default' })]

      render({ activeProfile: 'default', profileReady: true, sessions })

      expect(navigate).toHaveBeenCalledWith('/ssh-session', { replace: true })
      expect(getSessionOwnerHint('ssh-session')).toBeUndefined()
    })
  })

  describe('two profiles with distinct sessions', () => {
    it('restores profile A session when profile A is active', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.coder', '/coder-session')

      const sessions = [
        session({ id: 'coder-session', profile: 'coder' }),
        session({ id: 'ops-session', profile: 'ops' })
      ]

      render({ activeProfile: 'coder', profileReady: true, sessions })

      expect(navigate).toHaveBeenCalledWith('/coder-session', { replace: true })
    })

    it('does NOT bleed profile A session into profile B', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.coder', '/coder-session')

      const sessions = [session({ id: 'coder-session', profile: 'coder' })]

      // ops profile is active but has no own remembered route
      render({
        activeProfile: 'ops',
        profileReady: true,
        sessions
      })

      // No navigation — coder's remembered route doesn't belong to ops.
      expect(navigate).not.toHaveBeenCalled()
    })
  })

  describe('HUD window (win=hud)', () => {
    beforeEach(() => {
      hudWindowMock.mockReturnValue(true)
    })

    it('does NOT restore remembered navigation on a blank new-chat route', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/remembered-session')

      render({ profileReady: true, sessions: [session({ id: 'remembered-session', profile: 'default' })] })

      // The HUD is a fresh full renderer booting at the default route, but its
      // destination was chosen explicitly by hudTargetSessionId() at open time
      // — remembered-navigation restore must not hijack it to the last session.
      expect(navigate).not.toHaveBeenCalled()
    })

    it('does NOT write remembered navigation while showing a session', () => {
      render({
        profileReady: true,
        routedSessionId: 'live',
        sessions: [session({ id: 'live', profile: 'default' })]
      })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBeNull()
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBeNull()
    })

    it('does not restore the remembered session id either', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'remembered-session')

      render({ profileReady: true, sessions: [session({ id: 'remembered-session', profile: 'default' })] })

      expect(navigate).not.toHaveBeenCalled()
    })
  })

  describe('legacy key behavior', () => {
    it('discards legacy global keys on read and does NOT restore from them', () => {
      // Simulate a pre-per-profile install.
      window.localStorage.setItem('hermes.desktop.lastSessionId', 'legacy-session')
      window.localStorage.setItem('hermes.desktop.lastRoute', '/session/legacy-session')

      // Profile contexts without matching sessions.
      const sessions = [session({ id: 'legacy-session', profile: 'default' })]

      render({ profileReady: true, sessions })

      // Legacy keys must be discarded.
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId')).toBeNull()
      expect(window.localStorage.getItem('hermes.desktop.lastRoute')).toBeNull()

      // And no navigation should happen (the per-profile keys were empty).
      expect(navigate).not.toHaveBeenCalled()
    })
  })

  describe('⌘W close-preview routing over a focused terminal (#65457)', () => {
    let closeRequested: (() => void) | undefined

    function mountWithCloseIpc() {
      desktopWindow.hermesDesktop = {
        ...desktopWindow.hermesDesktop,
        onClosePreviewRequested: (cb: () => void) => {
          closeRequested = cb

          return () => undefined
        }
      } as unknown as Window['hermesDesktop']

      render({ profileReady: true, sessions: [] })
    }

    /** Mirror the production DOM shape: the handle is registered on the
     * xterm host nested inside the [data-terminal] scope, which carries
     * [data-interactive-terminal] only on the user PTY. */
    function focusedTerminal(interactive: boolean): void {
      const scope = document.createElement('div')
      scope.dataset.terminal = ''

      if (interactive) {
        scope.dataset.interactiveTerminal = ''
      }

      const host = document.createElement('div')
      scope.append(host)
      document.body.append(scope)
      scope.tabIndex = -1
      ;(scope as HTMLElement).focus()
      scopeCleanup.push(
        registerTerminalContextMenu(host, {
          getSelection: () => '',
          paste: () => undefined,
          reload: () => {},
          selectAll: () => undefined,
          wordErase: () => true
        })
      )
    }

    const scopeCleanup: Array<() => void> = []

    afterEach(() => {
      for (const cleanup of scopeCleanup.splice(0)) {
        cleanup()
      }

      document.body.replaceChildren()
      closeRequested = undefined
      closeActiveTab.mockClear()
    })

    it('re-delivers the chord to a focused interactive terminal instead of closing', () => {
      mountWithCloseIpc()
      focusedTerminal(true)

      closeRequested?.()

      // The terminal's wordErase verb consumed the chord; the close path
      // never ran.
      expect(closeActiveTab).not.toHaveBeenCalled()
    })

    it('still closes tabs when focus is on a read-only agent terminal', () => {
      mountWithCloseIpc()
      focusedTerminal(false)

      closeRequested?.()

      // The mirror's wordErase is null, so the rung falls through to
      // closeActiveTab — its tab stays closeable.
      expect(closeActiveTab).toHaveBeenCalledOnce()
    })

    it('still closes tabs when focus is outside any terminal', () => {
      mountWithCloseIpc()

      closeRequested?.()

      expect(closeActiveTab).toHaveBeenCalledOnce()
    })
  })

  describe('stale-result suppression during profile switch', () => {
    it('remembers route for the new profile after switch, not the old one', () => {
      const sessions = [
        session({ id: 'coder-session', profile: 'coder' }),
        session({ id: 'ops-session', profile: 'ops' })
      ]

      // Render with coder active and navigate to a session.
      const { rerender } = render({
        activeProfile: 'coder',
        locationPathname: '/coder-session',
        profileReady: true,
        routedSessionId: 'coder-session',
        sessions
      })

      // The coder session should be persisted under coder's key.
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.coder')).toBe('coder-session')

      // Now switch to ops.
      rerender({
        activeProfile: 'ops',
        locationPathname: '/ops-session',
        profileReady: true,
        resumeExhaustedSessionId: null,
        resumeLastSession: true,
        routedSessionId: 'ops-session',
        sessions
      })

      // The ops session should now be persisted under ops's key.
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.ops')).toBe('ops-session')

      // Coder's remembered session should still be there.
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.coder')).toBe('coder-session')
    })

    it('does NOT overwrite remembered state when session ownership fails validation', () => {
      // Simulate an async restore result arriving for a route that doesn't
      // own the active profile.
      const sessions = [session({ id: 'coder-session', profile: 'coder' })]

      // Active profile is ops, but the routed session belongs to coder.
      render({
        activeProfile: 'ops',
        locationPathname: '/',
        profileReady: true,
        routedSessionId: 'coder-session', // wrong profile!
        sessions
      })

      // No session should be remembered for the active profile.
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.ops')).toBeNull()
    })
  })

  describe('route-scoped restoration', () => {
    it('restores a non-session route like /capabilities', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/capabilities')

      const sessions = [session({ id: 'some-session', profile: 'default' })]

      render({ profileReady: true, sessions })

      // /capabilities is not a session route — no ownership validation needed.
      expect(navigate).toHaveBeenCalledWith('/capabilities', { replace: true })
    })

    it('does NOT restore overlay routes (settings/command-center)', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/settings')

      render({ profileReady: true, sessions: [] })

      // Overlay routes should not be restored.
      expect(navigate).not.toHaveBeenCalled()
    })

    it('does NOT persist overlay routes for next boot', () => {
      const { rerender } = render({
        activeProfile: 'default',
        locationPathname: '/settings',
        profileReady: true,
        routedSessionId: null,
        sessions: []
      })

      // Remembering effect fires on route change.
      rerender({
        activeProfile: 'default',
        locationPathname: '/settings',
        profileReady: true,
        resumeExhaustedSessionId: null,
        resumeLastSession: true,
        routedSessionId: null,
        sessions: []
      })

      // Overlay routes must NOT be persisted.
      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBeNull()
    })
  })

  describe('exhausted session cleanup', () => {
    it('clears remembered session id when the exhausted session matches', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'exhausted')

      const sessions = [session({ id: 'exhausted', profile: 'default' })]

      render({
        profileReady: true,
        resumeExhaustedSessionId: 'exhausted',
        sessions
      })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBeNull()
    })

    it('clears remembered route when it carries the exhausted session', () => {
      window.localStorage.setItem('hermes.desktop.lastRoute.profile.default', '/exhausted')

      const sessions = [session({ id: 'exhausted', profile: 'default' })]

      render({
        profileReady: true,
        resumeExhaustedSessionId: 'exhausted',
        sessions
      })

      expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBeNull()
    })

    it('does NOT clear exhausted when profileReady is false', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'exhausted')

      render({
        profileReady: false,
        resumeExhaustedSessionId: 'exhausted',
        sessions: []
      })

      // profileReady=false gates the cleanup effect.
      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('exhausted')
    })

    it('does NOT clear remembered state when exhausted id does not match', () => {
      window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'other-session')

      render({
        profileReady: true,
        resumeExhaustedSessionId: 'exhausted',
        sessions: [session({ id: 'other-session', profile: 'default' })]
      })

      expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBe('other-session')
    })
  })

  describe('notification activate + plugin deep links', () => {
    it('navigates when a plugin notification activate payload arrives', () => {
      let activate: ((payload: { activate?: string }) => void) | undefined
      desktopWindow.hermesDesktop = {
        ...desktopWindow.hermesDesktop,
        onNotificationActivate: (cb: (payload: { activate?: string }) => void) => {
          activate = cb

          return () => undefined
        }
      } as unknown as Window['hermesDesktop']

      render({ profileReady: true, sessions: [] })
      activate?.({ activate: '/index-network/intent/1' })
      expect(navigate).toHaveBeenCalledWith('/index-network/intent/1')
    })

    it('navigates hermes://index-network/intent/1 deep links through the same path vocabulary', () => {
      let deepLink: ((payload: { kind: string; name: string; params: Record<string, string> }) => void) | undefined
      desktopWindow.hermesDesktop = {
        ...desktopWindow.hermesDesktop,
        onDeepLink: (cb: (payload: { kind: string; name: string; params: Record<string, string> }) => void) => {
          deepLink = cb

          return () => undefined
        },
        signalDeepLinkReady: vi.fn()
      } as unknown as Window['hermesDesktop']

      render({ profileReady: true, sessions: [] })
      deepLink?.({ kind: 'index-network', name: 'intent/1', params: {} })
      expect(navigate).toHaveBeenCalledWith('/index-network/intent/1')
    })

    it('routes hermes://mcp/install to the pending-install dialog, not navigation', () => {
      let deepLink: ((payload: { kind: string; name: string; params: Record<string, string> }) => void) | undefined
      desktopWindow.hermesDesktop = {
        ...desktopWindow.hermesDesktop,
        onDeepLink: (cb: (payload: { kind: string; name: string; params: Record<string, string> }) => void) => {
          deepLink = cb

          return () => undefined
        },
        signalDeepLinkReady: vi.fn()
      } as unknown as Window['hermesDesktop']

      render({ profileReady: true, sessions: [] })
      deepLink?.({ kind: 'mcp', name: 'install', params: { name: 'context7' } })
      expect(requestMcpInstallFromDeepLink).toHaveBeenCalledWith({ name: 'context7' })
      expect(navigate).not.toHaveBeenCalled()
    })

    it('routes hermes://plugin/install?catalog= to the catalog lookup, not the git-path modal', () => {
      let deepLink: ((payload: { kind: string; name: string; params: Record<string, string> }) => void) | undefined
      desktopWindow.hermesDesktop = {
        ...desktopWindow.hermesDesktop,
        onDeepLink: (cb: (payload: { kind: string; name: string; params: Record<string, string> }) => void) => {
          deepLink = cb

          return () => undefined
        },
        signalDeepLinkReady: vi.fn()
      } as unknown as Window['hermesDesktop']

      render({ profileReady: true, sessions: [] })
      deepLink?.({ kind: 'plugin', name: 'install', params: { catalog: 'weather', repo: 'evil/repo' } })
      expect(requestPluginCatalogInstallFromDeepLink).toHaveBeenCalledWith('weather')
      expect(openPluginInstallRequest).not.toHaveBeenCalled()
      expect(navigate).not.toHaveBeenCalled()
    })
  })

  describe('catalog install deep links', () => {
    function listen() {
      render({ profileReady: true, resumeLastSession: false })

      return vi.mocked(window.hermesDesktop.onDeepLink!).mock.calls[0]![0]
    }

    afterEach(() => {
      settleConfirm(false)
      $hubInstalledOverride.set({})
      setApiRequestConnection(null)
      setApiRequestProfile(null)
    })

    it('opens repository confirmation without trusting catalog metadata from the link', () => {
      const deepLink = listen()
      const params = { repo: 'owner/repo#plugin', catalog_name: 'catalog-plugin', sha: 'display-pin' }
      deepLink({ kind: 'plugin', name: 'install', params })

      expect(openPluginInstallRequest).toHaveBeenCalledExactlyOnceWith({
        repo: params.repo,
        enable: true,
        force: false,
        legacyHint: null
      })
      expect(requestPluginCatalogInstallFromDeepLink).not.toHaveBeenCalled()
      expect(navigate).not.toHaveBeenCalled()
    })

    it('requires skill confirmation, preserves the request scope, and uses the hub pipeline', async () => {
      const api = vi.fn(async (request: { path: string }) => {
        if (request.path === '/api/skills/hub/install') {
          return { name: 'skill-link-test' }
        }

        if (request.path.startsWith('/api/actions/skill-link-test/')) {
          return { name: 'skill-link-test', running: false, exit_code: 0, lines: ['Installed'], pid: 123 }
        }

        return {}
      })

      desktopWindow.hermesDesktop = { ...desktopWindow.hermesDesktop, api } as unknown as Window['hermesDesktop']
      const deepLink = listen()
      const installs = () => api.mock.calls.filter(([r]) => r.path === '/api/skills/hub/install')
      const identifier = 'skills-sh/owner/repo/skill'
      const payload = { kind: 'skill', name: 'install', params: { identifier } }

      for (const [connection, profile] of [
        ['server-a', 'research'],
        ['server-b', 'work'],
        ['server-a', 'research']
      ]) {
        setApiRequestConnection(connection)
        setApiRequestProfile(profile)
        api.mockClear()
        $hubInstalledOverride.set({})
        act(() => deepLink(payload))
        expect($confirmRequest.get()?.title).toBe('Install “skill”?')
        expect($confirmRequest.get()?.details).toEqual([
          { label: 'Source', value: identifier },
          { label: 'Install to', value: `${connection} · ${profile}` }
        ])
        expect(installs()).toHaveLength(0)
        await act(async () => settleConfirm(false))
        expect(installs()).toHaveLength(0)

        act(() => deepLink(payload))
        await act(async () => runConfirm($confirmRequest.get()!))
        expect($confirmRequest.get()?.phase).toBe('done')
        settleConfirm(true)
        await waitFor(() => expect($hubInstalledOverride.get()[identifier]).toBe(true))
        expect(installs()).toEqual([
          [
            {
              connectionId: connection,
              profile,
              priority: 'foreground',
              path: '/api/skills/hub/install',
              method: 'POST',
              body: { identifier }
            }
          ]
        ])
        expect(api).toHaveBeenCalledWith({
          connectionId: connection,
          profile,
          priority: 'foreground',
          path: '/api/actions/skill-link-test/status?lines=200'
        })
      }

      api.mockClear()
      act(() => deepLink(payload))
      setApiRequestConnection('server-b')
      setApiRequestProfile('work')
      await expect(runConfirm($confirmRequest.get()!)).rejects.toThrow('The destination changed')
      settleConfirm(false)
      expect(installs()).toHaveLength(0)
      act(() => deepLink({ kind: 'skill', name: 'install', params: {} }))
      expect($confirmRequest.get()).toBeNull()
      expect(navigate).not.toHaveBeenCalled()
    })
  })

  describe('notification click -> focus-session id translation', () => {
    function withFocusSession(): (sessionId: string) => void {
      let handler: ((sessionId: string) => void) | undefined
      desktopWindow.hermesDesktop = {
        ...desktopWindow.hermesDesktop,
        onFocusSession: (cb: (sessionId: string) => void) => {
          handler = cb

          return () => undefined
        }
      } as unknown as Window['hermesDesktop']

      return sessionId => handler?.(sessionId)
    }

    function renderWithRuntimeMap(map: Map<string, string>) {
      return renderHook(
        ({ sessions }: { sessions: readonly SessionInfo[] }) =>
          useDesktopIntegrations({
            activeProfile: 'default',
            chatOpen: false,
            hasPreview: false,
            locationPathname: '/',
            navigate,
            profileReady: true,
            refreshSessions: vi.fn(),
            resumeExhaustedSessionId: null,
            resumeLastSession: false,
            routedSessionId: null,
            runtimeIdByStoredSessionId: { current: map },
            sessions
          }),
        { initialProps: { sessions: [] as readonly SessionInfo[] } }
      )
    }

    it('translates a runtime id via the window map before navigating', () => {
      const fire = withFocusSession()

      renderWithRuntimeMap(new Map([['stored-abc', 'runtime-123']]))
      fire('runtime-123')

      // 'stack' intent spends the unoccupied main draft → in-place navigate.
      expect(navigate).toHaveBeenCalledWith(sessionRoute('stored-abc'))
    })

    it('falls back to the durable per-runtime state mirror when the window map has no binding', () => {
      const fire = withFocusSession()
      const { unmount } = renderWithRuntimeMap(new Map())

      // Simulate a main-pane runtime whose ensureSessionState binding lives in
      // the shared store mirror, not this window's map (window reload /
      // pop-out window / gateway respawn).
      publishSessionState('runtime-999', createClientSessionState('stored-xyz'))
      fire('runtime-999')

      expect(navigate).toHaveBeenCalledWith(sessionRoute('stored-xyz'))

      unmount()
      dropSessionState('runtime-999')
    })
  })
})