Files
opencode-manager/frontend/src/contexts/EventContext.test.tsx
T
Chris Scott 9c32ba2038 fix(models): reload the model catalog on reconnect and broadcast its events
Model pickers without a location, such as the goal auditor and walkthrough model settings, could stay stuck on an empty model list. OpenCode's model and provider catalog events were only delivered to clients subscribed to the originating directory, and the provider catalog was not reloaded on a browser stream reconnect or upstream resync, so a list cached empty while OpenCode was loading or restarting never refreshed.

Route model.updated, provider.updated and integration.updated through the resolved-event broadcast like the command, agent and skill catalogs, and reload the provider catalog on reconnect and resync alongside them.
2026-10-09 11:43:48 -04:00

1737 lines
65 KiB
TypeScript

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<void>) => {
action.catch((error: unknown) => setRejection(error instanceof FetchError ? error.code ?? 'unknown' : 'unknown'))
}
return (
<div>
<div data-testid="rejection">{rejection}</div>
<div data-testid="count">{pendingCount}</div>
<div data-testid="current">{current?.id ?? 'none'}</div>
<div data-testid="for-session-1">{getForSession('session-1')?.id ?? 'none'}</div>
<div data-testid="for-session-2">{getForSession('session-2')?.id ?? 'none'}</div>
<div data-testid="for-session-unknown">{getForSession('session-unknown')?.id ?? 'none'}</div>
<div data-testid="permission-count">{permissions.pendingCount}</div>
<div data-testid="permission-current">{permissions.current?.id ?? 'none'}</div>
<div data-testid="permission-tool-call">{permissions.getForToolCall('call_1', 'msg_1')?.id ?? 'none'}</div>
<div data-testid="permission-tool-call-other-message">
{permissions.getForToolCall('call_1', 'msg_other')?.id ?? 'none'}
</div>
<div data-testid="permission-tool-call-other-id">
{permissions.getForToolCall('call_other', 'msg_1')?.id ?? 'none'}
</div>
<div data-testid="path">{location.pathname}</div>
<button onClick={() => syncForSession('/repo', 'session-1')}>Sync</button>
<button onClick={() => permissions.syncForSession('/repo', 'session-1')}>Sync Permissions</button>
<button onClick={navigateToCurrent}>Navigate</button>
<button onClick={() => current && recordRejection(cancel(current.id))}>Dismiss</button>
<button onClick={() => current && recordRejection(reply(current.id, { q0: 'Yes' }))}>Reply</button>
<button onClick={() => permissions.current && recordRejection(permissions.respond(permissions.current.id, permissions.current.sessionID, 'reject'))}>Reject Permission</button>
<button onClick={() => permissions.current && permissions.respond(permissions.current.id, permissions.current.sessionID, 'reject', 'not allowed')}>Reject Permission With Reason</button>
</div>
)
}
function createTestQueryClient() {
return new QueryClient({
defaultOptions: { queries: { retry: false } },
})
}
function createDeferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((res) => {
resolve = res
})
return { promise, resolve }
}
function createWrapper(queryClient = createTestQueryClient()) {
return ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
</MemoryRouter>
)
}
function CacheResolutionHarness({ sessionID }: { sessionID: string }) {
const { getRepoIdForSession } = useEventContext()
const repoId = getRepoIdForSession(sessionID)
return (
<div>
<div data-testid="repo-id">{repoId ?? 'none'}</div>
</div>
)
}
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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-b')
})
await act(async () => {
await Promise.resolve()
})
const pending = new Map<string, () => 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(<CacheResolutionHarness sessionID="ses-infinite" />, { 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(<CacheResolutionHarness sessionID="ses-detail" />, { 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(<CacheResolutionHarness sessionID="ses-second" />, { 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 (
<div>
<div data-testid="connected">{String(isConnected)}</div>
<div data-testid="healthy">{String(isHealthy)}</div>
<div data-testid="stalled">{String(isStalled)}</div>
</div>
)
}
render(<TestComponent />, { 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 <div data-testid="probe-connected">{String(isConnected)}</div>
}
render(<Probe />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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<Record<string, unknown>>()
const second = createDeferred<Record<string, unknown>>()
mocks.listActiveSessions
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise)
render(<Harness />, { 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<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
const { unmount } = render(<Harness />, { 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<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
render(<Harness />, { 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<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
render(<Harness />, { 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<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
render(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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(<Harness />, { 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()
}
})
})