import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { act, render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useState, type ReactNode } from 'react' import { MemoryRouter, useLocation } from 'react-router-dom' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode' import { FetchError } from '@opencode-manager/shared' import { showToast } from '@/lib/toast' import { useSessionStatus } from '@/stores/sessionStatusStore' import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough' import { EventProvider, useEventContext, useForms, usePermissions, useSSEHealth } from './EventContext' const mocks = vi.hoisted(() => ({ listRepos: vi.fn(), listPendingPermissions: vi.fn(), listPendingForms: vi.fn(), listActiveSessions: vi.fn(), replyPermission: vi.fn(), replyForm: vi.fn(), cancelForm: vi.fn(), subscribeGlobalMonitor: vi.fn(), getHealth: vi.fn(), })) vi.mock('@/api/repos', () => ({ listRepos: mocks.listRepos, })) vi.mock('@/api/opencode', () => ({ listActiveSessions: mocks.listActiveSessions, listPendingPermissions: mocks.listPendingPermissions, listPendingForms: mocks.listPendingForms, replyPermission: mocks.replyPermission, replyForm: mocks.replyForm, cancelForm: mocks.cancelForm, })) vi.mock('@/lib/opencode-event-stream', () => ({ openCodeEventStream: { subscribeGlobalMonitor: mocks.subscribeGlobalMonitor, getHealth: mocks.getHealth, }, })) vi.mock('@/lib/toast', () => ({ showToast: { error: vi.fn(), info: vi.fn(), }, })) const pendingForm: FormInfo = { id: 'form-1', sessionID: 'session-1', title: 'Continue?', fields: [ { key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] }, ], } const secondPendingForm: FormInfo = { id: 'form-2', sessionID: 'session-2', title: 'Deploy?', fields: [ { key: 'q0', title: 'Deploy', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] }, ], } const pendingPermission: PermissionRequest = { id: 'permission-1', sessionID: 'session-1', action: 'shell', resources: ['echo hello'], metadata: {}, } const secondPendingPermission: PermissionRequest = { id: 'permission-2', sessionID: 'session-1', action: 'edit', resources: ['/tmp/test.txt'], metadata: {}, } const sourcedPermission: PermissionRequest = { id: 'permission-3', sessionID: 'session-1', action: 'shell', resources: ['echo hello'], metadata: {}, source: { type: 'tool', messageID: 'msg_1', id: 'call_1' }, } function Harness() { const { current, pendingCount, syncForSession, navigateToCurrent, cancel, reply, getForSession } = useForms() const permissions = usePermissions() const location = useLocation() const [rejection, setRejection] = useState('none') const recordRejection = (action: Promise) => { action.catch((error: unknown) => setRejection(error instanceof FetchError ? error.code ?? 'unknown' : 'unknown')) } return (
{rejection}
{pendingCount}
{current?.id ?? 'none'}
{getForSession('session-1')?.id ?? 'none'}
{getForSession('session-2')?.id ?? 'none'}
{getForSession('session-unknown')?.id ?? 'none'}
{permissions.pendingCount}
{permissions.current?.id ?? 'none'}
{permissions.getForToolCall('call_1', 'msg_1')?.id ?? 'none'}
{permissions.getForToolCall('call_1', 'msg_other')?.id ?? 'none'}
{permissions.getForToolCall('call_other', 'msg_1')?.id ?? 'none'}
{location.pathname}
) } function createTestQueryClient() { return new QueryClient({ defaultOptions: { queries: { retry: false } }, }) } function createDeferred() { let resolve!: (value: T) => void const promise = new Promise((res) => { resolve = res }) return { promise, resolve } } function createWrapper(queryClient = createTestQueryClient()) { return ({ children }: { children: ReactNode }) => ( {children} ) } function CacheResolutionHarness({ sessionID }: { sessionID: string }) { const { getRepoIdForSession } = useEventContext() const repoId = getRepoIdForSession(sessionID) return (
{repoId ?? 'none'}
) } describe('EventProvider permissions and forms', () => { beforeEach(() => { vi.clearAllMocks() mocks.listRepos.mockResolvedValue([]) mocks.listPendingPermissions.mockResolvedValue([]) mocks.listPendingForms.mockResolvedValue([]) mocks.listActiveSessions.mockResolvedValue({}) mocks.replyPermission.mockResolvedValue(undefined) mocks.replyForm.mockResolvedValue(undefined) mocks.cancelForm.mockResolvedValue(undefined) mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false }) useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 }) mocks.subscribeGlobalMonitor.mockReturnValue({ dispose: vi.fn(), updateDirectories: vi.fn(), reconnect: vi.fn(), reportVisibility: vi.fn(), }) }) it('syncs missed pending forms for a session', async () => { mocks.listPendingForms.mockResolvedValue([pendingForm]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') expect(screen.getByTestId('current')).toHaveTextContent('form-1') }) }) it('syncs missed pending permissions for a session', async () => { mocks.listPendingPermissions.mockResolvedValue([pendingPermission]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1') }) }) it('clears stale pending permissions for a session', async () => { mocks.listPendingPermissions .mockResolvedValueOnce([pendingPermission]) .mockResolvedValueOnce([]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('0') expect(screen.getByTestId('permission-current')).toHaveTextContent('none') }) }) it('advances to the remaining permission after rejecting the current one of two in the same session', async () => { mocks.listPendingPermissions.mockResolvedValue([pendingPermission, secondPendingPermission]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('2') expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1') }) await userEvent.click(screen.getByRole('button', { name: 'Reject Permission' })) await waitFor(() => { expect(mocks.replyPermission).toHaveBeenCalledTimes(1) expect(mocks.replyPermission).toHaveBeenCalledWith('session-1', 'permission-1', 'reject', undefined) expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-2') }) }) it('removes a permission the server no longer knows about when replying', async () => { mocks.listPendingPermissions.mockResolvedValue([pendingPermission]) mocks.replyPermission.mockRejectedValue(new FetchError('Permission request not found', 404, 'PermissionNotFoundError')) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => expect(screen.getByTestId('permission-count')).toHaveTextContent('1')) await userEvent.click(screen.getByRole('button', { name: 'Reject Permission' })) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('0') expect(screen.getByTestId('permission-current')).toHaveTextContent('none') }) expect(showToast.info).toHaveBeenCalledWith('Permission request expired') expect(screen.getByTestId('rejection')).toHaveTextContent('none') }) it('keeps a permission and rejects when the reply fails for another reason', async () => { mocks.listPendingPermissions.mockResolvedValue([pendingPermission]) mocks.replyPermission.mockRejectedValue(new FetchError('Session not found', 404, 'SessionNotFoundError')) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => expect(screen.getByTestId('permission-count')).toHaveTextContent('1')) await userEvent.click(screen.getByRole('button', { name: 'Reject Permission' })) await waitFor(() => expect(screen.getByTestId('rejection')).toHaveTextContent('SessionNotFoundError')) expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1') expect(showToast.info).not.toHaveBeenCalled() }) it.each([ ['Reply', 'replyForm'], ['Dismiss', 'cancelForm'], ] as const)('removes a form the server no longer knows about on %s', async (button, mock) => { mocks.listPendingForms.mockResolvedValue([pendingForm]) mocks[mock].mockRejectedValue(new FetchError('Form not found', 404, 'FormNotFoundError')) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => expect(screen.getByTestId('count')).toHaveTextContent('1')) await userEvent.click(screen.getByRole('button', { name: button })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('0') expect(screen.getByTestId('current')).toHaveTextContent('none') }) expect(showToast.info).toHaveBeenCalledWith('Form expired') expect(screen.getByTestId('rejection')).toHaveTextContent('none') }) it.each([ ['Reply', 'replyForm'], ['Dismiss', 'cancelForm'], ] as const)('keeps a form and rejects when %s fails for another reason', async (button, mock) => { mocks.listPendingForms.mockResolvedValue([pendingForm]) mocks[mock].mockRejectedValue(new FetchError('Form already settled', 409, 'FormAlreadySettledError')) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => expect(screen.getByTestId('count')).toHaveTextContent('1')) await userEvent.click(screen.getByRole('button', { name: button })) await waitFor(() => expect(screen.getByTestId('rejection')).toHaveTextContent('FormAlreadySettledError')) expect(screen.getByTestId('count')).toHaveTextContent('1') expect(screen.getByTestId('current')).toHaveTextContent('form-1') expect(showToast.info).not.toHaveBeenCalled() }) it('forwards an optional rejection message to the facade', async () => { mocks.listPendingPermissions.mockResolvedValue([pendingPermission]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' })) await waitFor(() => expect(screen.getByTestId('permission-count')).toHaveTextContent('1')) await userEvent.click(screen.getByRole('button', { name: 'Reject Permission With Reason' })) await waitFor(() => expect(mocks.replyPermission).toHaveBeenCalledWith('session-1', 'permission-1', 'reject', 'not allowed'), ) }) it('clears stale pending forms for a session', async () => { mocks.listPendingForms .mockResolvedValueOnce([pendingForm]) .mockResolvedValueOnce([]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('0') expect(screen.getByTestId('current')).toHaveTextContent('none') }) }) it('reconciles pending forms for the whole directory', async () => { mocks.listPendingForms .mockResolvedValueOnce([pendingForm, secondPendingForm]) .mockResolvedValueOnce([pendingForm]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('2') }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') expect(screen.getByTestId('current')).toHaveTextContent('form-1') }) }) it('resolves pending forms per session independently of the global current', async () => { mocks.listPendingForms.mockResolvedValue([pendingForm, secondPendingForm]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('2') }) expect(screen.getByTestId('current')).toHaveTextContent('form-1') expect(screen.getByTestId('for-session-1')).toHaveTextContent('form-1') expect(screen.getByTestId('for-session-2')).toHaveTextContent('form-2') expect(screen.getByTestId('for-session-unknown')).toHaveTextContent('none') }) it('reconciles stale pending forms after reconnect', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingForms .mockResolvedValueOnce([pendingForm]) .mockResolvedValueOnce([]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void handleStatusChange(true) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('0') expect(screen.getByTestId('current')).toHaveTextContent('none') }) }) it('clears settled pending actions on an upstream resync while the browser stream stays connected', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingPermissions.mockResolvedValue([]) mocks.listPendingForms.mockResolvedValue([]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo') expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo') }) await act(async () => { await Promise.resolve() }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined act(() => { onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' }) onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo' }) }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('count')).toHaveTextContent('1') }) act(() => { onResync?.() }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('0') expect(screen.getByTestId('count')).toHaveTextContent('0') }) }) it('retains genuinely pending actions on an upstream resync', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingPermissions.mockResolvedValue([pendingPermission]) mocks.listPendingForms.mockResolvedValue([pendingForm]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled() }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined act(() => { onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' }) onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo' }) }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('count')).toHaveTextContent('1') }) act(() => { onResync?.() }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('count')).toHaveTextContent('1') }) }) it('reconciles tracked worktree session directories on an upstream resync', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingPermissions.mockResolvedValue([]) mocks.listPendingForms.mockResolvedValue([]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo') expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo') }) await act(async () => { await Promise.resolve() }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined act(() => { onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/worktrees/wt-1' }) }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') }) act(() => { onResync?.() }) await waitFor(() => { expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/worktrees/wt-1') expect(screen.getByTestId('permission-count')).toHaveTextContent('0') }) }) it('navigates to a synced pending form without session query cache', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingForms.mockResolvedValue([pendingForm]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('current')).toHaveTextContent('form-1') }) await userEvent.click(screen.getByRole('button', { name: 'Navigate' })) await waitFor(() => { expect(screen.getByTestId('path')).toHaveTextContent('/repos/123/sessions/session-1') }) }) it('clears a pending form after dismiss succeeds', async () => { mocks.listPendingForms.mockResolvedValue([pendingForm]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') }) await userEvent.click(screen.getByRole('button', { name: 'Dismiss' })) await waitFor(() => { expect(mocks.cancelForm).toHaveBeenCalledWith('session-1', 'form-1') expect(screen.getByTestId('count')).toHaveTextContent('0') expect(screen.getByTestId('current')).toHaveTextContent('none') }) }) it('clears a pending form after reply succeeds', async () => { mocks.listPendingForms.mockResolvedValue([pendingForm]) render(, { wrapper: createWrapper() }) await userEvent.click(screen.getByRole('button', { name: 'Sync' })) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') }) await userEvent.click(screen.getByRole('button', { name: 'Reply' })) await waitFor(() => { expect(mocks.replyForm).toHaveBeenCalledWith('session-1', 'form-1', { q0: 'Yes' }) expect(screen.getByTestId('count')).toHaveTextContent('0') expect(screen.getByTestId('current')).toHaveTextContent('none') }) }) it('adds a pending form received via the global monitor onEvent', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled() }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo', }) }) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') expect(screen.getByTestId('current')).toHaveTextContent('form-1') }) }) it('adds a pending permission received via the global monitor onEvent', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled() }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo', }) }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('1') expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1') }) act(() => { onEvent({ type: 'permission.replied', data: { sessionID: 'session-1', requestID: 'permission-1', reply: 'reject' }, directory: '/repo', }) }) await waitFor(() => { expect(screen.getByTestId('permission-count')).toHaveTextContent('0') }) }) it('resolves a pending permission by its source tool call and message', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled() }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'permission.asked', data: sourcedPermission, directory: '/repo', }) }) await waitFor(() => { expect(screen.getByTestId('permission-tool-call')).toHaveTextContent('permission-3') }) expect(screen.getByTestId('permission-tool-call-other-message')).toHaveTextContent('none') expect(screen.getByTestId('permission-tool-call-other-id')).toHaveTextContent('none') }) it('removes a pending form on a form.cancelled event', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingForms.mockResolvedValue([pendingForm]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('1') }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'form.cancelled', data: { id: 'form-1', sessionID: 'session-1' }, directory: '/repo', }) }) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('0') expect(screen.getByTestId('current')).toHaveTextContent('none') }) }) it('does not invalidate the transcript on form reply or cancel events', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listPendingForms.mockResolvedValue([pendingForm, secondPendingForm]) const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('2') }) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'form.replied', data: { id: 'form-1', sessionID: 'session-1', answer: {} }, directory: '/repo' }) onEvent({ type: 'form.cancelled', data: { id: 'form-2', sessionID: 'session-2' }, directory: '/repo' }) }) await waitFor(() => { expect(screen.getByTestId('count')).toHaveTextContent('0') }) expect(invalidateQueries).not.toHaveBeenCalled() }) it.each([ 'credential.updated', 'credential.switched', 'integration.updated', 'provider.updated', 'model.updated', ])('invalidates provider caches on a location-less %s event', async (type) => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type, data: {} }) }) await waitFor(() => { for (const queryKey of [ ['provider-credentials'], ['provider-auth-methods'], ['opencode', 'providers'], ]) { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey }) } }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers'] }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers-for-execution-model'] }) }) it('collapses a burst of provider events into a single provider invalidation flush', async () => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'credential.updated', data: {} }) onEvent({ type: 'provider.updated', data: {} }) onEvent({ type: 'model.updated', data: {} }) onEvent({ type: 'integration.updated', data: {} }) onEvent({ type: 'credential.switched', data: {} }) onEvent({ type: 'provider.updated', data: {} }) }) await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) }) expect(invalidateQueries).toHaveBeenCalledTimes(3) }) it.each<[string, string[]]>([ ['agent.updated', ['opencode', 'agents']], ['command.updated', ['opencode', 'commands']], ['skill.updated', ['opencode', 'skills']], ])('invalidates the %s cache', async (type, queryKey) => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type, data: {} }) }) await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey }) }) }) it('invalidates the location catalog caches on an upstream resync', async () => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined act(() => { onResync?.() }) await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'commands'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) }) }) it('invalidates the location catalog caches when the browser stream reconnects', async () => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(false) handleStatusChange(true) }) await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'commands'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) }) }) it('invalidates both config caches on config.updated', async () => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'config.updated', data: {} }) }) await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'config'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config'] }) }) }) it('reconciles every tracked directory concurrently on an upstream resync', async () => { mocks.listRepos.mockResolvedValue([ { id: 1, fullPath: '/repo-a' }, { id: 2, fullPath: '/repo-b' }, ]) render(, { wrapper: createWrapper() }) await waitFor(() => { expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-b') }) await act(async () => { await Promise.resolve() }) const pending = new Map void>() mocks.listPendingPermissions.mockImplementation( (directory: string) => new Promise((resolve) => { pending.set(directory, () => resolve([])) }), ) mocks.listPendingPermissions.mockClear() mocks.listPendingForms.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined act(() => { onResync?.() }) expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo-a') expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo-b') expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-a') expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-b') await act(async () => { pending.forEach((resolve) => resolve()) }) }) it('resolves a session directory from the infinite-query session list cache', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const queryClient = createTestQueryClient() queryClient.setQueryData( ['opencode', 'sessions', '/repo', { search: undefined, limit: 25 }], { pages: [{ items: [ { id: 'ses-infinite', projectID: 'proj-1', title: 'From Infinite Query', location: { directory: '/repo' }, time: { created: 1000, updated: 1000 } }, ], cursors: {}, }], pageParams: [undefined], }, ) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { expect(screen.getByTestId('repo-id')).toHaveTextContent('123') }) }) it('resolves a session directory from the single-session cache without a remembered event directory', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const queryClient = createTestQueryClient() queryClient.setQueryData( ['opencode', 'session', 'ses-detail', '/repo'], { id: 'ses-detail', projectID: 'proj-1', title: 'Session Detail', location: { directory: '/repo' }, time: { created: 1000, updated: 1000 }, }, ) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { expect(screen.getByTestId('repo-id')).toHaveTextContent('123') }) }) it('resolves a session in the second directory page of the session list cache', async () => { mocks.listRepos.mockResolvedValue([ { id: 123, fullPath: '/repo-a' }, { id: 456, fullPath: '/repo-b' }, ]) const queryClient = createTestQueryClient() queryClient.setQueryData( ['opencode', 'sessions', '/repo-a|/repo-b', { search: undefined, limit: 25 }], { pages: [ { items: [ { id: 'ses-first', projectID: 'proj-1', title: 'First', location: { directory: '/repo-a' }, time: { created: 1000, updated: 1000 } }, ], cursors: { '/repo-a': 'cursor-a' }, }, { items: [ { id: 'ses-second', projectID: 'proj-1', title: 'Second', location: { directory: '/repo-b' }, time: { created: 2000, updated: 2000 } }, ], cursors: {}, }, ], pageParams: [undefined, { '/repo-a': 'cursor-a' }], }, ) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { expect(screen.getByTestId('repo-id')).toHaveTextContent('456') }) }) it('exposes sseHealth through context', async () => { mocks.getHealth.mockReturnValue({ isConnected: true, isHealthy: true, lastEventAt: Date.now(), isStalled: false }) mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange }) => { onHealthChange({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false }) return { dispose: vi.fn(), updateDirectories: vi.fn(), reconnect: vi.fn(), reportVisibility: vi.fn(), } }) const TestComponent = () => { const { isConnected, isHealthy, isStalled } = useSSEHealth() return (
{String(isConnected)}
{String(isHealthy)}
{String(isStalled)}
) } render(, { wrapper: createWrapper() }) await waitFor(() => { expect(screen.getByTestId('connected')).toHaveTextContent('false') expect(screen.getByTestId('healthy')).toHaveTextContent('false') }) }) it('does not re-render consumers for health notifications that only change lastEventAt', async () => { let onHealthChange: (state: { isConnected: boolean; isHealthy: boolean; lastEventAt: number | null; isStalled: boolean }) => void = () => {} mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange: handler }) => { onHealthChange = handler return { dispose: vi.fn(), updateDirectories: vi.fn(), reconnect: vi.fn(), reportVisibility: vi.fn(), } }) let renderCount = 0 const Probe = () => { renderCount += 1 const { isConnected } = useSSEHealth() return
{String(isConnected)}
} render(, { wrapper: createWrapper() }) await waitFor(() => { expect(screen.getByTestId('probe-connected')).toHaveTextContent('false') }) const initialRenderCount = renderCount act(() => { onHealthChange({ isConnected: true, isHealthy: true, lastEventAt: 1, isStalled: false }) }) await waitFor(() => { expect(screen.getByTestId('probe-connected')).toHaveTextContent('true') }) const afterBooleanChange = renderCount act(() => { onHealthChange({ isConnected: true, isHealthy: true, lastEventAt: 2, isStalled: false }) onHealthChange({ isConnected: true, isHealthy: true, lastEventAt: 3, isStalled: false }) }) expect(afterBooleanChange).toBe(initialRenderCount + 1) expect(renderCount).toBe(afterBooleanChange) }) it('applies a session.status event from the global monitor to the status store', async () => { render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.status', data: { sessionID: 'session-9', status: { type: 'busy' } }, directory: '/repo', }) }) expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' }) }) it('applies execution lifecycle and idle events from the global monitor to the status store', async () => { render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.execution.started', data: { sessionID: 'session-9' }, directory: '/repo' }) }) expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' }) act(() => { onEvent({ type: 'session.execution.succeeded', data: { sessionID: 'session-9' }, directory: '/repo' }) }) expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' }) act(() => { onEvent({ type: 'session.execution.started', data: { sessionID: 'session-9' }, directory: '/repo' }) onEvent({ type: 'session.idle', data: { sessionID: 'session-9' }, directory: '/repo' }) }) expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' }) }) it.each([ ['session.execution.succeeded', { sessionID: 'session-9' }], ['session.execution.failed', { sessionID: 'session-9', error: { message: 'boom' } }], ['session.execution.interrupted', { sessionID: 'session-9', reason: 'user' }], ] as const)('invalidates the change walkthrough query on %s', async (type, data) => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) invalidateQueries.mockClear() const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type, data, directory: '/repo' }) }) await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: changeWalkthroughQueryKey('session-9') }) }) }) it('marks a child session as known from its execution lifecycle events', async () => { render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' }) }) expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true) expect(useSessionStatus.getState().knownSessions.has('child-unknown')).toBe(false) }) it('does not treat a child omitted from a global snapshot as finished', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listActiveSessions.mockResolvedValue({}) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined act(() => { onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' }) }) expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'busy' }) act(() => { onResync?.() }) await waitFor(() => { expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(false) }) }) it('records a failed child outcome and preserves it when the child goes idle', async () => { render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' }) onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' }) }) expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed') expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' }) act(() => { onEvent({ type: 'session.idle', data: { sessionID: 'child-1' }, directory: '/repo' }) }) expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed') }) it('records an interrupted child outcome', async () => { render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.execution.interrupted', data: { sessionID: 'child-1', reason: 'user' }, directory: '/repo' }) }) expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('interrupted') expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' }) }) it('does not turn a failed child into completed across a reconnect snapshot', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listActiveSessions.mockResolvedValue({}) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' }) }) expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed') act(() => { handleStatusChange(true) }) await waitFor(() => { expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed') expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' }) expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true) }) }) it('clears a previous child outcome when a new execution starts', async () => { render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' }) onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' }) }) expect(useSessionStatus.getState().outcomes.get('child-1')).toBeUndefined() }) it('forgets a deleted session status, knowledge, and outcome while keeping the list invalidation', async () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] }) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' }) }) expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed') expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true) act(() => { onEvent({ type: 'session.deleted', data: { sessionID: 'child-1' }, directory: '/repo' }) }) const after = useSessionStatus.getState() expect(after.statuses.has('child-1')).toBe(false) expect(after.knownSessions.has('child-1')).toBe(false) expect(after.outcomes.has('child-1')).toBe(false) await waitFor(() => { expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true) }) }) it('invalidates only the reconciliation of children that moved from busy to unknown during a poll', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listActiveSessions .mockResolvedValueOnce({ 'child-1': { type: 'running' }, 'child-2': { type: 'running' } }) .mockResolvedValue({ 'child-2': { type: 'running' } }) const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') queryClient.setQueryData(['opencode', 'session-reconcile', 'child-1'], { id: 'child-1' }) queryClient.setQueryData(['opencode', 'session-reconcile', 'child-2'], { id: 'child-2' }) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void vi.useFakeTimers() try { act(() => { handleStatusChange(true) }) await act(async () => { await vi.advanceTimersByTimeAsync(0) }) expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true) invalidateQueries.mockClear() await act(async () => { await vi.advanceTimersByTimeAsync(5000) }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile', 'child-1'], }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile', 'child-2'], }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'], }) } finally { vi.useRealTimers() } }) it('reconciles the global active snapshot on reconnect and clears omitted sessions', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listActiveSessions.mockResolvedValue({ 'session-other': { type: 'running' } }) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) act(() => { useSessionStatus.getState().setStatus('session-other', { type: 'busy' }) useSessionStatus.getState().setStatus('session-stale', { type: 'busy' }) }) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(true) }) await waitFor(() => { expect(useSessionStatus.getState().getStatus('session-other')).toEqual({ type: 'busy' }) expect(useSessionStatus.getState().getStatus('session-stale')).toEqual({ type: 'idle' }) }) }) it('ignores a superseded connect snapshot that resolves after a newer reconnect snapshot', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const first = createDeferred>() const second = createDeferred>() mocks.listActiveSessions .mockReturnValueOnce(first.promise) .mockReturnValueOnce(second.promise) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) act(() => { handleStatusChange(false) handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(2) await act(async () => { second.resolve({ 'session-new': { type: 'running' } }) await second.promise }) await waitFor(() => { expect(useSessionStatus.getState().getStatus('session-new')).toEqual({ type: 'busy' }) }) await act(async () => { first.resolve({ 'session-old': { type: 'running' } }) await first.promise }) expect(useSessionStatus.getState().getStatus('session-new')).toEqual({ type: 'busy' }) expect(useSessionStatus.getState().getStatus('session-old')).toEqual({ type: 'idle' }) }) it('does not apply a global snapshot that resolves after unmount', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const deferred = createDeferred>() mocks.listActiveSessions.mockReturnValueOnce(deferred.promise) const { unmount } = render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) unmount() await act(async () => { deferred.resolve({ 'session-late': { type: 'running' } }) await deferred.promise }) expect(useSessionStatus.getState().getStatus('session-late')).toEqual({ type: 'idle' }) }) it('does not let a deferred connect snapshot revert an idle event received while it was in flight', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const deferred = createDeferred>() mocks.listActiveSessions.mockReturnValueOnce(deferred.promise) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) act(() => { onEvent({ type: 'session.status', data: { sessionID: 'session-a', status: { type: 'busy' } }, directory: '/repo' }) onEvent({ type: 'session.idle', data: { sessionID: 'session-a' }, directory: '/repo' }) }) await act(async () => { deferred.resolve({ 'session-a': { type: 'running' } }) await deferred.promise }) expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' }) }) it('does not let a deferred empty connect snapshot erase a session that started while it was in flight', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const deferred = createDeferred>() mocks.listActiveSessions.mockReturnValueOnce(deferred.promise) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) act(() => { onEvent({ type: 'session.execution.started', data: { sessionID: 'session-a' }, directory: '/repo' }) }) await act(async () => { deferred.resolve({}) await deferred.promise }) expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' }) }) it('does not let a deferred connect snapshot resurrect an unknown session that went idle', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) const deferred = createDeferred>() mocks.listActiveSessions.mockReturnValueOnce(deferred.promise) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) act(() => { onEvent({ type: 'session.idle', data: { sessionID: 'session-unseen' }, directory: '/repo' }) }) await act(async () => { deferred.resolve({ 'session-unseen': { type: 'running' } }) await deferred.promise }) expect(useSessionStatus.getState().getStatus('session-unseen')).toEqual({ type: 'idle' }) }) it('debounces a session list invalidation on session lifecycle events', async () => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] }) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.created', data: { sessionID: 'session-9' }, directory: '/repo' }) onEvent({ type: 'session.renamed', data: { sessionID: 'session-9', title: 'Renamed' }, directory: '/repo' }) onEvent({ type: 'session.deleted', data: { sessionID: 'session-9' }, directory: '/repo' }) }) await waitFor(() => { expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true) }) expect(invalidateQueries).toHaveBeenCalledTimes(1) }) it('invalidates the session list when a session is forked', async () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] }) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.forked', data: { sessionID: 'session-fork', parentID: 'session-9' }, directory: '/repo' }) }) await waitFor(() => { expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true) }) }) it('invalidates only the session list for the event directory', async () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'sessions', '/repo-a'], { pages: [], pageParams: [] }) queryClient.setQueryData(['opencode', 'sessions', '/repo-b'], { pages: [], pageParams: [] }) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void act(() => { onEvent({ type: 'session.created', data: { sessionID: 'session-9' }, directory: '/repo-a' }) }) await waitFor(() => { expect(queryClient.getQueryState(['opencode', 'sessions', '/repo-a'])?.isInvalidated).toBe(true) }) expect(queryClient.getQueryState(['opencode', 'sessions', '/repo-b'])?.isInvalidated).toBe(false) }) it('does not invalidate session lists on session.usage.updated', async () => { const queryClient = createTestQueryClient() const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] }) render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void invalidateQueries.mockClear() act(() => { onEvent({ type: 'session.usage.updated', data: { sessionID: 'session-9', cost: 0, tokens: {} }, directory: '/repo' }) }) await act(async () => { await new Promise((resolve) => setTimeout(resolve, 300)) }) expect(invalidateQueries).not.toHaveBeenCalled() expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(false) }) it('fetches the active session snapshot on connect and polls every 5 seconds while connected', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listActiveSessions.mockResolvedValue({}) render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void vi.useFakeTimers() try { act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) await act(async () => { await vi.advanceTimersByTimeAsync(5000) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(2) await act(async () => { await vi.advanceTimersByTimeAsync(5000) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(3) act(() => { handleStatusChange(false) }) await act(async () => { await vi.advanceTimersByTimeAsync(15000) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(3) } finally { vi.useRealTimers() } }) it('stops polling the active session snapshot after unmount', async () => { mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }]) mocks.listActiveSessions.mockResolvedValue({}) const { unmount } = render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void vi.useFakeTimers() try { act(() => { handleStatusChange(true) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) unmount() await act(async () => { await vi.advanceTimersByTimeAsync(15000) }) expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() } }) })