Skip to content

The agent that grows with you

23.5 KB
Raw Blame
import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'
import { MotionGlobalConfig } from 'motion/react'
import { createElement, type ReactElement, type ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { NotificationStack } from '@/components/notifications'
import { getStatus } from '@/hermes'
import { I18nProvider, type Locale, TRANSLATIONS, type Translations } from '@/i18n'
import { $freeTierStatus } from '@/store/free-tier'
import { $setupReadyTick, notifySetupReady } from '@/store/live-sync'
import { $notifications, clearNotifications } from '@/store/notifications'
import { $desktopOnboarding, refreshOnboarding } from '@/store/onboarding'
import { markOnboardingDecided } from '@/store/onboarding-presence'
import { $currentModel } from '@/store/session'

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

import { useStatusSnapshot } from './use-status-snapshot'

vi.mock('@/hermes', () => ({
  getStatus: vi.fn()
}))

type GatewayRequester = <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>

async function flushAsync() {
  await act(async () => {
    await vi.advanceTimersByTimeAsync(0)
  })
}

// This file is about status RPC cadence, not card choreography: the notification
// stack's exit animation would otherwise straddle the fake→real timer swap between
// locales and leave a departing card in the next test's DOM.
MotionGlobalConfig.skipAnimations = true

beforeEach(() => {
  vi.useFakeTimers()
  vi.spyOn(document, 'hasFocus').mockReturnValue(true)
  vi.mocked(getStatus)
    .mockReset()
    .mockResolvedValue({} as never)
  $setupReadyTick.set(0)
  $desktopOnboarding.set({ ...$desktopOnboarding.get(), flow: { status: 'idle' } })
  clearNotifications()
})

afterEach(() => {
  cleanup()
  vi.restoreAllMocks()
  vi.useRealTimers()
})

describe('useStatusSnapshot', () => {
  it.each(Object.entries(TRANSLATIONS) as [Locale, Translations][])(
    'localizes and deduplicates shared-profile warnings in %s',
    async (locale: Locale, copy: Translations): Promise<void> => {
      const warning: string = copy.notifications.sharedProfileWarning

      expect(warning).toBeTypeOf('string')

      const wrapper: (props: { children: ReactNode }) => ReactElement = ({
        children
      }: {
        children: ReactNode
      }): ReactElement => createElement(I18nProvider, { configClient: null, initialLocale: locale, children })

      const requestGateway: GatewayRequester = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester

      render(createElement(NotificationStack), { wrapper })

      const { rerender }: { rerender: (props: { scope: string }) => void } = renderHook(
        ({ scope }: { scope: string }): ReturnType<typeof useStatusSnapshot> =>
          useStatusSnapshot('open', requestGateway, scope),
        {
          initialProps: { scope: 'local-default' },
          wrapper
        }
      )

      await flushAsync()
      expect(screen.queryByText(warning)).toBeNull()
      vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: true } as never)
      await act(async (): Promise<void> => {
        await vi.advanceTimersByTimeAsync(60_000)
      })
      expect(screen.getByText(warning)).toBeTruthy()
      // Dismiss departs through the card stack (store row on a microtask, then the exit).
      await act(async (): Promise<void> => {
        fireEvent.click(screen.getByRole('button', { name: copy.notifications.dismiss }))
        await vi.advanceTimersByTimeAsync(100)
      })
      expect(screen.queryByText(warning)).toBeNull()
      await act(async (): Promise<void> => {
        await vi.advanceTimersByTimeAsync(60_000)
      })
      expect(screen.queryByText(warning)).toBeNull()

      vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: false } as never)
      await act(async (): Promise<void> => {
        await vi.advanceTimersByTimeAsync(60_000)
      })
      vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: true } as never)
      await act(async (): Promise<void> => {
        await vi.advanceTimersByTimeAsync(60_000)
      })
      expect(screen.getByText(warning)).toBeTruthy()
      vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: false } as never)
      rerender({ scope: 'local-work' })
      await flushAsync()
      await act(async (): Promise<void> => {
        await vi.advanceTimersByTimeAsync(100)
      })
      expect(screen.queryByText(warning)).toBeNull()
    }
  )

  it('drops the free-tier verdict on a profile or source switch, not on a gateway flap', async () => {
    const requestGateway = vi.fn().mockRejectedValue(new Error('offline')) as unknown as GatewayRequester
    const signedOut = { available: true, enabled: true, has_guest: true, label: '', model: '', notice_pending: false }

    const { rerender } = renderHook(
      ({ gatewayState, scope }) => useStatusSnapshot(gatewayState, requestGateway, scope),
      { initialProps: { gatewayState: 'open', scope: 'local\0work' } }
    )

    await flushAsync()
    $freeTierStatus.set(signedOut)
    rerender({ gatewayState: 'connecting', scope: 'local\0work' })
    rerender({ gatewayState: 'open', scope: 'local\0work' })
    await flushAsync()
    expect($freeTierStatus.get()).toEqual(signedOut)

    rerender({ gatewayState: 'open', scope: 'local\0home' })
    await flushAsync()
    expect($freeTierStatus.get()).toBeNull()
  })

  it('pauses status RPCs while visible but unfocused, then catches up on focus', async () => {
    vi.mocked(document.hasFocus).mockReturnValue(false)
    const requestGateway = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester

    renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()

    expect(getStatus).not.toHaveBeenCalled()
    expect(requestGateway).not.toHaveBeenCalled()

    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })
    expect(getStatus).not.toHaveBeenCalled()

    vi.mocked(document.hasFocus).mockReturnValue(true)
    window.dispatchEvent(new Event('focus'))
    await flushAsync()

    expect(getStatus).toHaveBeenCalledOnce()
    // One refresh round = setup.status + setup.runtime_check + free_tier.status.
    expect(requestGateway).toHaveBeenCalledTimes(3)
  })

  it('keeps the last authoritative readiness through a transient RPC failure', async () => {
    let refresh = 0

    const requestGatewayMock = vi.fn(async (method: string) => {
      const cycle = Math.floor(refresh / 2)
      refresh += 1

      if (cycle > 0) {
        throw new Error(`${method} timed out`)
      }

      return (method === 'setup.runtime_check' ? { ok: true } : { provider_configured: true }) as never
    })

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))

    await flushAsync()
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })

    await act(async () => {
      await vi.advanceTimersByTimeAsync(15_000)
    })

    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })
  })

  it('does not present an initial transport failure as inference not ready', async () => {
    const requestGatewayMock = vi.fn(async (method: string) => {
      throw new Error(`${method} connection closed`)
    })

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))

    await flushAsync()

    expect(result.current.inferenceStatus).toBeNull()
  })

  it('still publishes an authoritative runtime failure', async () => {
    const requestGatewayMock = vi.fn(
      async (method: string) =>
        (method === 'setup.runtime_check'
          ? { error: 'No usable credentials found for nous.', ok: false }
          : { provider_configured: true }) as never
    )

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))

    await flushAsync()

    expect(result.current.inferenceStatus).toMatchObject({
      ready: false,
      reason: expect.stringContaining('No usable credentials found for nous.'),
      source: 'runtime_check'
    })
  })

  it('clears readiness immediately when the gateway disconnects', async () => {
    const pendingStatus = deferred<never>()

    vi.mocked(getStatus)
      .mockResolvedValueOnce({} as never)
      .mockReturnValueOnce(pendingStatus.promise)

    const requestGateway = vi.fn(
      async (method: string) =>
        (method === 'setup.runtime_check' ? { ok: true } : { provider_configured: true }) as never
    ) as unknown as GatewayRequester

    const { rerender, result } = renderHook(({ gatewayState }) => useStatusSnapshot(gatewayState, requestGateway), {
      initialProps: { gatewayState: 'open' }
    })

    await flushAsync()
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })

    rerender({ gatewayState: 'connecting' })

    expect(getStatus).toHaveBeenCalledTimes(2)
    expect(result.current.inferenceStatus).toBeNull()
  })

  it('refreshes readiness by source and ignores the previous backend response', async () => {
    const workRuntime = deferred<unknown>()
    const workSetup = deferred<unknown>()
    const homeRuntime = deferred<unknown>()
    const homeSetup = deferred<unknown>()
    let source = 'work'

    const requestGateway = vi.fn((method: string) => {
      if (source === 'work') {
        return method === 'setup.runtime_check' ? workRuntime.promise : workSetup.promise
      }

      return method === 'setup.runtime_check' ? homeRuntime.promise : homeSetup.promise
    }) as unknown as GatewayRequester

    const { rerender, result } = renderHook(({ scope }) => useStatusSnapshot('open', requestGateway, scope), {
      initialProps: { scope: 'work\0default' }
    })

    await flushAsync()
    source = 'home'
    rerender({ scope: 'home\0default' })
    await flushAsync()

    expect(result.current.inferenceStatus).toBeNull()

    await act(async () => {
      homeRuntime.resolve({ ok: true })
      homeSetup.resolve({ provider_configured: true })
      await vi.advanceTimersByTimeAsync(0)
    })
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })

    await act(async () => {
      workRuntime.resolve({ error: 'stale backend', ok: false })
      workSetup.resolve({ provider_configured: false })
      await vi.advanceTimersByTimeAsync(0)
    })
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })
  })

  it('waits for a slow refresh to settle before scheduling another one', async () => {
    const setup = deferred<unknown>()
    const runtime = deferred<unknown>()

    const requestGatewayMock = vi.fn(
      (method: string) => (method === 'setup.runtime_check' ? runtime.promise : setup.promise) as never
    )

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()

    // Open runs the readiness legs once: setup.status, setup.runtime_check, free_tier.status.
    expect(getStatus).toHaveBeenCalledOnce()
    expect(requestGatewayMock).toHaveBeenCalledTimes(3)

    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })

    expect(getStatus).toHaveBeenCalledOnce()
    expect(requestGatewayMock).toHaveBeenCalledTimes(3)

    await act(async () => {
      setup.resolve({ provider_configured: true })
      runtime.resolve({ ok: true })
      await vi.advanceTimersByTimeAsync(0)
    })

    await act(async () => {
      await vi.advanceTimersByTimeAsync(59_999)
    })
    expect(getStatus).toHaveBeenCalledOnce()

    await act(async () => {
      await vi.advanceTimersByTimeAsync(1)
    })

    // The periodic tick is status-only: readiness and the free-tier verdict
    // arrive by `setup.ready` push plus the one-shots on open and on return.
    expect(getStatus).toHaveBeenCalledTimes(2)
    expect(requestGatewayMock).toHaveBeenCalledTimes(3)
  })

  it('retries readiness on the 60s tick while no authoritative verdict exists yet', async () => {
    // A gateway flap answers with no boolean at all, so the round falls back to
    // the transport verdict and the status stays null — the chip reads
    // "checking" until some later seam fires, if one ever does.
    let answering = false

    const requestGatewayMock = vi.fn(async (method: string) => {
      if (!answering) {
        return {} as never
      }

      return (method === 'setup.runtime_check' ? { ok: true } : { provider_configured: true }) as never
    })

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()

    expect(result.current.inferenceStatus).toBeNull()

    answering = true

    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })

    const methods = requestGatewayMock.mock.calls.map(([method]) => method)
    expect(methods.filter(method => method === 'setup.runtime_check')).toHaveLength(2)
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })
  })

  it('retries a fully failed readiness round on the tick, then stops once a verdict lands', async () => {
    // Both readiness legs fail here, which is the only shape that leaves no
    // authoritative answer at all: one surviving leg is enough to publish.
    let answering = false

    const requestGatewayMock = vi.fn(async (method: string) => {
      if (!answering) {
        throw new Error(`${method} connection closed`)
      }

      return (method === 'setup.runtime_check' ? { ok: true } : { provider_configured: true }) as never
    })

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()

    expect(result.current.inferenceStatus).toBeNull()

    answering = true

    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })

    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })

    // Recovery ends the retries: an answered chip needs no further readiness
    // traffic, so the ambient 60s poll goes back to being status-only.
    requestGatewayMock.mockClear()

    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })

    const methods = requestGatewayMock.mock.calls.map(([method]) => method)
    expect(methods.filter(method => method === 'setup.runtime_check')).toHaveLength(0)
    expect(getStatus).toHaveBeenCalledTimes(3)
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })
  })

  it('clears the "Local model unavailable" notice once the local server recovers', async () => {
    // The Webapp opened while the local server was still starting: onboarding stayed exempt
    // (configured) and raised the notice. Recovery must take it down, not leave "ready" beside it.
    let serving = false

    const requestGatewayMock = vi.fn(async (method: string) => {
      if (method === 'setup.runtime_check') {
        return (
          serving
            ? { ok: true }
            : { error: 'The local model server is not running.', error_code: 'local_runtime_unavailable', ok: false }
        ) as never
      }

      return { provider_configured: true } as never
    })

    const requestGateway = requestGatewayMock as unknown as GatewayRequester
    markOnboardingDecided()
    await refreshOnboarding({ requestGateway })
    const notice = () => $notifications.get().find(item => item.id === 'local-runtime-unavailable')
    expect(notice()).toBeTruthy()

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()
    expect(result.current.inferenceStatus).toMatchObject({ errorCode: 'local_runtime_unavailable', ready: false })

    // A starting server announces nothing to this window: the ambient tick keeps checking.
    serving = true
    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })

    expect(result.current.inferenceStatus).toMatchObject({ ready: true })
    expect(notice()).toBeUndefined()
  })

  it('backs off re-checking a local model server that stays down, and resets on a model switch', async () => {
    // Enabled but unable to boot (no staged model): every check kicks a boot and blocks for seconds.
    const requestGatewayMock = vi.fn(
      async (method: string) =>
        (method === 'setup.runtime_check'
          ? { error: 'The local model server is not running.', error_code: 'local_runtime_unavailable', ok: false }
          : { provider_configured: true }) as never
    )

    const requestGateway = requestGatewayMock as unknown as GatewayRequester
    const checks = () => requestGatewayMock.mock.calls.filter(([method]) => method === 'setup.runtime_check').length

    const advance = async (ms: number) => {
      await act(async () => {
        await vi.advanceTimersByTimeAsync(ms)
      })
    }

    renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()
    expect(checks()).toBe(1)

    await advance(60_000) // first gap: 60 s
    expect(checks()).toBe(2)

    await advance(60_000) // second gap: 2 min
    expect(checks()).toBe(2)
    await advance(60_000)
    expect(checks()).toBe(3)

    await advance(240_000) // then a 5-minute cap
    expect(checks()).toBe(3)
    await advance(60_000)
    expect(checks()).toBe(4)
    await advance(240_000)
    expect(checks()).toBe(4)
    await advance(60_000)
    expect(checks()).toBe(5)

    // The status tick itself never slowed down.
    expect(getStatus).toHaveBeenCalledTimes(14)

    // A model switch asks again on the next tick.
    $currentModel.set('another/model')
    await advance(60_000)
    expect(checks()).toBe(6)
  })

  it('re-reads readiness and the free-tier verdict once per setup.ready, off the status tick', async () => {
    const requestGatewayMock = vi.fn(
      async (method: string) =>
        (method === 'setup.runtime_check' ? { ok: true } : { provider_configured: true }) as never
    )

    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()
    requestGatewayMock.mockClear()
    vi.mocked(getStatus).mockClear()

    await act(async () => {
      notifySetupReady()
      await vi.advanceTimersByTimeAsync(0)
    })

    const methods = requestGatewayMock.mock.calls.map(([method]) => method)
    expect(methods.filter(method => method === 'free_tier.status')).toHaveLength(1)
    expect(methods.filter(method => method === 'setup.runtime_check')).toHaveLength(1)
    expect(methods.filter(method => method === 'setup.status')).toHaveLength(1)
    expect(getStatus).not.toHaveBeenCalled()
  })

  it('ignores setup.ready while the gateway is not open', async () => {
    const requestGatewayMock = vi.fn(async () => ({}) as never)
    const requestGateway = requestGatewayMock as unknown as GatewayRequester

    renderHook(() => useStatusSnapshot('connecting', requestGateway))
    await flushAsync()

    await act(async () => {
      notifySetupReady()
      await vi.advanceTimersByTimeAsync(0)
    })

    expect(requestGatewayMock).not.toHaveBeenCalled()
  })

  it('keeps the same snapshot reference across a content-equal 60s re-read; a real change publishes', async () => {
    vi.mocked(getStatus).mockImplementation(async () => ({ version: '1.0.0' }) as never)
    const requestGateway = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()

    const first = result.current.statusSnapshot
    expect(first).toEqual({ version: '1.0.0' })

    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })
    expect(getStatus).toHaveBeenCalledTimes(2)
    // Identity preserved on a no-op: consumers keyed on the snapshot must not re-render.
    expect(result.current.statusSnapshot).toBe(first)

    vi.mocked(getStatus).mockImplementation(async () => ({ version: '1.0.1' }) as never)
    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })
    expect(result.current.statusSnapshot).toEqual({ version: '1.0.1' })
  })

  it('clears a stale readiness failure when OAuth completes while unfocused', async () => {
    let healthy = false

    const requestGateway = vi.fn(async (method: string) => {
      if (method === 'setup.runtime_check') {
        return (healthy ? { ok: true } : { error: 'No usable credentials found for nous.', ok: false }) as never
      }

      return { provider_configured: healthy } as never
    }) as unknown as GatewayRequester

    // Focused: seed the authoritative credential failure.
    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()
    expect(result.current.inferenceStatus).toMatchObject({ ready: false, source: 'runtime_check' })

    // User leaves Hermes for the browser to complete OAuth; no focus event fires.
    vi.mocked(document.hasFocus).mockReturnValue(false)
    healthy = true

    // OAuth completes: the onboarding flow transitions to success while unfocused.
    await act(async () => {
      $desktopOnboarding.set({
        ...$desktopOnboarding.get(),
        flow: { status: 'success', provider: { id: 'nous', name: 'Nous' } as never }
      })
      await vi.advanceTimersByTimeAsync(0)
    })

    // The stale failure is replaced by the healthy result without a focus event.
    expect(result.current.inferenceStatus).toMatchObject({ ready: true, source: 'runtime_check' })
  })

  it('does not force a background poll on non-success onboarding transitions while unfocused', async () => {
    const requestGateway = vi.fn(
      async (method: string) =>
        (method === 'setup.runtime_check' ? { ok: true } : { provider_configured: true }) as never
    ) as unknown as GatewayRequester

    vi.mocked(document.hasFocus).mockReturnValue(false)
    renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()
    expect(requestGateway).not.toHaveBeenCalled()

    // A non-success flow change (e.g. entering the polling state) must not
    // trigger the focus-bypassing refresh — only auth success does.
    await act(async () => {
      $desktopOnboarding.set({
        ...$desktopOnboarding.get(),
        flow: { status: 'starting', provider: { id: 'nous', name: 'Nous' } as never }
      })
      await vi.advanceTimersByTimeAsync(0)
    })

    expect(requestGateway).not.toHaveBeenCalled()
  })
})

describe('useStatusSnapshot on a signed-out status read', () => {
  it('keeps the last full snapshot when a Webapp read comes back signed out', async () => {
    const full = { active_sessions: 2, auth_required: true, install_id: 'i', version: '1.0.0' }
    vi.mocked(getStatus).mockImplementation(async () => full as never)
    const requestGateway = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester

    const { result } = renderHook(() => useStatusSnapshot('open', requestGateway))
    await flushAsync()
    expect(result.current.statusSnapshot).toEqual(full)

    // An access token expired since the tab's last gated request: the public route answers signed out.
    vi.mocked(getStatus).mockImplementation(async () => ({ auth_required: true, version: '1.0.0' }) as never)
    await act(async () => {
      await vi.advanceTimersByTimeAsync(60_000)
    })
    expect(getStatus).toHaveBeenCalledTimes(2)
    expect(result.current.statusSnapshot).toEqual(full)
  })
})