Skip to content

The agent that grows with you

6.8 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { createClientSessionState } from '@/lib/chat-runtime'
import { $selectedStoredSessionId, $unreadFinishedSessionIds } from '@/store/session'
import {
  $sessionStates,
  $workingSessionIds,
  clearAllSessionStates,
  publishSessionState,
  reconcileBusyStatesOnReconnect
} from '@/store/session-states'

import { rehydrateLiveSessionStatuses, resetLiveRuntimeTracking } from './use-background-sync'

/**
 * (C) The sidebar spinner is driven by `$workingSessionIds`, which is keyed by
 * STORED session id. A turn that STARTS while Desktop isn't receiving stream
 * events — a background profile, a degraded remote socket, a session opened on
 * another surface — is only ever learned about through the `session.active_list`
 * poll. If that poll can't seed a row the renderer has never seen, the thread
 * name never gets its arc even though the backend is plainly working.
 */
describe('rehydrateLiveSessionStatuses — seeding a turn the renderer never saw start', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    $selectedStoredSessionId.set(null)
    $unreadFinishedSessionIds.set([])
    resetLiveRuntimeTracking()
  })

  afterEach(() => {
    vi.clearAllTimers()
    vi.useRealTimers()
    clearAllSessionStates()
    resetLiveRuntimeTracking()
    $unreadFinishedSessionIds.set([])
  })

  it('shows the spinner for a turn that started with no stream events', () => {
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-cold', session_key: 'stored-cold', status: 'working' }]
    })

    expect($workingSessionIds.get()).toContain('stored-cold')
  })

  it('keeps the spinner across polls while the turn is still running', () => {
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-cold', session_key: 'stored-cold', status: 'working' }]
    })
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-cold', session_key: 'stored-cold', status: 'working' }]
    })

    expect($workingSessionIds.get()).toContain('stored-cold')
  })

  // #113029 (salvage #113038): `session.active_list` is an async snapshot. A
  // stream event that lands while the request is in flight is the newer fact
  // in either direction — an old idle row must not finish a live turn, an old
  // working row must not revive a finished one.
  it('ignores a snapshot captured before a live turn event, in either direction', () => {
    const live = { ...createClientSessionState('stored-race'), busy: true, sawAssistantPayload: true, turnLive: true }

    // Request went out while idle; the turn started before the response landed.
    let stateAtRequest = $sessionStates.get()
    publishSessionState('runtime-race', live)
    rehydrateLiveSessionStatuses(
      { sessions: [{ id: 'runtime-race', session_key: 'stored-race', status: 'idle' }] },
      Date.now(),
      'default',
      stateAtRequest
    )

    expect($workingSessionIds.get()).toContain('stored-race')
    expect($unreadFinishedSessionIds.get()).not.toContain('stored-race')

    // Request went out while working; the turn finished before the response landed.
    stateAtRequest = $sessionStates.get()
    publishSessionState('runtime-race', { ...live, busy: false, turnLive: false })
    rehydrateLiveSessionStatuses(
      { sessions: [{ id: 'runtime-race', session_key: 'stored-race', status: 'working' }] },
      Date.now(),
      'default',
      stateAtRequest
    )

    expect($workingSessionIds.get()).not.toContain('stored-race')
    expect($unreadFinishedSessionIds.get()).toContain('stored-race')
  })

  it('retries absence reconciliation after a newer live event', () => {
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-race', session_key: 'stored-race', status: 'working' }]
    })
    const stateAtRequest = $sessionStates.get()

    publishSessionState('runtime-race', {
      ...createClientSessionState('stored-race'),
      busy: true,
      sawAssistantPayload: true,
      turnLive: true
    })

    rehydrateLiveSessionStatuses({ sessions: [] }, Date.now(), 'default', stateAtRequest)
    expect($workingSessionIds.get()).toContain('stored-race')

    rehydrateLiveSessionStatuses({ sessions: [] })
    expect($workingSessionIds.get()).not.toContain('stored-race')
  })

  // #113029: a reconnect reconcile downgrades busy blind, so it defers the
  // unread dot. The authoritative snapshot decides: gone/idle → the turn really
  // ended while the socket was down and the dot lights; working → no dot.
  it('lights the deferred completion only when the snapshot confirms the turn ended', () => {
    const live = { ...createClientSessionState('stored-race'), busy: true, sawAssistantPayload: true, turnLive: true }

    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-race', session_key: 'stored-race', status: 'working' }]
    })
    publishSessionState('runtime-race', live)
    reconcileBusyStatesOnReconnect()
    expect($unreadFinishedSessionIds.get()).not.toContain('stored-race')

    // Still working on the backend: the arc comes back, no completion.
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-race', session_key: 'stored-race', status: 'working' }]
    })
    expect($workingSessionIds.get()).toContain('stored-race')
    expect($unreadFinishedSessionIds.get()).not.toContain('stored-race')

    // Second reconnect; this time the turn ended while the socket was down.
    reconcileBusyStatesOnReconnect()
    rehydrateLiveSessionStatuses({ sessions: [] })
    expect($workingSessionIds.get()).not.toContain('stored-race')
    expect($unreadFinishedSessionIds.get()).toContain('stored-race')
  })

  it('shows the spinner when a runtime id is recycled onto a new stored session', () => {
    // A respawned backend can mint the same runtime id for a different stored
    // session. The row for the NEW stored id must light up, not the stale one.
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-1', session_key: 'stored-old', status: 'working' }]
    })

    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-1', session_key: 'stored-new', status: 'working' }]
    })

    expect($workingSessionIds.get()).toContain('stored-new')
    expect($workingSessionIds.get()).not.toContain('stored-old')
  })

  it('leaves a starting session idle — the agent build is not proof of a turn', () => {
    // `starting` = `agent_build_started` without `agent_ready`. _start_agent_build
    // runs on the first prompt OR any incidental RPC that needs the agent, so it
    // is not proof of a turn — lighting the spinner here would fire on merely
    // opening a session. A real turn arrives as `working`.
    rehydrateLiveSessionStatuses({
      sessions: [{ id: 'runtime-boot', session_key: 'stored-boot', status: 'starting' }]
    })

    expect($workingSessionIds.get()).not.toContain('stored-boot')
  })
})