Skip to content

The agent that grows with you

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

import type { SessionInfo, SidebarSessionsResponse } from '@/hermes'
import { $cronJobs, setCronJobs } from '@/store/cron'
import {
  beginGatewaySwitch,
  endGatewaySwitch,
  recoverActiveSourceAfterFailedGatewaySwitch,
  registerGatewaySwitchLifecycle
} from '@/store/gateway-switch'
import {
  $cronSessions,
  $messagingPlatformTotals,
  $messagingSessions,
  $messagingTruncated,
  $sessionProfilesFailed,
  $sessionProfilesTruncated,
  $sessionProfilesUsage,
  $sessions,
  $sessionsLoadError,
  $sessionsLoading,
  setCronSessions,
  setMessagingPlatformTotals,
  setMessagingSessions,
  setMessagingTruncated,
  setSessionProfilesFailed,
  setSessionProfilesTruncated,
  setSessionProfilesUsage,
  setSessions,
  setSessionsLoadError,
  setSessionsLoading
} from '@/store/session'

import { deferred } from '../../../test/deferred'

import { useSessionListActions } from './use-session-list-actions'

// Sidebar refresh hygiene: a content-identical refresh (turn complete,
// cross-window broadcast, reconnect) must not replace $sessions' array
// identity — that identity is the dependency for every sidebar memo — and
// must not flicker the loading flag over an already-populated list.

const row = (id: string, over: Partial<SessionInfo> = {}): SessionInfo =>
  ({
    ended_at: null,
    id,
    input_tokens: 0,
    is_active: false,
    last_active: 1000,
    message_count: 3,
    model: 'm',
    output_tokens: 0,
    preview: 'hey',
    profile: 'default',
    source: 'desktop',
    started_at: 900,
    title: `Chat ${id}`,
    ...over
  }) as SessionInfo

// Batched sidebar response builder. `refreshSessions` now makes ONE
// listSidebarSessions call that returns all three slices, replacing the three
// separate listAllProfileSessions calls (each of which reopened every profile
// DB) — #66377-adjacent perf work from the desktop audit canvas.
const sidebar = (
  recents: { sessions: SessionInfo[]; profiles_truncated?: Record<string, boolean> },
  cron: SessionInfo[] = [],
  messaging: SessionInfo[] = []
): SidebarSessionsResponse => ({
  recents: { sessions: recents.sessions, profiles_truncated: recents.profiles_truncated },
  cron: { sessions: cron },
  messaging: { sessions: messaging }
})

const listSidebarSessions = vi.fn()
const listAllProfileSessions = vi.fn()
const getCronJobs = vi.fn()
const gatewayScope = vi.hoisted(() => ({ epoch: 0 }))

interface Deferred<T> {
  promise: Promise<T>
  resolve: (value: T) => void
}

/** Create a promise whose completion order the stale-response tests control. */

vi.mock('@/hermes', async importOriginal => ({
  ...(await importOriginal<Record<string, unknown>>()),
  getCronJobs: (...args: unknown[]) => getCronJobs(...args),
  listAllProfileSessions: (...args: unknown[]) => listAllProfileSessions(...args),
  listSidebarSessions: (...args: unknown[]) => listSidebarSessions(...args)
}))

vi.mock('@/store/gateway', async importOriginal => ({
  ...(await importOriginal<Record<string, unknown>>()),
  gatewayActivationEpoch: () => gatewayScope.epoch
}))

// The refresh only reads the optimistic tombstone set; stub it so we don't pull
// the whole projects store (gateway / fs / git) into this hook's test.
const removed = vi.hoisted(() => ({ ids: new Set<string>() }))

vi.mock('@/store/session-removal', async importActual => ({
  ...(await importActual<Record<string, unknown>>()),
  $removedSessionIds: { get: () => removed.ids }
}))

// The settle-grace keep set must be mocked at MODULE scope: the hook imports
// getRecentlySettledSessionIds as a live ESM binding, so patching a
// dynamically-imported copy (or a temporary object) never reaches it.
const settled = vi.hoisted(() => ({ ids: [] as string[] }))

vi.mock('@/store/session-states', async importActual => ({
  ...(await importActual<Record<string, unknown>>()),
  getRecentlySettledSessionIds: () => settled.ids
}))

beforeEach(() => {
  gatewayScope.epoch = 0
  settled.ids = []
  getCronJobs.mockReset()
  getCronJobs.mockResolvedValue([])
  listSidebarSessions.mockReset()
  listAllProfileSessions.mockReset()
  removed.ids = new Set()
  setCronJobs([])
  setSessions([])
  setCronSessions([])
  setMessagingSessions([])
  setMessagingPlatformTotals({})
  setMessagingTruncated(false)
  setSessionProfilesTruncated({})
  setSessionProfilesUsage({})
  setSessionProfilesFailed([])
  setSessionsLoading(false)
  setSessionsLoadError(false)
})

afterEach(() => {
  setCronJobs([])
  setSessions([])
  setCronSessions([])
  setMessagingSessions([])
  setMessagingPlatformTotals({})
  setMessagingTruncated(false)
  setSessionProfilesTruncated({})
  setSessionProfilesUsage({})
  setSessionsLoading(false)
  setSessionsLoadError(false)
})

describe('workspace-only sidebar refresh', () => {
  it.each(['cwd', 'git_repo_root', 'git_branch'] as const)(
    'publishes %s changes to all slices without another message or a session click',
    async field => {
      const previous = row('moved', { cwd: '/old', git_repo_root: '/old', git_branch: 'old' })
      const incoming = { ...previous, [field]: '/new' }
      setSessions([previous])
      setCronSessions([{ ...previous, source: 'cron' }])
      setMessagingSessions([{ ...previous, source: 'telegram' }])
      listSidebarSessions.mockResolvedValue(
        sidebar({ sessions: [incoming] }, [{ ...incoming, source: 'cron' }], [{ ...incoming, source: 'telegram' }])
      )
      const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

      await act(async () => {
        await result.current.refreshSessions()
      })

      for (const store of [$sessions, $cronSessions, $messagingSessions]) {
        expect(store.get()[0]?.[field]).toBe('/new')
      }

      const snapshots = [$sessions.get(), $cronSessions.get(), $messagingSessions.get()]
      await act(async () => {
        await result.current.refreshSessions()
      })
      ;[$sessions, $cronSessions, $messagingSessions].forEach((store, i) => {
        expect(store.get()).toBe(snapshots[i])
      })
    }
  )
})

// #67600: a cold-start read that fails must not render as "No sessions yet".
describe('refreshSessions cold-start load error', () => {
  const failedScan = (storage?: Record<string, 'corrupt'>): SidebarSessionsResponse => ({
    ...sidebar({ sessions: [] }),
    errors: [{ error: 'boom', profile: 'default' }],
    storage
  })

  it('flags a thrown first read and clears the flag once a retry lands rows', async () => {
    listSidebarSessions.mockRejectedValueOnce(new Error('ECONNREFUSED'))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions().catch(() => undefined)
    })

    expect($sessionsLoadError.get()).toBe(true)
    expect($sessionsLoading.get()).toBe(false)

    listSidebarSessions.mockResolvedValueOnce(sidebar({ sessions: [row('a')] }))
    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessionsLoadError.get()).toBe(false)
    expect($sessions.get().map(s => s.id)).toEqual(['a'])
  })

  it('flags a reported scan failure that leaves the list empty', async () => {
    listSidebarSessions.mockResolvedValueOnce(failedScan())
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessionsLoadError.get()).toBe(true)
  })

  it('flags a failed load that carries retry and omits the session list', async () => {
    listSidebarSessions.mockResolvedValueOnce({
      cron: { errors: [{ error: 'schema heal exhausted', profile: 'default' }], failed: true, retry: true },
      errors: [{ error: 'schema heal exhausted', profile: 'default' }],
      messaging: { errors: [{ error: 'schema heal exhausted', profile: 'default' }], failed: true, retry: true },
      recents: { errors: [{ error: 'schema heal exhausted', profile: 'default' }], failed: true, retry: true }
    })
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessionsLoadError.get()).toBe(true)
    expect($sessions.get()).toEqual([])
  })

  it('leaves a corrupt store to its own notice instead of offering retry', async () => {
    listSidebarSessions.mockResolvedValueOnce(failedScan({ default: 'corrupt' }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessionsLoadError.get()).toBe(false)
  })

  it('never flags a failed refresh over rows already on screen', async () => {
    setSessions([row('a')])
    listSidebarSessions.mockRejectedValueOnce(new Error('ECONNREFUSED'))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions().catch(() => undefined)
    })

    expect($sessionsLoadError.get()).toBe(false)
    expect($sessions.get().map(s => s.id)).toEqual(['a'])
  })

  it('names a profile whose scan failed beside rows that loaded, until a scan reads it', async () => {
    listSidebarSessions.mockResolvedValueOnce({
      ...sidebar({ sessions: [row('a')] }),
      errors: [{ error: 'database is locked', profile: 'work' }]
    })
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'all' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessionsLoadError.get()).toBe(false)
    expect($sessionProfilesFailed.get()).toEqual(['work'])

    listSidebarSessions.mockResolvedValueOnce(sidebar({ sessions: [row('a')] }))
    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessionProfilesFailed.get()).toEqual([])
  })
})

describe('refreshSessions identity + loading hygiene', () => {
  it('keeps the previous $sessions array when the refresh is content-identical', async () => {
    const rows = [row('a'), row('b')]
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: rows }))

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    const first = $sessions.get()
    expect(first.map(s => s.id)).toEqual(['a', 'b'])

    // Second refresh returns fresh (but equal) row objects, as the API does.
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a'), row('b')] }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get()).toBe(first)
  })

  it('swaps the array when rows actually changed', async () => {
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    const first = $sessions.get()

    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a', { last_active: 2000, title: 'Renamed' })] }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get()).not.toBe(first)
    expect($sessions.get()[0].title).toBe('Renamed')
  })

  it('does not flicker the loading flag over a populated list', async () => {
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    const loadingStates: boolean[] = []
    const off = $sessionsLoading.subscribe(value => loadingStates.push(value))

    await act(async () => {
      await result.current.refreshSessions()
    })

    off()
    // Only the initial subscribe emission — no true/false churn per refresh.
    expect(loadingStates).toEqual([false])
  })

  it('drops rows the user just deleted, even when the backend page still lists them', async () => {
    // A delete RPC is in flight: the row is tombstoned optimistically but the
    // batched refresh still carries it (and a lineage-tip variant). Both must be
    // filtered so the optimistic removal never flashes back.
    removed.ids = new Set(['b', 'root-c'])
    listSidebarSessions.mockResolvedValue(
      sidebar({
        sessions: [row('a'), row('b'), row('c', { _lineage_root_id: 'root-c' } as Partial<SessionInfo>)]
      })
    )

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get().map(s => s.id)).toEqual(['a'])
  })

  it('never resurrects a just-archived row the keep set still names (#118156)', async () => {
    // The archive race: the RPC landed (so the in-flight pin released and the
    // projects.tree prune dropped the tombstone — hence EMPTY tombstones
    // here), but the row is still inside the 30s settle grace, so
    // sessionsToKeep() names it. A refresh whose `previous` still holds the
    // row must not carry it back through the survivor path. The map from
    // tombstone→epoch keeps the exclusion alive exactly as long as the
    // tombstone stood, so it must reproduce with the tombstone still set.
    removed.ids = new Set(['just-archived'])

    // Seed $sessions with the row still present, as a refresh racing the
    // optimistic drop would see it.
    setSessions([row('just-archived'), row('mine')])
    // And make the settle grace name it: simulate a turn that just ended.
    settled.ids = ['just-archived']

    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('mine', { message_count: 3 })] }))

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get().map(s => s.id)).toEqual(['mine'])
  })

  it('drops a doomed row whose tombstone was pruned while the page was in flight (#123685)', async () => {
    // The observed Windows resurrection: a sidebar refresh STARTS (reads the
    // page pre-archive-commit), the user archives, the RPC lands, the
    // projects.tree refresh prunes the tombstone (its snapshot is right —
    // the id is gone), and THEN the stale page arrives. Membership is empty
    // by then, so dropTombstoned has nothing to say; only the removal
    // generation delta still names the row.
    const pending = deferred<SidebarSessionsResponse>()
    listSidebarSessions.mockReturnValue(pending.promise)

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const refresh = result.current.refreshSessions()

    // The archive lands mid-flight: tombstone armed, RPC resolves, the tree
    // prune clears membership (the real prune writes the atom directly,
    // which is exactly why the generation guard is needed).
    const removals = await import('@/store/session-removal')
    removals.tombstoneSessions(['doomed'])
    removed.ids = new Set()

    // The keep set still names the doomed row (settle grace), so the
    // survivor path would carry it back if the guard were absent.
    setSessions([row('doomed')])
    settled.ids = ['doomed']

    await act(async () => {
      pending.resolve(sidebar({ sessions: [row('doomed', { message_count: 4 }), row('mine')] }))
      await refresh
    })

    expect($sessions.get().map(s => s.id)).toEqual(['mine'])

    removals.untombstoneSessions(['doomed'])
  })

  it('re-admits a row whose archive rolled back mid-flight (release edge)', async () => {
    // A failed archive untombstones immediately; a page that raced the
    // rollback must still list the row — the guard only vetoes rows whose
    // removal lifecycle moved TOWARD removal.
    const pending = deferred<SidebarSessionsResponse>()
    listSidebarSessions.mockReturnValue(pending.promise)

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const refresh = result.current.refreshSessions()

    const removals = await import('@/store/session-removal')
    removals.tombstoneSessions(['rollback'])
    removals.untombstoneSessions(['rollback'])
    removed.ids = new Set()

    await act(async () => {
      pending.resolve(sidebar({ sessions: [row('rollback')] }))
      await refresh
    })

    expect($sessions.get().map(s => s.id)).toEqual(['rollback'])
  })

  it('matches a pruned-tombstone row by any lineage segment, and filters the cron slice too (#123685)', async () => {
    // The tombstone was armed on the ROOT id while the page carries the row
    // under a middle lineage segment (post-compression): the match must go
    // through _lineage_ids, not just tip + root. Same race shape as above —
    // the prune has already cleared membership.
    const pending = deferred<SidebarSessionsResponse>()
    listSidebarSessions.mockReturnValue(pending.promise)

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const refresh = result.current.refreshSessions()

    const removals = await import('@/store/session-removal')
    removals.tombstoneSessions(['root-x'])
    removed.ids = new Set()

    await act(async () => {
      pending.resolve(
        sidebar(
          { sessions: [row('segment', { _lineage_ids: ['root-x', 'segment', 'tip-x'] } as Partial<SessionInfo>)] },
          [row('cron-doomed', { source: 'cron', _lineage_root_id: 'root-x' } as Partial<SessionInfo>)]
        )
      )
      await refresh
    })

    expect($sessions.get().map(s => s.id)).toEqual([])
    expect($cronSessions.get().map(s => s.id)).toEqual([])

    removals.untombstoneSessions(['root-x'])
  })

  it('keeps idle recents when the sidebar returns an empty page plus profile errors', async () => {
    // Backend contract on disk I/O / lock: HTTP 200, recents=[], errors=[{profile}].
    // mergeSessionPage only keeps working/pinned/selected, so Yesterday/This-week
    // idle rows must be carried forward from the previous list — not clobbered.
    const idle = [row('yesterday'), row('week')]
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: idle }))

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get().map(s => s.id)).toEqual(['yesterday', 'week'])

    setSessionProfilesTruncated({ default: true })
    setSessionProfilesUsage({ default: { cost_usd: 3, tokens: 30 } })
    setMessagingTruncated(true)

    listSidebarSessions.mockResolvedValue({
      ...sidebar({ sessions: [] }),
      errors: [{ error: 'disk I/O error', profile: 'default' }]
    })

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get().map(s => s.id)).toEqual(['yesterday', 'week'])
    expect($sessionProfilesTruncated.get()).toEqual({ default: true })
    expect($sessionProfilesUsage.get()).toEqual({ default: { cost_usd: 3, tokens: 30 } })
    expect($messagingTruncated.get()).toBe(true)
  })

  it('still accepts a genuine empty recents page when the backend reported no errors', async () => {
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($sessions.get()).toEqual([])
  })

  it('drops tombstoned rows from the messaging slice and per-platform paging too (#50928)', async () => {
    // The same delete race exists on every ingestion point: the batched
    // refresh's messaging slice and the per-platform "load more" pager must
    // both honor the tombstone, or a deleted platform thread resurrects.
    removed.ids = new Set(['tg-2'])
    listSidebarSessions.mockResolvedValue(
      sidebar({ sessions: [] }, [], [row('tg-1', { source: 'telegram' }), row('tg-2', { source: 'telegram' })])
    )

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect($messagingSessions.get().map(s => s.id)).toEqual(['tg-1'])

    // Per-platform pager: backend page still lists the doomed row.
    listAllProfileSessions.mockResolvedValue({
      sessions: [
        row('tg-1', { source: 'telegram' }),
        row('tg-2', { source: 'telegram' }),
        row('tg-3', { source: 'telegram' })
      ],
      total: 3
    })

    await act(async () => {
      await result.current.loadMoreMessagingForPlatform('telegram')
    })

    expect($messagingSessions.get().map(s => s.id)).toEqual(['tg-1', 'tg-3'])
  })

  it('still shows loading for the initial (empty-list) fetch', async () => {
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const loadingStates: boolean[] = []
    const off = $sessionsLoading.subscribe(value => loadingStates.push(value))

    await act(async () => {
      await result.current.refreshSessions()
    })

    off()
    expect(loadingStates).toEqual([false, true, false])
  })

  it('does not let a superseded owner publish or release a newer switch loading barrier', async () => {
    const pending = deferred<SidebarSessionsResponse>()
    let ownsRefresh = true

    listSidebarSessions.mockReturnValue(pending.promise)

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
    const refresh = result.current.refreshSessions(() => ownsRefresh)

    expect($sessionsLoading.get()).toBe(true)

    ownsRefresh = false
    setSessions([row('winner')])
    setCronSessions([row('winner-cron', { source: 'cron' })])
    setMessagingSessions([row('winner-message', { source: 'signal' })])
    setMessagingTruncated(true)
    setSessionProfilesTruncated({ winner: true })
    setSessionProfilesUsage({ winner: { cost_usd: 2, tokens: 20 } })
    setSessionsLoading(true)

    await act(async () => {
      pending.resolve({
        recents: {
          profiles_truncated: { stale: true },
          profiles_usage: { stale: { cost_usd: 1, tokens: 10 } },
          sessions: [row('stale')]
        },
        cron: { sessions: [row('stale-cron', { source: 'cron' })] },
        messaging: { sessions: [row('stale-message', { source: 'telegram' })] }
      })
      await refresh
    })

    expect($sessions.get().map(session => session.id)).toEqual(['winner'])
    expect($cronSessions.get().map(session => session.id)).toEqual(['winner-cron'])
    expect($messagingSessions.get().map(session => session.id)).toEqual(['winner-message'])
    expect($messagingTruncated.get()).toBe(true)
    expect($sessionProfilesTruncated.get()).toEqual({ winner: true })
    expect($sessionProfilesUsage.get()).toEqual({ winner: { cost_usd: 2, tokens: 20 } })
    expect($sessionsLoading.get()).toBe(true)
    expect(getCronJobs).not.toHaveBeenCalled()
  })

  it('keeps failed-switch recovery from publishing through a newer switch', async () => {
    const pending = deferred<SidebarSessionsResponse>()

    listSidebarSessions.mockReturnValue(pending.promise)

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const off = registerGatewaySwitchLifecycle({
      beforeConnectionSwitch: () => undefined,
      refreshSessions: result.current.refreshSessions
    })

    let newer: number | undefined

    try {
      const failed = beginGatewaySwitch()

      recoverActiveSourceAfterFailedGatewaySwitch(failed)
      endGatewaySwitch(failed)
      await vi.waitFor(() => expect(listSidebarSessions).toHaveBeenCalledTimes(1))

      // A newer switch owns the freshly wiped lists and loading barrier while
      // the failed switch's real sidebar publisher is still in flight.
      newer = beginGatewaySwitch()

      await act(async () => {
        pending.resolve({
          recents: {
            profiles_truncated: { stale: true },
            profiles_usage: { stale: { cost_usd: 1, tokens: 10 } },
            sessions: [row('stale')]
          },
          cron: { sessions: [row('stale-cron', { source: 'cron' })] },
          messaging: { sessions: [row('stale-message', { source: 'telegram' })] }
        })
        await pending.promise
      })

      expect($sessions.get()).toEqual([])
      expect($cronSessions.get()).toEqual([])
      expect($messagingSessions.get()).toEqual([])
      expect($messagingTruncated.get()).toBe(false)
      expect($sessionProfilesTruncated.get()).toEqual({})
      expect($sessionProfilesUsage.get()).toEqual({})
      expect($sessionsLoading.get()).toBe(true)
      expect($cronJobs.get()).toEqual([])
      expect(getCronJobs).not.toHaveBeenCalled()
    } finally {
      endGatewaySwitch(newer)
      off()
    }
  })

  it('re-reads for the current route after a failed source activation advances the gateway epoch', async () => {
    const pending = deferred<SidebarSessionsResponse>()
    listSidebarSessions
      .mockReturnValueOnce(pending.promise)
      .mockResolvedValueOnce(sidebar({ sessions: [row('current')] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    let refresh!: Promise<void>

    act(() => {
      refresh = result.current.refreshSessions()
    })

    expect($sessionsLoading.get()).toBe(true)

    // A source dial owns a new activation epoch even when it fails and leaves
    // the previous source active. Its in-flight response is stale and must not
    // publish, but nothing else re-requests the list when the route atoms did
    // not move, so the refresh re-reads under the new epoch and releases the
    // initial loading state itself.
    gatewayScope.epoch += 1

    await act(async () => {
      pending.resolve(sidebar({ sessions: [row('stale')] }))
      await refresh
    })

    expect(listSidebarSessions).toHaveBeenCalledTimes(2)
    expect($sessions.get().map(session => session.id)).toEqual(['current'])
    expect($sessionsLoading.get()).toBe(false)
  })

  // #67600 / #88866: re-activating the route the window is already on (a
  // resume or rail click through ensureGatewayAgent('local', 'default'))
  // advances the epoch without changing any route atom, so no effect fires a
  // follow-up refresh. The in-flight 200-with-rows page used to be discarded
  // and the sidebar stayed on "No sessions" until the user re-selected the
  // profile.
  it('fills the sidebar when a same-route re-activation lands mid-refresh', async () => {
    const pending = deferred<SidebarSessionsResponse>()
    const rows = [row('a'), row('b')]
    listSidebarSessions.mockReturnValueOnce(pending.promise).mockResolvedValueOnce(sidebar({ sessions: rows }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    let refresh!: Promise<void>

    act(() => {
      refresh = result.current.refreshSessions()
    })

    gatewayScope.epoch += 1

    await act(async () => {
      pending.resolve(sidebar({ sessions: rows }))
      await refresh
    })

    expect($sessions.get().map(session => session.id)).toEqual(['a', 'b'])
  })

  it('does not re-read a refresh a newer one already superseded', async () => {
    const older = deferred<SidebarSessionsResponse>()
    listSidebarSessions.mockReturnValueOnce(older.promise).mockResolvedValueOnce(sidebar({ sessions: [row('newer')] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const olderRefresh = result.current.refreshSessions()
    gatewayScope.epoch += 1

    await act(async () => {
      await result.current.refreshSessions()
      older.resolve(sidebar({ sessions: [row('older')] }))
      await olderRefresh
    })

    expect(listSidebarSessions).toHaveBeenCalledTimes(2)
    expect($sessions.get().map(session => session.id)).toEqual(['newer'])
  })
})

describe('refreshSessions batches slices into one request', () => {
  it('forwards the active profile scope + section limits to the batched call', async () => {
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'work' }))

    await act(async () => {
      await result.current.refreshSessions()
    })

    expect(listSidebarSessions).toHaveBeenCalledWith(
      expect.objectContaining({
        recentsProfile: 'work',
        recentsExclude: expect.arrayContaining(['cron']),
        messagingExclude: expect.arrayContaining(['cron'])
      })
    )
  })

  it('does not start a refresh callback captured before a profile switch', async () => {
    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))

    const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
      initialProps: { profileScope: 'work' }
    })

    const staleRefresh = result.current.refreshSessions

    rerender({ profileScope: 'personal' })

    await act(async () => {
      await staleRefresh()
    })

    expect(listSidebarSessions).not.toHaveBeenCalled()
  })

  it('keeps the committed profile active when a later render is discarded', async () => {
    const never = new Promise<never>(() => undefined)
    let committedRefresh: (() => Promise<void>) | undefined

    /** Expose only callbacks from committed renders; suspended renders are discarded. */
    function Harness({ profileScope, suspend }: { profileScope: string; suspend: boolean }) {
      const actions = useSessionListActions({ profileScope })

      if (suspend) {
        throw never
      }

      committedRefresh = actions.refreshSessions

      return null
    }

    listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))

    const view = render(
      <Suspense fallback={null}>
        <Harness profileScope="work" suspend={false} />
      </Suspense>
    )

    const workRefresh = committedRefresh!

    view.rerender(
      <Suspense fallback={null}>
        <Harness profileScope="personal" suspend />
      </Suspense>
    )

    await act(async () => {
      await workRefresh()
    })

    expect(listSidebarSessions).toHaveBeenCalledWith(expect.objectContaining({ recentsProfile: 'work' }))
  })

  it('ignores an in-flight sidebar response after the active profile changes', async () => {
    const work = deferred<SidebarSessionsResponse>()
    const personal = deferred<SidebarSessionsResponse>()

    listSidebarSessions.mockImplementation(({ recentsProfile }) =>
      recentsProfile === 'work' ? work.promise : personal.promise
    )

    const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
      initialProps: { profileScope: 'work' }
    })

    const workRefresh = result.current.refreshSessions()

    rerender({ profileScope: 'personal' })
    const personalRefresh = result.current.refreshSessions()

    await act(async () => {
      personal.resolve(
        sidebar(
          { sessions: [row('personal-session', { profile: 'personal' })] },
          [row('personal-cron', { profile: 'personal', source: 'cron' })],
          [row('personal-signal', { profile: 'personal', source: 'signal' })]
        )
      )
      await personalRefresh

      work.resolve(
        sidebar(
          { sessions: [row('work-session', { profile: 'work' })] },
          [row('work-cron', { profile: 'work', source: 'cron' })],
          [row('work-telegram', { profile: 'work', source: 'telegram' })]
        )
      )
      await workRefresh
    })

    expect($sessions.get().map(session => session.id)).toEqual(['personal-session'])
    expect($cronSessions.get().map(session => session.id)).toEqual(['personal-cron'])
    expect($messagingSessions.get().map(session => session.id)).toEqual(['personal-signal'])
  })

  it('ignores an in-flight response after the source changes with the same profile', async () => {
    const work = deferred<SidebarSessionsResponse>()
    const personal = deferred<SidebarSessionsResponse>()

    listSidebarSessions.mockReturnValueOnce(work.promise).mockReturnValueOnce(personal.promise)
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
    const workRefresh = result.current.refreshSessions()

    gatewayScope.epoch += 1
    const personalRefresh = result.current.refreshSessions()

    await act(async () => {
      personal.resolve(
        sidebar({ sessions: [row('personal-session')] }, [], [row('personal-chat', { source: 'telegram' })])
      )
      await personalRefresh

      work.resolve(sidebar({ sessions: [row('work-session')] }, [], [row('work-chat', { source: 'signal' })]))
      await workRefresh
    })

    expect($sessions.get().map(session => session.id)).toEqual(['personal-session'])
    expect($messagingSessions.get().map(session => session.id)).toEqual(['personal-chat'])
  })

  it('requests cron jobs for the unified scope', async () => {
    const unified = renderHook(() => useSessionListActions({ profileScope: '__all__' }))

    await act(async () => {
      await unified.result.current.refreshCronJobs()
    })

    expect(getCronJobs).toHaveBeenLastCalledWith('all')
  })

  it('ignores an out-of-order cron-jobs response from the previous profile', async () => {
    const work = deferred<Array<{ enabled: boolean; id: string }>>()
    const personal = deferred<Array<{ enabled: boolean; id: string }>>()

    getCronJobs.mockImplementation((profile: string) => (profile === 'work' ? work.promise : personal.promise))

    const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
      initialProps: { profileScope: 'work' }
    })

    const workRefresh = result.current.refreshCronJobs()

    rerender({ profileScope: 'personal' })
    const personalRefresh = result.current.refreshCronJobs()

    await act(async () => {
      personal.resolve([{ enabled: true, id: 'personal-job' }])
      await personalRefresh

      work.resolve([{ enabled: true, id: 'work-job' }])
      await workRefresh
    })

    expect(getCronJobs.mock.calls.map(call => call[0])).toEqual(['work', 'personal'])
    expect($cronJobs.get().map(job => job.id)).toEqual(['personal-job'])
  })
})

describe('messaging profile scope', () => {
  it('keeps the explicit all-profiles view unified', async () => {
    listAllProfileSessions.mockResolvedValue({ sessions: [], total: 0 })
    const { result } = renderHook(() => useSessionListActions({ profileScope: '__all__' }))

    await act(async () => {
      await result.current.refreshMessagingSessions()
    })

    expect(listAllProfileSessions.mock.calls[0][4]).toBe('all')
  })

  it('keeps per-platform pagination on the active profile', async () => {
    setMessagingSessions([row('m1', { profile: 'work', source: 'signal' })])
    listAllProfileSessions.mockResolvedValue({
      sessions: [row('m1', { profile: 'work', source: 'signal' }), row('m2', { profile: 'work', source: 'signal' })],
      total: 2
    })
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'work' }))

    await act(async () => {
      await result.current.loadMoreMessagingForPlatform('signal')
    })

    expect(listAllProfileSessions.mock.calls[0][4]).toBe('work')
    expect($messagingSessions.get().map(s => s.id)).toEqual(['m1', 'm2'])
    expect($messagingPlatformTotals.get()).toEqual({ 'work:signal': 2 })
  })

  it('keeps rows from every profile when paginating the unified scope', async () => {
    setMessagingSessions([row('work-signal', { profile: 'work', source: 'signal' })])
    listAllProfileSessions.mockResolvedValue({
      sessions: [
        row('work-signal', { profile: 'work', source: 'signal' }),
        row('personal-signal', { profile: 'personal', source: 'signal' })
      ],
      total: 2
    })

    const { result } = renderHook(() => useSessionListActions({ profileScope: '__all__' }))

    await act(async () => {
      await result.current.loadMoreMessagingForPlatform('signal')
    })

    expect(listAllProfileSessions.mock.calls[0][4]).toBe('all')
    expect($messagingSessions.get().map(session => session.id)).toEqual(['work-signal', 'personal-signal'])
    expect($messagingPlatformTotals.get()).toEqual({ 'all:signal': 2 })
  })

  it('keeps loaded platform rows when pagination fails', async () => {
    const loaded = [row('work-signal', { profile: 'work', source: 'signal' })]
    setMessagingSessions(loaded)
    setMessagingPlatformTotals({ 'work:signal': 12 })
    listAllProfileSessions.mockRejectedValue(new Error('request failed'))

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'work' }))

    await act(async () => {
      await expect(result.current.loadMoreMessagingForPlatform('signal')).resolves.toBeUndefined()
    })

    expect($messagingSessions.get()).toEqual(loaded)
    expect($messagingPlatformTotals.get()).toEqual({ 'work:signal': 12 })
  })

  it('keeps resolved platform totals separate across profile switches', async () => {
    listAllProfileSessions.mockResolvedValue({
      sessions: [row('work-signal', { profile: 'work', source: 'signal' })],
      total: 42
    })

    const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
      initialProps: { profileScope: 'work' }
    })

    await act(async () => {
      await result.current.loadMoreMessagingForPlatform('signal')
    })

    expect($messagingPlatformTotals.get()).toEqual({ 'work:signal': 42 })

    rerender({ profileScope: 'personal' })

    expect($messagingPlatformTotals.get()['personal:signal']).toBeUndefined()
    expect($messagingPlatformTotals.get()['work:signal']).toBe(42)

    listAllProfileSessions.mockResolvedValue({
      sessions: [row('personal-signal', { profile: 'personal', source: 'signal' })],
      total: 3
    })

    await act(async () => {
      await result.current.loadMoreMessagingForPlatform('signal')
    })

    expect($messagingPlatformTotals.get()).toEqual({ 'personal:signal': 3, 'work:signal': 42 })

    rerender({ profileScope: 'work' })

    expect($messagingPlatformTotals.get()['work:signal']).toBe(42)
  })

  it('ignores an older overlapping load-more response for the same profile and platform', async () => {
    const older = deferred<{ sessions: SessionInfo[]; total: number }>()
    const newer = deferred<{ sessions: SessionInfo[]; total: number }>()

    setMessagingSessions([row('m1', { profile: 'work', source: 'signal' })])
    listAllProfileSessions.mockImplementationOnce(() => older.promise).mockImplementationOnce(() => newer.promise)

    const { result } = renderHook(() => useSessionListActions({ profileScope: 'work' }))
    const olderLoad = result.current.loadMoreMessagingForPlatform('signal')

    setMessagingSessions([
      row('m1', { profile: 'work', source: 'signal' }),
      row('m2', { profile: 'work', source: 'signal' })
    ])
    const newerLoad = result.current.loadMoreMessagingForPlatform('signal')

    await act(async () => {
      newer.resolve({
        sessions: [
          row('m1', { profile: 'work', source: 'signal' }),
          row('m2', { profile: 'work', source: 'signal' }),
          row('m3', { profile: 'work', source: 'signal' })
        ],
        total: 3
      })
      await newerLoad

      older.resolve({
        sessions: [row('m1', { profile: 'work', source: 'signal' }), row('m2', { profile: 'work', source: 'signal' })],
        total: 2
      })
      await olderLoad
    })

    expect($messagingSessions.get().map(session => session.id)).toEqual(['m1', 'm2', 'm3'])
    expect($messagingPlatformTotals.get()).toEqual({ 'work:signal': 3 })
  })

  it('ignores an in-flight response after the active profile changes', async () => {
    const work = deferred<{ sessions: SessionInfo[]; total: number }>()
    const personal = deferred<{ sessions: SessionInfo[]; total: number }>()

    listAllProfileSessions.mockImplementation((_limit, _min, _archived, _order, profile) =>
      profile === 'work' ? work.promise : personal.promise
    )

    const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
      initialProps: { profileScope: 'work' }
    })

    const workRefresh = result.current.refreshMessagingSessions()
    rerender({ profileScope: 'personal' })
    const personalRefresh = result.current.refreshMessagingSessions()

    await act(async () => {
      personal.resolve({
        sessions: [row('personal-message', { profile: 'personal', source: 'telegram' })],
        total: 1
      })
      await personalRefresh
      work.resolve({ sessions: [row('work-message', { profile: 'work', source: 'signal' })], total: 1 })
      await workRefresh
    })

    expect(listAllProfileSessions.mock.calls.map(call => call[4])).toEqual(['work', 'personal'])
    expect($messagingSessions.get().map(session => session.id)).toEqual(['personal-message'])
  })

  it('does not let a callback captured before a profile switch disturb current totals', async () => {
    listAllProfileSessions.mockResolvedValue({ sessions: [], total: 0 })
    setMessagingPlatformTotals({ 'work:signal': 12 })

    const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
      initialProps: { profileScope: 'work' }
    })

    const staleRefresh = result.current.refreshMessagingSessions

    rerender({ profileScope: 'personal' })

    await act(async () => {
      await staleRefresh()
    })

    expect(listAllProfileSessions).not.toHaveBeenCalled()
    expect($messagingPlatformTotals.get()).toEqual({ 'work:signal': 12 })
  })

  it('re-reads the messaging slice when a same-route re-activation lands mid-refresh', async () => {
    const pending = deferred<{ sessions: SessionInfo[]; total: number }>()
    const rows = [row('tg', { source: 'telegram' })]
    listAllProfileSessions.mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ sessions: rows, total: 1 })
    const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))

    const refresh = result.current.refreshMessagingSessions()
    gatewayScope.epoch += 1

    await act(async () => {
      pending.resolve({ sessions: rows, total: 1 })
      await refresh
    })

    expect(listAllProfileSessions).toHaveBeenCalledTimes(2)
    expect($messagingSessions.get().map(session => session.id)).toEqual(['tg'])
  })
})