Skip to content

The agent that grows with you

49.0 KB
Raw Blame
import { act, cleanup, render, waitFor } from '@testing-library/react'
import { type MutableRefObject, useLayoutEffect, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { group } from '@/components/pane-shell/tree/model'
import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'
import type { ChatMessage } from '@/lib/chat-messages'
import { purgeInFlightTurnJournals, resetInFlightTurnJournalStateForTests } from '@/lib/inflight-turn-journal'
import { $activeGatewayProfile } from '@/store/profile'
import {
  $activeSessionStoredIdRotation,
  $currentFastMode,
  $currentModel,
  $currentProvider,
  $currentReasoningEffort,
  $currentServiceTier,
  $messages,
  $selectedStoredSessionId,
  $sessionStartedAt,
  $turnStartedAt,
  setActiveSessionId,
  setActiveSessionStoredIdRotation,
  setCurrentFastMode,
  setCurrentModel,
  setCurrentProvider,
  setCurrentReasoningEffort,
  setCurrentServiceTier,
  setSelectedStoredSessionId,
  setSessions,
  setSessionStartedAt,
  setTurnStartedAt
} from '@/store/session'
import {
  $sessionStates,
  $sessionTiles,
  clearAllSessionStates,
  closeSessionTile,
  openSessionTile,
  reconcileBusyStatesOnReconnect,
  type SessionTileDelegate,
  setSessionTileDelegate,
  setZoneParkedTiles
} from '@/store/session-states'

import { useSessionActions } from './use-session-actions'
import { cachedSessionRow } from './use-session-actions/utils'
import { useSessionStateCache } from './use-session-state-cache'

type Cache = ReturnType<typeof useSessionStateCache>

interface HarnessProps {
  activeSessionId: string | null
  onReady: (cache: Cache) => void
  selectedStoredSessionId: string | null
}

describe('useSessionStateCache — stored-id rotation provenance', () => {
  afterEach(() => {
    cleanup()
    clearAllSessionStates()
    setActiveSessionId(null)
    setActiveSessionStoredIdRotation(null)
    setSelectedStoredSessionId(null)
    setSessions([])
    $sessionTiles.set([])
    $layoutTree.set(null)
    noteActiveTreeGroup(null)
    window.history.pushState({}, '', '/')
  })
  it('emits the previous, next, and runtime ids and removes the stale reverse mapping', () => {
    let cache!: Cache

    setActiveSessionId('runtime-A')
    setSelectedStoredSessionId('stored-A')
    render(
      <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A" />
    )

    act(() => {
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
      cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
    })

    expect($activeSessionStoredIdRotation.get()).toEqual({
      nextStoredSessionId: 'stored-A-next',
      previousStoredSessionId: 'stored-A',
      runtimeSessionId: 'runtime-A'
    })
    expect(cache.runtimeIdByStoredSessionIdRef.current.has('stored-A')).toBe(false)
    expect(cache.runtimeIdByStoredSessionIdRef.current.get('stored-A-next')).toBe('runtime-A')
  })

  it('does not publish a foreground-navigation event for a background runtime rotation', () => {
    let cache!: Cache

    setActiveSessionId('runtime-B')
    render(
      <Harness activeSessionId="runtime-B" onReady={value => (cache = value)} selectedStoredSessionId="stored-B" />
    )

    act(() => {
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
      cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
    })

    expect($activeSessionStoredIdRotation.get()).toBeNull()
    expect(cache.runtimeIdByStoredSessionIdRef.current.has('stored-A')).toBe(false)
    expect(cache.runtimeIdByStoredSessionIdRef.current.get('stored-A-next')).toBe('runtime-A')
  })

  // The foreground has three voices — the stored selection, the HashRouter
  // route and the focused layout pane. Any one of them naming a session
  // outside the rotating lineage means the user already moved on (#86106).
  it.each([
    {
      surface: 'selection',
      arm: () => setSelectedStoredSessionId('stored-B'),
      selected: 'stored-B'
    },
    {
      // Also the pop-out/secondary-window shape: `isSecondaryWindow()` starts
      // that renderer with `$sessionTiles` empty AND `$layoutTree` null, so
      // `$focusedStoredSessionId` collapses to the selection and the route is
      // the only voice left. No tiles and no tree is exactly this case.
      surface: 'hash route',
      arm: () => window.history.pushState({}, '', '/#/stored-B'),
      selected: null
    },
    {
      surface: 'focused tile',
      arm: () => {
        // Route and selection still name A while tile B holds the layout
        // focus. The selection is armed BEFORE the layout: its listener homes
        // focus to the workspace, so the tile focus must be noted last.
        setSessions([{ id: 'stored-A' }, { id: 'stored-B' }] as never)
        $sessionTiles.set([{ storedSessionId: 'stored-B' }])
        setSelectedStoredSessionId('stored-A')
        window.history.pushState({}, '', '/#/stored-A')
        $layoutTree.set(
          group(['workspace', 'session-tile:stored-B'], { active: 'session-tile:stored-B', id: 'grp-main' })
        )
        noteActiveTreeGroup('grp-main')
      },
      selected: 'stored-A'
    }
  ])('does not steal the foreground when the $surface names another session while A rotates', ({ arm, selected }) => {
    let cache!: Cache

    setActiveSessionId('runtime-A')
    arm()
    render(
      <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId={selected} />
    )

    act(() => {
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
      cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
    })

    expect($activeSessionStoredIdRotation.get()).toBeNull()
    expect(cache.runtimeIdByStoredSessionIdRef.current.has('stored-A')).toBe(false)
    expect(cache.runtimeIdByStoredSessionIdRef.current.get('stored-A-next')).toBe('runtime-A')

    // Aftermath of the suppression: nothing re-points the primary, so its
    // selection and route keep the PRE-rotation stored id. That residue is
    // benign only if the id is still a live handle — the lineage row resolves
    // it to the tip, so coming back to this chat resumes A-next (the same
    // resolution `resolveStoredSession` does on every sidebar/route resume)
    // rather than a dead segment.
    setSessions([
      { _lineage_ids: ['stored-A', 'stored-A-next'], _lineage_root_id: 'stored-A', id: 'stored-A-next' }
    ] as never)
    expect(cachedSessionRow('stored-A')?.id).toBe('stored-A-next')
  })

  it.each([
    { shape: 'the primary route is that same session', arm: () => window.history.pushState({}, '', '/#/stored-A') },
    { shape: 'there is no route and no store selection', arm: () => undefined },
    {
      shape: 'the focused tile belongs to the same lineage',
      arm: () => {
        // A tile keyed by an OLDER segment id of the same conversation still
        // counts as the foreground: the rotation carries it to the new tip.
        setSessions([
          { _lineage_ids: ['stored-A', 'stored-A-next'], _lineage_root_id: 'stored-A', id: 'stored-A-next' }
        ] as never)
        $sessionTiles.set([{ storedSessionId: 'stored-A' }])
        $layoutTree.set(
          group(['workspace', 'session-tile:stored-A'], { active: 'session-tile:stored-A', id: 'grp-main' })
        )
        noteActiveTreeGroup('grp-main')
      }
    }
  ])('follows A -> A-next when $shape', ({ arm }) => {
    let cache!: Cache

    setActiveSessionId('runtime-A')
    setSelectedStoredSessionId(null)
    arm()
    render(<Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId={null} />)

    act(() => {
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
      cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
    })

    expect($activeSessionStoredIdRotation.get()).toEqual({
      nextStoredSessionId: 'stored-A-next',
      previousStoredSessionId: 'stored-A',
      runtimeSessionId: 'runtime-A'
    })
  })

  it('re-homes an open tile on a cache-path rotation even when the runtime is background (#98622)', () => {
    let cache!: Cache

    // Background runtime: the rotation atom stays null, but the tile keyed on
    // the pre-rotation id must still re-home to the new tip.
    setActiveSessionId('runtime-B')
    render(
      <Harness activeSessionId="runtime-B" onReady={value => (cache = value)} selectedStoredSessionId="stored-B" />
    )

    act(() => {
      $sessionTiles.set([{ storedSessionId: 'stored-A' }])
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
      cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
    })

    const tiles = $sessionTiles.get()
    expect(tiles.find(t => t.storedSessionId === 'stored-A')).toBeUndefined()
    expect(tiles.find(t => t.storedSessionId === 'stored-A-next')).toBeDefined()
  })

  it('carries the conversation preview tabs onto the new tip when compression rotates it (#73890)', async () => {
    const { $previewTabs, $visiblePreviewTabs, closeRightRail, openPreview } = await import('@/store/preview')
    let cache!: Cache

    setActiveSessionId('runtime-A')
    setSelectedStoredSessionId('stored-A')
    render(
      <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A" />
    )

    try {
      openPreview({ kind: 'url', label: 'Docs', source: 'https://docs.example', url: 'https://docs.example' })

      act(() => {
        cache.updateSessionState('runtime-A', state => state, 'stored-A')
        cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
      })

      expect($previewTabs.get().map(tab => tab.sessionId)).toEqual(['stored-A-next'])
      expect($visiblePreviewTabs.get()).toHaveLength(1)

      act(() => setSelectedStoredSessionId('stored-A-next'))
      expect($visiblePreviewTabs.get()).toHaveLength(1)
    } finally {
      closeRightRail()
    }
  })

  it("hands a runtime's pre-stored-id preview tabs over when its stored id binds, even on a no-op update (#73890)", async () => {
    const { $previewTabs, closeRightRail, openPreview } = await import('@/store/preview')
    let cache!: Cache

    setActiveSessionId('runtime-B')
    setSelectedStoredSessionId(null)
    render(<Harness activeSessionId="runtime-B" onReady={value => (cache = value)} selectedStoredSessionId={null} />)

    try {
      act(() => {
        cache.updateSessionState('runtime-B', state => state, null)
      })
      openPreview({ kind: 'url', label: 'Docs', source: 'https://docs.example', url: 'https://docs.example' }, null)
      expect($previewTabs.get().map(tab => tab.sessionId)).toEqual([undefined])

      act(() => {
        cache.updateSessionState('runtime-B', state => state, 'stored-B')
      })

      expect($previewTabs.get().map(tab => tab.sessionId)).toEqual(['stored-B'])
    } finally {
      closeRightRail()
    }
  })

  it('rekeys the persisted owner profile when its runtime rotates while another profile is visible', () => {
    let cache!: Cache
    const profileA = 'rotation-profile-a-98622'
    const profileB = 'rotation-profile-b-98622'
    const previousStoredSessionId = 'stored-profile-previous'
    const nextStoredSessionId = 'stored-profile-next'

    try {
      act(() => {
        $activeGatewayProfile.set(profileA)
        closeSessionTile(previousStoredSessionId)
        closeSessionTile(nextStoredSessionId)
        openSessionTile(previousStoredSessionId)
        $activeGatewayProfile.set(profileB)
      })

      setActiveSessionId('runtime-visible-b')
      render(
        <Harness
          activeSessionId="runtime-visible-b"
          onReady={value => (cache = value)}
          selectedStoredSessionId={null}
        />
      )

      act(() => {
        cache.updateSessionState('runtime-a', state => state, previousStoredSessionId)
        cache.updateSessionState('runtime-a', state => state, nextStoredSessionId)
      })

      act(() => {
        $activeGatewayProfile.set(profileA)
      })
      expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual([nextStoredSessionId])
    } finally {
      act(() => {
        $activeGatewayProfile.set(profileA)
        closeSessionTile(previousStoredSessionId)
        closeSessionTile(nextStoredSessionId)
        $activeGatewayProfile.set('default')
      })
    }
  })

  it('leaves only the rotated main session when ensureSessionState publishes before route-follow', async () => {
    let cache!: Cache

    setActiveSessionId('runtime-cache-ordering')
    setSelectedStoredSessionId('stored-cache-previous')
    $sessionTiles.set([{ storedSessionId: 'stored-cache-previous' }])
    render(
      <RotationHarness
        activeSessionId="runtime-cache-ordering"
        onReady={value => (cache = value)}
        selectedStoredSessionId="stored-cache-previous"
      />
    )

    act(() => {
      cache.updateSessionState('runtime-cache-ordering', state => state, 'stored-cache-previous')
      cache.updateSessionState('runtime-cache-ordering', state => state, 'stored-cache-next')
    })

    await waitFor(() => expect($selectedStoredSessionId.get()).toBe('stored-cache-next'))
    expect($sessionTiles.get()).toEqual([])
  })

  it('preserves the old tile when a cache update detaches its stored session id', () => {
    let cache!: Cache

    setActiveSessionId('runtime-detach')
    $sessionTiles.set([{ storedSessionId: 'stored-detach-old' }])
    render(
      <Harness activeSessionId="runtime-detach" onReady={value => (cache = value)} selectedStoredSessionId={null} />
    )

    act(() => {
      cache.updateSessionState('runtime-detach', state => state, 'stored-detach-old')
      cache.updateSessionState('runtime-detach', state => state, null)
    })

    expect($sessionTiles.get()).toEqual([{ storedSessionId: 'stored-detach-old' }])
  })

  it('drops the stale tile on a cache-path rotation when the new tip is the main selection (#98622)', () => {
    let cache!: Cache

    setActiveSessionId('runtime-A')
    render(
      <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A-next" />
    )

    act(() => {
      // The drop decision reads the GLOBAL selection atom, not the harness prop.
      setSelectedStoredSessionId('stored-A-next')
      $sessionTiles.set([{ storedSessionId: 'stored-A' }])
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
      cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
    })

    // Main already shows the conversation on the new tip: the tile is dropped
    // entirely (main OR tile — never both).
    expect($sessionTiles.get()).toHaveLength(0)
  })
})

// #77486 review follow-up (kvnloo): the journal under a pre-rotation stored id
// is unreachable by every id a permanent delete holds, so it used to survive
// until MAX_AGE_MS. Rotation now migrates it to the new tip.
describe('useSessionStateCache — journal migration on stored-id rotation', () => {
  beforeEach(() => {
    // The 400ms persist throttle is real timer work; fake timers make the
    // journaled write deterministic without racing the 15s test timeout.
    vi.useFakeTimers()
    resetInFlightTurnJournalStateForTests()
    window.localStorage.clear()
  })

  afterEach(() => {
    cleanup()
    clearAllSessionStates()
    setActiveSessionId(null)
    setActiveSessionStoredIdRotation(null)
    setSelectedStoredSessionId(null)
    setSessions([])
    $sessionTiles.set([])
    window.localStorage.clear()
    resetInFlightTurnJournalStateForTests()
    vi.useRealTimers()
  })

  it('migrates the journaled in-flight tail to the new stored id so permanent delete reaches it', () => {
    let cache!: Cache

    setActiveSessionId('runtime-A')
    setSelectedStoredSessionId('stored-A')
    render(
      <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A" />
    )

    // Busy turn journaled under the lineage tip A.
    act(() => {
      cache.updateSessionState('runtime-A', state => state, 'stored-A')
    })

    const assistantStreaming = assistantText('assistant-stream-1', 'partial answer')

    assistantStreaming.pending = true

    act(() => {
      cache.updateSessionState(
        'runtime-A',
        state => ({
          ...state,
          busy: true,
          messages: [userMessage('u1', 'sensitive prompt'), assistantStreaming],
          streamId: 'assistant-stream-1',
          turnStartedAt: 1000
        }),
        'stored-A'
      )
    })

    act(() => {
      vi.advanceTimersByTime(400)
    })

    const journalKey = (storedSessionId: string) =>
      `hermes.desktop.inflightTurnJournal.v2:${encodeURIComponent(storedSessionId)}`

    expect(window.localStorage.getItem(journalKey('stored-A'))).not.toBeNull()

    // Compression rotates the same runtime's stored id A -> B through the REAL
    // ensureSessionState path (updateSessionState delegates to it).
    act(() => {
      cache.updateSessionState('runtime-A', state => state, 'stored-B')
    })

    // The old key is gone and the new key holds the migrated snapshot.
    expect(window.localStorage.getItem(journalKey('stored-A'))).toBeNull()
    expect(window.localStorage.getItem(journalKey('stored-B'))).not.toBeNull()

    // Permanent delete of the surviving lineage tip B reaches every copy: no
    // journal key for A or B remains (the delete gesture holds B plus the
    // lineage root; A is only reachable because the rotation migrated it).
    act(() => {
      purgeInFlightTurnJournals(['stored-B'])
    })

    expect(window.localStorage.getItem(journalKey('stored-A'))).toBeNull()
    expect(window.localStorage.getItem(journalKey('stored-B'))).toBeNull()
  })
})

function Harness({ activeSessionId, onReady, selectedStoredSessionId }: HarnessProps) {
  const busyRef: MutableRefObject<boolean> = { current: false }

  const cache = useSessionStateCache({
    activeSessionId,
    busyRef,
    selectedStoredSessionId,
    setAwaitingResponse: () => undefined,
    setBusy: () => undefined,
    setMessages: () => undefined
  })

  onReady(cache)

  return null
}

function RotationHarness({ activeSessionId, onReady, selectedStoredSessionId }: HarnessProps) {
  const busyRef = useRef(false)
  const activeSessionIdRef = useRef<string | null>(activeSessionId)
  const selectedStoredSessionIdRef = useRef<string | null>(selectedStoredSessionId)

  const cache = useSessionStateCache({
    activeSessionId,
    busyRef,
    selectedStoredSessionId,
    setAwaitingResponse: () => undefined,
    setBusy: () => undefined,
    setMessages: () => undefined
  })

  useSessionActions({
    activeSessionId,
    activeSessionIdRef,
    busyRef,
    creatingSessionRef: useRef(false),
    ensureSessionState: cache.ensureSessionState,
    getRouteToken: () => 'rotation-test',
    getRoutedStoredSessionId: () => selectedStoredSessionId,
    navigate: vi.fn() as never,
    requestGateway: async () => ({}) as never,
    resetViewSync: cache.resetViewSync,
    routedSessionId: null,
    runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,
    selectedStoredSessionId,
    selectedStoredSessionIdRef,
    sessionStateByRuntimeIdRef: cache.sessionStateByRuntimeIdRef,
    syncSessionStateToView: cache.syncSessionStateToView,
    updateSessionState: cache.updateSessionState
  })

  onReady(cache)

  return null
}

describe('useSessionStateCache — per-session timers', () => {
  beforeEach(() => {
    // The view-sync flush runs on a real rAF in the browser path; in jsdom we
    // want it synchronous so the global mirror is observable immediately. The
    // hook closes over `window.requestAnimationFrame`, so stub that exact ref.
    // Return null (not a handle) so the hook's `viewSyncRafRef.current = rAF(...)`
    // assignment doesn't overwrite the null the synchronous callback just set —
    // otherwise the ref reads truthy and the NEXT sync is suppressed (a real
    // browser returns a handle but runs the callback async, so this race is a
    // test-only artifact of firing synchronously).
    vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => {
      cb(0)

      return null as unknown as number
    })
    setTurnStartedAt(null)
    setCurrentModel('')
    setCurrentProvider('')
    setCurrentReasoningEffort('')
    setCurrentServiceTier('')
    setCurrentFastMode(false)
    setSessionStartedAt(null)
  })

  afterEach(() => {
    cleanup()
    vi.restoreAllMocks()
    setTurnStartedAt(null)
    setCurrentModel('')
    setCurrentProvider('')
    setCurrentReasoningEffort('')
    setCurrentServiceTier('')
    setCurrentFastMode(false)
    setSessionStartedAt(null)
  })

  it('mirrors only the focused runtime session anchor into the global timer', () => {
    let cache!: Cache
    render(<Harness activeSessionId="fg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="fg-stored" />)

    act(() => {
      cache.updateSessionState('bg-runtime', state => ({ ...state, runtimeStartedAt: 1_700_000_000_000 }), 'bg-stored')
    })
    expect($sessionStartedAt.get()).toBeNull()

    act(() => {
      cache.updateSessionState('fg-runtime', state => ({ ...state, runtimeStartedAt: 1_700_000_111_000 }), 'fg-stored')
    })
    expect($sessionStartedAt.get()).toBe(1_700_000_111_000)
  })

  it("keeps a background session's running turn clock and never mirrors it to the view", () => {
    let cache!: Cache
    // Active session is "fg-runtime"; the turn starts on the BACKGROUND session.
    render(<Harness activeSessionId="fg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="fg-stored" />)

    const startedAt = 1_700_000_000_000

    act(() => {
      cache.updateSessionState('bg-runtime', state => ({ ...state, busy: true, turnStartedAt: startedAt }), 'bg-stored')
    })

    // The background session's own cache entry holds the clock...
    expect(cache.sessionStateByRuntimeIdRef.current.get('bg-runtime')?.turnStartedAt).toBe(startedAt)
    // ...but the global atom (statusbar timer) is untouched — a background turn
    // must not drive the foreground timer.
    expect($turnStartedAt.get()).toBeNull()
  })

  it('clears the global clock when the focused turn ends', () => {
    let cache!: Cache
    render(<Harness activeSessionId="fg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="fg-stored" />)

    act(() => {
      cache.updateSessionState(
        'fg-runtime',
        state => ({ ...state, busy: true, turnStartedAt: 1_700_000_222_000 }),
        'fg-stored'
      )
    })
    expect($turnStartedAt.get()).toBe(1_700_000_222_000)

    act(() => {
      cache.updateSessionState('fg-runtime', state => ({ ...state, busy: false, turnStartedAt: null }))
    })
    expect($turnStartedAt.get()).toBeNull()
  })

  it('mirrors the focused session model metadata when switching from a cached session', () => {
    let cache!: Cache

    const { rerender } = render(
      <Harness activeSessionId="fg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="fg-stored" />
    )

    act(() => {
      cache.updateSessionState(
        'bg-runtime',
        state => ({
          ...state,
          fast: true,
          model: 'anthropic/claude-opus-4.8',
          provider: 'anthropic',
          reasoningEffort: 'high',
          serviceTier: 'priority'
        }),
        'bg-stored'
      )
    })

    // Background metadata is cached but must not bleed into the visible statusbar.
    expect($currentModel.get()).toBe('')
    expect($currentReasoningEffort.get()).toBe('')
    expect($currentFastMode.get()).toBe(false)

    rerender(<Harness activeSessionId="bg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="bg-stored" />)

    const bgState = cache.sessionStateByRuntimeIdRef.current.get('bg-runtime')
    expect(bgState).toBeTruthy()

    act(() => {
      cache.syncSessionStateToView('bg-runtime', bgState!)
    })

    expect($currentModel.get()).toBe('anthropic/claude-opus-4.8')
    expect($currentProvider.get()).toBe('anthropic')
    expect($currentReasoningEffort.get()).toBe('high')
    expect($currentServiceTier.get()).toBe('priority')
    expect($currentFastMode.get()).toBe(true)
  })

  it('clears stale model metadata when the newly focused session has no cached value', () => {
    setCurrentModel('previous-model')
    setCurrentProvider('previous-provider')
    setCurrentReasoningEffort('high')
    setCurrentServiceTier('priority')
    setCurrentFastMode(true)

    let cache!: Cache

    const { rerender } = render(
      <Harness activeSessionId="fg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="fg-stored" />
    )

    act(() => {
      cache.updateSessionState('bg-runtime', state => ({ ...state }), 'bg-stored')
    })

    rerender(<Harness activeSessionId="bg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="bg-stored" />)

    const bgState = cache.sessionStateByRuntimeIdRef.current.get('bg-runtime')
    expect(bgState).toBeTruthy()

    act(() => {
      cache.syncSessionStateToView('bg-runtime', bgState!)
    })

    expect($currentModel.get()).toBe('')
    expect($currentProvider.get()).toBe('')
    expect($currentReasoningEffort.get()).toBe('')
    expect($currentServiceTier.get()).toBe('')
    expect($currentFastMode.get()).toBe(false)
  })

  it('mirrors runtime model/provider into the view without persisting over the composer selection (#102793)', () => {
    // A real user pick: persisted to localStorage, the same as picking a
    // provider in the model menu.
    setCurrentModel('claude-opus-5')
    setCurrentProvider('anthropic')
    expect(window.localStorage.getItem('hermes.desktop.composer.provider')).toBe('anthropic')

    let cache!: Cache

    render(<Harness activeSessionId="fg-runtime" onReady={c => (cache = c)} selectedStoredSessionId="fg-stored" />)

    // A session.info heartbeat reports the resolved runtime class — `custom`
    // for a named custom provider — for the same foreground session.
    act(() => {
      cache.updateSessionState(
        'fg-runtime',
        state => ({ ...state, model: 'claude-opus-5', provider: 'custom' }),
        'fg-stored'
      )
    })

    // The visible status area follows the runtime...
    expect($currentProvider.get()).toBe('custom')
    // ...but the user's persisted composer selection must survive the
    // heartbeat, so a fresh chat still follows it instead of `custom`.
    expect(window.localStorage.getItem('hermes.desktop.composer.provider')).toBe('anthropic')
  })
})

interface LayoutProbeHarnessProps {
  activeSessionId: string | null
  onLayoutSnapshot: (snapshot: { active: string | null; selected: string | null }) => void
  onReady: (cache: Cache) => void
  selectedStoredSessionId: string | null
}

function LayoutProbeHarness({
  activeSessionId,
  onLayoutSnapshot,
  onReady,
  selectedStoredSessionId
}: LayoutProbeHarnessProps) {
  const busyRef: MutableRefObject<boolean> = { current: false }

  const cache = useSessionStateCache({
    activeSessionId,
    busyRef,
    selectedStoredSessionId,
    setAwaitingResponse: () => undefined,
    setBusy: () => undefined,
    setMessages: () => undefined
  })

  onReady(cache)

  // useLayoutEffect fires synchronously right after the DOM commit, BEFORE
  // the hook's own useEffect (a passive effect) has a chance to mirror the
  // new props into activeSessionIdRef/selectedStoredSessionIdRef. Anything
  // that reads the refs in this window — including a synchronous DOM event
  // handler firing against the just-committed view — observes the outgoing
  // session's ids.
  useLayoutEffect(() => {
    onLayoutSnapshot({
      active: cache.activeSessionIdRef.current,
      selected: cache.selectedStoredSessionIdRef.current
    })
  })

  return null
}

describe('useSessionStateCache — refs stay coherent with the committed session on switch (#59305)', () => {
  afterEach(() => cleanup())

  it('reflects the new session ids from the layout phase right after switching to a new session', () => {
    let cache!: Cache
    const snapshots: Array<{ active: string | null; selected: string | null }> = []

    const { rerender } = render(
      <LayoutProbeHarness
        activeSessionId="runtime-A"
        onLayoutSnapshot={s => snapshots.push(s)}
        onReady={c => (cache = c)}
        selectedStoredSessionId="stored-A"
      />
    )

    void cache
    snapshots.length = 0 // drop the initial-mount snapshot; only the switch matters

    rerender(
      <LayoutProbeHarness
        activeSessionId="runtime-B"
        onLayoutSnapshot={s => snapshots.push(s)}
        onReady={c => (cache = c)}
        selectedStoredSessionId="stored-B"
      />
    )

    // The refs must already reflect B by the layout phase — a callback firing
    // in this window must never observe the outgoing session's ids.
    expect(snapshots[0]).toEqual({ active: 'runtime-B', selected: 'stored-B' })
  })

  it('does not clobber an imperative ref pin on a re-render that leaves the props unchanged (#54527-class)', () => {
    // submit.ts pins activeSessionIdRef.current to a freshly resumed runtime id
    // WITHOUT updating the source atom that feeds the activeSessionId prop (by
    // design — see submit.ts's "pin the foreground session context" comment).
    // The prop-mirroring here must only fire when the prop itself changes; an
    // unconditional resync would silently undo that pin on the next incidental
    // render (wiring.tsx re-renders constantly during an active turn).
    let cache!: Cache

    const { rerender } = render(
      <Harness activeSessionId="runtime-A" onReady={c => (cache = c)} selectedStoredSessionId="stored-A" />
    )

    // Simulate submit.ts's imperative pin: a resume swapped in a new runtime
    // id without touching the prop.
    cache.activeSessionIdRef.current = 'runtime-resumed'

    // A re-render with the SAME props (e.g. an unrelated $busy/$messages
    // change elsewhere in the tree) must not touch the pinned ref.
    rerender(<Harness activeSessionId="runtime-A" onReady={c => (cache = c)} selectedStoredSessionId="stored-A" />)

    expect(cache.activeSessionIdRef.current).toBe('runtime-resumed')

    // A genuine prop change (a real navigation/selection move) still wins.
    rerender(<Harness activeSessionId="runtime-B" onReady={c => (cache = c)} selectedStoredSessionId="stored-B" />)

    expect(cache.activeSessionIdRef.current).toBe('runtime-B')
  })
})

function userMessage(id: string, text: string): ChatMessage {
  return { id, role: 'user', parts: [{ type: 'text', text }] }
}

function assistantText(id: string, text: string): ChatMessage {
  return { id, role: 'assistant', parts: [{ type: 'text', text }] }
}

function assistantError(id: string, error: string): ChatMessage {
  return { id, role: 'assistant', parts: [], error, pending: false }
}

function transcriptForCache(id: string): ChatMessage[] {
  return [userMessage(`${id}-user`, id), assistantText(`${id}-assistant`, `reply ${id}`)]
}

interface ViewHarnessProps {
  activeSessionId: string | null
  onReady: (cache: Cache) => void
}

function ViewHarness({ activeSessionId, onReady }: ViewHarnessProps) {
  const busyRef: MutableRefObject<boolean> = { current: false }

  const cache = useSessionStateCache({
    activeSessionId,
    busyRef,
    selectedStoredSessionId: null,
    setAwaitingResponse: () => undefined,
    setBusy: () => undefined,
    // Wire the published view back into the real $messages atom the flush
    // reads from, so the round-trip matches production.
    setMessages: messages => $messages.set(messages)
  })

  onReady(cache)

  return null
}

describe('useSessionStateCache — cross-thread error isolation', () => {
  afterEach(() => {
    cleanup()
    $messages.set([])
    $sessionStates.set({})
  })

  it('does not leak a failed turn into another thread on switch', () => {
    $messages.set([])
    let cache!: Cache
    const { rerender } = render(<ViewHarness activeSessionId="thread-A" onReady={c => (cache = c)} />)

    // Thread A ends its turn with an out-of-funds error and is on screen.
    act(() => {
      cache.updateSessionState(
        'thread-A',
        state => ({
          ...state,
          busy: false,
          messages: [userMessage('user-a', 'do the thing'), assistantError('assistant-a-error', 'Out of funds')]
        }),
        'stored-A'
      )
    })

    expect($messages.get().some(message => message.error === 'Out of funds')).toBe(true)

    // Switch to thread B (which completed cleanly). Its cached state syncs to
    // the view while $messages still holds thread A's transcript.
    rerender(<ViewHarness activeSessionId="thread-B" onReady={c => (cache = c)} />)
    act(() => {
      cache.updateSessionState(
        'thread-B',
        state => ({
          ...state,
          busy: false,
          messages: [userMessage('user-b', 'hello'), assistantText('assistant-b', 'hi there')]
        }),
        'stored-B'
      )
    })

    expect($messages.get().map(message => message.id)).toEqual(['user-b', 'assistant-b'])
    expect($messages.get().some(message => message.error === 'Out of funds')).toBe(false)
  })

  it('still preserves a same-session local error a heartbeat dropped', () => {
    $messages.set([])
    let cache!: Cache
    render(<ViewHarness activeSessionId="thread-A" onReady={c => (cache = c)} />)

    // First paint establishes thread A as the on-screen session.
    act(() => {
      cache.updateSessionState(
        'thread-A',
        state => ({ ...state, busy: false, messages: [userMessage('user-a', 'do the thing')] }),
        'stored-A'
      )
    })

    // A local error lands in the view (e.g. failAssistantMessage wrote it).
    $messages.set([userMessage('user-a', 'do the thing'), assistantError('assistant-a-error', 'OpenRouter 403')])

    // A later same-session heartbeat carries cached state that lost the error.
    act(() => {
      cache.updateSessionState('thread-A', state => ({
        ...state,
        busy: false,
        messages: [userMessage('user-a', 'do the thing')]
      }))
    })

    expect($messages.get().some(message => message.error === 'OpenRouter 403')).toBe(true)
  })

  it('evicts the oldest warm transcript with its reverse ownership while retaining lightweight state', () => {
    let cache!: Cache
    render(<Harness activeSessionId={null} onReady={value => (cache = value)} selectedStoredSessionId={null} />)

    act(() => {
      for (let index = 0; index < 25; index += 1) {
        cache.updateSessionState(
          `runtime-${index}`,
          state => ({ ...state, messages: transcriptForCache(`message-${index}`) }),
          `stored-${index}`
        )
      }
    })

    expect(cache.sessionStateByRuntimeIdRef.current.has('runtime-0')).toBe(false)
    expect(cache.runtimeIdByStoredSessionIdRef.current.has('stored-0')).toBe(false)
    expect($sessionStates.get()['runtime-0']).toMatchObject({ storedSessionId: 'stored-0', busy: false })
    expect($sessionStates.get()['runtime-0']?.messages).toEqual([])
    expect(cache.getRuntimeIdForStoredSession('stored-24')).toBe('runtime-24')
  })

  it('only returns a runtime whose cached state owns the requested stored session', () => {
    let cache!: Cache
    render(<Harness activeSessionId={null} onReady={value => (cache = value)} selectedStoredSessionId={null} />)

    act(() => {
      cache.ensureSessionState('runtime-A', 'stored-A')
      cache.ensureSessionState('runtime-B', 'stored-B')
    })

    expect(cache.getRuntimeIdForStoredSession('stored-A')).toBe('runtime-A')
    expect(cache.getRuntimeIdForStoredSession('missing')).toBeNull()

    // Simulate a recycled/cross-wired map entry. The reverse state ownership
    // check must reject it instead of allowing a submit into stored-B.
    cache.runtimeIdByStoredSessionIdRef.current.set('stored-A', 'runtime-B')
    expect(cache.getRuntimeIdForStoredSession('stored-A')).toBeNull()
  })

  describe('reconnect-orphaned transcripts (#95189)', () => {
    // Unique per-test runtime/stored ids: earlier describes in this file leave
    // states in $sessionStates, and a recycled id would let this test's
    // authority probe read THEIR stale flags instead of its own.
    const bg = 'orphan-bg-runtime'
    const fg = 'orphan-fg-runtime'
    const bgStored = 'orphan-bg-stored'
    const fgStored = 'orphan-fg-stored'

    beforeEach(() => {
      $sessionStates.set({})
      setActiveSessionId(null)
    })

    afterEach(() => {
      $sessionStates.set({})
      setActiveSessionId(null)
    })

    it('releases a busy transcript once reconciliation settles the authoritative record', () => {
      let cache!: Cache

      render(<Harness activeSessionId={fg} onReady={value => (cache = value)} selectedStoredSessionId={fgStored} />)

      act(() => {
        // A mid-turn session carries a growing transcript: without messages
        // there would be nothing warm to release.
        cache.updateSessionState(
          bg,
          state => ({
            ...state,
            busy: true,
            messages: [
              { id: `${bg}-user`, role: 'user', parts: [{ type: 'text', text: 'hello' }] },
              { id: `${bg}-assistant`, role: 'assistant', parts: [{ type: 'text', text: 'partial reply' }] }
            ]
          }),
          bgStored
        )
      })

      expect($sessionStates.get()[bg]?.busy).toBe(true)
      expect(cache.sessionStateByRuntimeIdRef.current.has(bg)).toBe(true)

      act(() => {
        // The minting socket died mid-turn; reconnect reconciliation
        // (reconcileBusyStatesOnReconnect) downgrades the authoritative
        // record, and the respawned backend re-mints runtime ids so no event
        // will ever settle this snapshot's own busy flag again.
        const states = $sessionStates.get()

        $sessionStates.set({
          ...states,
          [bg]: { ...states[bg]!, busy: false, awaitingResponse: false }
        })
      })

      // Production caches are bounded by the class defaults (24 sessions /
      // 32MB), and prune only drains once that budget is exceeded. Simulate
      // the reconnect churn of #95189: a stream of settled sessions pushes
      // the cache past its cap, and the orphaned entry — oldest touched,
      // finally warm-eligible now that the authoritative record settled —
      // must be the first thing drained, ownership included.
      const liveBusy = `${bg}-still-working`

      act(() => {
        cache.updateSessionState(
          liveBusy,
          state => ({
            ...state,
            busy: true,
            messages: [{ id: `${liveBusy}-u`, role: 'user', parts: [{ type: 'text', text: 'long turn' }] }]
          }),
          `${liveBusy}-stored`
        )
      })

      for (let i = 0; i < 24; i += 1) {
        act(() => {
          cache.updateSessionState(
            `${bg}-churn-${i}`,
            state => ({
              ...state,
              messages: [{ id: `churn-${i}`, role: 'user', parts: [{ type: 'text', text: `done ${i}` }] }]
            }),
            `${bg}-churn-${i}-stored`
          )
        })
      }

      expect(cache.sessionStateByRuntimeIdRef.current.has(bg)).toBe(false)
      expect(cache.runtimeIdByStoredSessionIdRef.current.has(bgStored)).toBe(false)
      // A genuinely running turn is never a casualty of the drain.
      expect(cache.sessionStateByRuntimeIdRef.current.has(liveBusy)).toBe(true)
    })

    it('keeps a live background turn cached while its authoritative record is busy', () => {
      let cache!: Cache

      render(<Harness activeSessionId={fg} onReady={value => (cache = value)} selectedStoredSessionId={fgStored} />)

      act(() => {
        cache.updateSessionState(bg, state => ({ ...state, busy: true }), bgStored)
      })

      act(() => {
        cache.updateSessionState(fg, state => ({ ...state, model: 'test/model' }))
      })

      expect(cache.sessionStateByRuntimeIdRef.current.has(bg)).toBe(true)
      expect(cache.runtimeIdByStoredSessionIdRef.current.get(bgStored)).toBe(bg)
    })
  })
})

// #117867: the warm-resume transcript gate used to empty the view entirely
// while held, so rows arriving LIVE during the hold (the user's in-flight turn)
// never painted until REST authority landed. The gate now hides only the cached
// prefix captured when the hold was armed.
describe('useSessionStateCache — held transcript gate keeps live rows (#117867)', () => {
  const runtime = 'hold-runtime'
  const stored = 'hold-stored'

  beforeEach(() => {
    clearAllSessionStates()
    setActiveSessionId(runtime)
  })

  afterEach(() => {
    cleanup()
    $messages.set([])
    clearAllSessionStates()
    setActiveSessionId(null)
  })

  it('paints rows appended after the arm and hides only the cached prefix', () => {
    let cache!: Cache
    let release: (() => void) | undefined

    render(<ViewHarness activeSessionId={runtime} onReady={value => (cache = value)} />)

    // Seed the warm cache entry with the unproven cached prefix — exactly what
    // resumeSession has in hand when it arms the hold.
    act(() => {
      cache.updateSessionState(
        runtime,
        state => ({
          ...state,
          messages: [userMessage('cached-1', 'cached prompt'), assistantText('cached-2', 'cached tail')]
        }),
        stored
      )
    })

    // The real production arm path, after the cache entry exists.
    act(() => {
      release = cache.holdSessionTranscriptView(runtime)
    })

    // A live row arrives mid-hold. busy:false forces the critical-transition
    // sync flush (no rAF), so $messages is observable here.
    act(() => {
      cache.updateSessionState(
        runtime,
        state => ({
          ...state,
          busy: false,
          messages: [
            userMessage('cached-1', 'cached prompt'),
            assistantText('cached-2', 'cached tail'),
            userMessage('live-1', 'live turn')
          ]
        }),
        stored
      )
    })

    const ids = $messages.get().map(message => message.id)

    expect(ids).toContain('live-1')
    expect(ids).not.toContain('cached-1')
    expect(ids).not.toContain('cached-2')

    // Releasing restores the full transcript.
    act(() => release?.())
    act(() => {
      cache.updateSessionState(runtime, state => ({ ...state, messages: state.messages }), stored)
    })

    expect($messages.get().map(message => message.id)).toEqual(['cached-1', 'cached-2', 'live-1'])
  })

  it('fails closed when the hold was armed with no cached prefix', () => {
    let cache!: Cache
    let release: (() => void) | undefined

    render(<ViewHarness activeSessionId={runtime} onReady={value => (cache = value)} />)

    act(() => {
      release = cache.holdSessionTranscriptView(runtime)
    })

    act(() => {
      cache.updateSessionState(
        runtime,
        state => ({
          ...state,
          busy: false,
          messages: [userMessage('late-1', 'arrived after the arm')]
        }),
        stored
      )
    })

    // No baseline was captured, so nothing is trustworthy yet: today's
    // hide-everything behavior is preserved until REST authority lands.
    expect($messages.get()).toEqual([])

    act(() => release?.())
  })

  it('keeps a re-sequenced cached tail hidden when compaction assigns fresh ids mid-hold (#117867)', () => {
    let cache!: Cache
    let release: (() => void) | undefined

    render(<ViewHarness activeSessionId={runtime} onReady={value => (cache = value)} />)

    act(() => {
      cache.updateSessionState(
        runtime,
        state => ({
          ...state,
          messages: [userMessage('cached-1', 'cached prompt'), assistantText('cached-2', 'cached tail')]
        }),
        stored
      )
    })

    act(() => {
      release = cache.holdSessionTranscriptView(runtime)
    })

    // A mid-hold compaction re-sequences the cached tail with FRESH row ids
    // while keeping the content (archive_and_compact contract: consumers that
    // reference durable row ids re-resolve by content). An id-only cutoff
    // would pass `seq-*` through as if it were live and paint the compressed
    // tail the hold exists to hide (#73646); the content fingerprint keeps it
    // hidden while a genuinely new row still paints.
    act(() => {
      cache.updateSessionState(
        runtime,
        state => ({
          ...state,
          busy: false,
          messages: [
            userMessage('seq-71', 'cached prompt'),
            assistantText('seq-72', 'cached tail'),
            userMessage('live-1', 'live turn')
          ]
        }),
        stored
      )
    })

    const ids = $messages.get().map(message => message.id)

    expect(ids).toContain('live-1')
    expect(ids).not.toContain('seq-71')
    expect(ids).not.toContain('seq-72')

    act(() => release?.())
  })
})

// #93059: reconnect used to downgrade the $sessionStates mirror only, leaving
// this cache (which warm resume ORs over `running: false`) still busy.
describe('useSessionStateCache — reconnect busy reconcile (#93059)', () => {
  // Only retireBusyClaim is reachable from the store.
  const asDelegate = (partial: Partial<SessionTileDelegate>) => partial as SessionTileDelegate

  // Stands in for "no wiring mounted": every claim is a miss, nothing written.
  const inertDelegate = asDelegate({ retireBusyClaim: () => false })

  afterEach(() => {
    cleanup()
    setSessionTileDelegate(inertDelegate)
    clearAllSessionStates()
    setActiveSessionId(null)
  })

  it('retires the wiring cache entry, not just the store mirror', () => {
    let cache!: Cache

    setActiveSessionId('runtime-1')
    render(
      <Harness activeSessionId="runtime-1" onReady={value => (cache = value)} selectedStoredSessionId="stored-1" />
    )

    // The wiring layer's own retireBusyClaim, over the REAL updateSessionState.
    setSessionTileDelegate(
      asDelegate({
        retireBusyClaim: runtimeId => {
          cache.updateSessionState(runtimeId, state => ({ ...state, awaitingResponse: false, busy: false }))

          return true
        }
      })
    )

    act(() => {
      cache.updateSessionState('runtime-1', state => ({ ...state, awaitingResponse: true, busy: true }), 'stored-1')
    })

    expect(cache.sessionStateByRuntimeIdRef.current.get('runtime-1')?.busy).toBe(true)

    // Backend respawned: no terminal busy:false can arrive for this runtime.
    act(() => reconcileBusyStatesOnReconnect())

    expect(cache.sessionStateByRuntimeIdRef.current.get('runtime-1')?.busy).toBe(false)
    expect(cache.sessionStateByRuntimeIdRef.current.get('runtime-1')?.awaitingResponse).toBe(false)
    expect($sessionStates.get()['runtime-1']?.busy).toBe(false)
  })
})

// #77311: a tile the pane shell PARKED (bounded keep-alive, pane-lifecycle.ts)
// still exists in $sessionTiles, so the warm cache's isReferenced predicate used
// to count it as visible and pin its transcript forever. Parking is the only
// thing that changes here — no navigation, no publish — which is exactly the
// idle-window case the fix has to cover.
describe('useSessionStateCache — parked tiles release their warm transcript (#77311)', () => {
  const runtime = 'parked-runtime'
  const stored = 'parked-stored'

  /** Fill the cache to its settled-entry cap with unreferenced sessions, so a
   *  single additional candidate is enough to force one eviction. */
  const fillToCap = (cache: Cache, count: number) => {
    for (let i = 0; i < count; i += 1) {
      act(() => {
        cache.updateSessionState(
          `parked-filler-${i}`,
          state => ({ ...state, messages: transcriptForCache(`filler-${i}`) }),
          `parked-filler-${i}-stored`
        )
      })
    }
  }

  beforeEach(() => {
    clearAllSessionStates()
    setActiveSessionId(null)
    $sessionTiles.set([{ storedSessionId: stored }])
  })

  afterEach(() => {
    cleanup()
    setZoneParkedTiles('parked-zone', [])
    $sessionTiles.set([])
    clearAllSessionStates()
    setActiveSessionId(null)
  })

  it('evicts and releases a settled parked tile with no other state change', () => {
    let cache!: Cache
    render(<Harness activeSessionId={null} onReady={value => (cache = value)} selectedStoredSessionId={null} />)

    // Seeded first, so it is the least-recently-touched candidate once parked.
    act(() => {
      cache.updateSessionState(runtime, state => ({ ...state, messages: transcriptForCache('parked') }), stored)
    })
    fillToCap(cache, 24)

    // Still on screen as a tile: referenced, therefore not even a candidate.
    expect(cache.sessionStateByRuntimeIdRef.current.has(runtime)).toBe(true)

    act(() => setZoneParkedTiles('parked-zone', [stored]))

    expect(cache.sessionStateByRuntimeIdRef.current.has(runtime)).toBe(false)
    expect(cache.runtimeIdByStoredSessionIdRef.current.has(stored)).toBe(false)
    // releaseSessionTranscript ran: the cheap status projection survives, the
    // transcript bytes do not.
    expect($sessionStates.get()[runtime]).toMatchObject({ storedSessionId: stored })
    expect($sessionStates.get()[runtime]?.messages).toEqual([])
  })

  it('keeps a parked tile whose turn is still running', () => {
    let cache!: Cache
    render(<Harness activeSessionId={null} onReady={value => (cache = value)} selectedStoredSessionId={null} />)

    act(() => {
      cache.updateSessionState(
        runtime,
        state => ({ ...state, busy: true, messages: transcriptForCache('parked-busy') }),
        stored
      )
    })
    // One past the cap, so a drain definitely runs — the busy entry surviving
    // it is the assertion, not an absence of pressure.
    fillToCap(cache, 25)

    act(() => setZoneParkedTiles('parked-zone', [stored]))

    expect(cache.sessionStateByRuntimeIdRef.current.has(runtime)).toBe(true)
    expect($sessionStates.get()[runtime]?.messages.length).toBe(2)
  })
})