fix(frontend): reconcile pending questions by directory and improve TTS fallback (#204)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-04-28 11:32:19 -04:00
1 parent 1beb353668
commit 62c8a41e01
10 files changed
+582 -26

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { QuestionRequest } from '@/api/types'
import { EventProvider, useQuestions } from './EventContext'
const mocks = vi.hoisted(() => ({
listRepos: vi.fn(),
listPendingPermissions: vi.fn(),
listPendingQuestions: vi.fn(),
replyToQuestion: vi.fn(),
rejectQuestion: vi.fn(),
subscribeToSSE: vi.fn(),
addSSEDirectory: vi.fn(),
ensureSSEConnected: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
listRepos: mocks.listRepos,
}))
vi.mock('@/api/opencode', () => ({
OpenCodeClient: vi.fn(() => ({
listPendingPermissions: mocks.listPendingPermissions,
listPendingQuestions: mocks.listPendingQuestions,
replyToQuestion: mocks.replyToQuestion,
rejectQuestion: mocks.rejectQuestion,
})),
}))
vi.mock('@/lib/sseManager', () => ({
subscribeToSSE: mocks.subscribeToSSE,
addSSEDirectory: mocks.addSSEDirectory,
ensureSSEConnected: mocks.ensureSSEConnected,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
error: vi.fn(),
info: vi.fn(),
},
}))
const pendingQuestion: QuestionRequest = {
id: 'question-1',
sessionID: 'session-1',
questions: [
{
question: 'Continue?',
header: 'Confirm',
options: [
{
label: 'Yes',
description: 'Continue',
},
],
multiple: false,
},
],
}
const secondPendingQuestion: QuestionRequest = {
id: 'question-2',
sessionID: 'session-2',
questions: [
{
question: 'Deploy?',
header: 'Deploy',
options: [
{
label: 'Yes',
description: 'Deploy changes',
},
],
multiple: false,
},
],
}
function Harness() {
const { current, pendingCount, syncForSession, navigateToCurrent, reject, reply } = useQuestions()
const location = useLocation()
return (
<div>
<div data-testid="count">{pendingCount}</div>
<div data-testid="current">{current?.id ?? 'none'}</div>
<div data-testid="path">{location.pathname}</div>
<button onClick={() => syncForSession('/repo', 'session-1')}>Sync</button>
<button onClick={navigateToCurrent}>Navigate</button>
<button onClick={() => current && reject(current.id)}>Dismiss</button>
<button onClick={() => current && reply(current.id, [['Yes']])}>Reply</button>
</div>
)
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
return ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
</MemoryRouter>
)
}
describe('EventProvider questions', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.listRepos.mockResolvedValue([])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingQuestions.mockResolvedValue([])
mocks.replyToQuestion.mockResolvedValue(undefined)
mocks.rejectQuestion.mockResolvedValue(undefined)
mocks.subscribeToSSE.mockReturnValue(() => {})
mocks.addSSEDirectory.mockReturnValue(() => {})
mocks.ensureSSEConnected.mockResolvedValue(true)
})
it('syncs missed pending questions for a session', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
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('question-1')
})
})
it('clears stale pending questions for a session', async () => {
mocks.listPendingQuestions
.mockResolvedValueOnce([pendingQuestion])
.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 questions for the whole directory', async () => {
mocks.listPendingQuestions
.mockResolvedValueOnce([pendingQuestion, secondPendingQuestion])
.mockResolvedValueOnce([pendingQuestion])
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('question-1')
})
})
it('reconciles stale pending questions after reconnect', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingQuestions
.mockResolvedValueOnce([pendingQuestion])
.mockResolvedValueOnce([])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
const lastSubscribeCall = mocks.subscribeToSSE.mock.calls[mocks.subscribeToSSE.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[1] as (connected: boolean) => void
handleStatusChange(true)
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('0')
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
it('navigates to a synced pending question without session query cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
render(<Harness />, { wrapper: createWrapper() })
await userEvent.click(screen.getByRole('button', { name: 'Sync' }))
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('question-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 question after dismiss succeeds', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
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(screen.getByTestId('count')).toHaveTextContent('0')
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
it('clears a pending question after reply succeeds', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
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(screen.getByTestId('count')).toHaveTextContent('0')
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
})
+87 -16
View File
@@ -13,6 +13,20 @@ import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessi
type PermissionsBySession = Record<string, PermissionRequest[]>
type QuestionsBySession = Record<string, QuestionRequest[]>
function groupQuestionsBySession(questions: QuestionRequest[]): QuestionsBySession {
return questions.reduce<QuestionsBySession>((grouped, question) => {
const existing = grouped[question.sessionID] ?? []
return {
...grouped,
[question.sessionID]: [...existing, question],
}
}, {})
}
function sortQuestionsById(questions: QuestionRequest[]): QuestionRequest[] {
return [...questions].sort((a, b) => a.id.localeCompare(b.id))
}
function optimisticallyErrorToolPart(
queryClient: ReturnType<typeof useQueryClient>,
sessionID: string,
@@ -107,6 +121,7 @@ interface EventContextValue {
getForCallID: (callID: string, sessionID: string) => QuestionRequest | null
hasForSession: (sessionID: string) => boolean
navigateToCurrent: () => void
syncForSession: (directory: string, sessionID: string) => Promise<void>
}
getRepoIdForSession: (sessionID: string) => number | null
getClient: (sessionID: string) => OpenCodeClient | null
@@ -135,6 +150,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
const prevPermissionCountRef = useRef(0)
const initialFetchDoneRef = useRef(false)
const MAX_CACHED_CLIENTS = 50
@@ -157,7 +173,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const currentPermission = allPermissions[0] ?? null
const currentQuestion = allQuestions[0] ?? null
const findSessionInCache = useCallback((sessionID: string): { url: string; directory: string } | null => {
const rememberSessionDirectory = useCallback((sessionID: string, directory?: string) => {
if (!directory) return
sessionDirectoriesRef.current.set(sessionID, directory)
}, [])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
if (remembered) return remembered
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
@@ -166,9 +190,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
const sessionData = query.state.data as { id: string } | undefined
if (sessionData?.id === sessionID) {
const url = key[2] as string
const directory = key[4] as string
if (url && directory) return { url, directory }
if (directory) return directory
}
}
}
@@ -180,9 +203,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
if (!sessionsList) continue
const found = sessionsList.find(s => s.id === sessionID)
if (found) {
const url = key[2] as string
const directory = key[3] as string
if (url && directory) return { url, directory }
if (directory) return directory
}
}
}
@@ -190,13 +212,19 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return null
}, [queryClient])
const findSessionInCache = useCallback((sessionID: string): { url: string; directory: string } | null => {
const directory = findSessionDirectory(sessionID)
if (!directory) return null
return { url: OPENCODE_API_ENDPOINT, directory }
}, [findSessionDirectory])
const getRepoIdForSession = useCallback((sessionID: string): number | null => {
if (!repos) return null
const result = findSessionInCache(sessionID)
if (!result) return null
const repo = repos.find(r => r.fullPath === result.directory)
const directory = findSessionDirectory(sessionID)
if (!directory) return null
const repo = repos.find(r => r.fullPath === directory)
return repo?.id ?? null
}, [repos, findSessionInCache])
}, [repos, findSessionDirectory])
const getClient = useCallback((sessionID: string): OpenCodeClient | null => {
const result = findSessionInCache(sessionID)
@@ -231,6 +259,31 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
removeFromSessionKeyedState(setQuestionsBySession, requestID, sessionID)
}, [])
const reconcileQuestionsForDirectory = useCallback((directory: string, questions: QuestionRequest[]) => {
const grouped = groupQuestionsBySession(questions)
questions.forEach(question => {
rememberSessionDirectory(question.sessionID, directory)
})
setQuestionsBySession(prev => {
const next = { ...prev }
for (const sessionID of Object.keys(prev)) {
if (grouped[sessionID]) continue
if (sessionDirectoriesRef.current.get(sessionID) === directory) {
delete next[sessionID]
}
}
for (const [sessionID, sessionQuestions] of Object.entries(grouped)) {
next[sessionID] = sortQuestionsById(sessionQuestions)
}
return next
})
}, [rememberSessionDirectory])
useEffect(() => {
const permissionCount = allPermissions.length
if (permissionCount > prevPermissionCountRef.current && permissionCount > 0 && !showPermissionDialog) {
@@ -275,7 +328,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const client = getClient(question.sessionID)
if (!client) throw new Error('No client found for session')
await client.replyToQuestion(requestID, answers)
}, [getClient, questionsBySession])
removeQuestion(requestID, question.sessionID)
}, [getClient, questionsBySession, removeQuestion])
const rejectQuestion = useCallback(async (requestID: string) => {
const connected = await ensureSSEConnected()
@@ -293,7 +347,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
await client.rejectQuestion(requestID)
}, [getClient, questionsBySession, queryClient])
removeQuestion(requestID, question.sessionID)
}, [getClient, questionsBySession, queryClient, removeQuestion])
const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => {
const perms = permissionsBySession[sessionID] ?? []
@@ -346,17 +401,29 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
for (const directory of uniqueDirectories) {
try {
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
const pendingQuestions = await client.listPendingQuestions()
if (pendingQuestions && pendingQuestions.length > 0) {
pendingQuestions.forEach(addQuestion)
const pendingPermissions = await client.listPendingPermissions()
if (pendingPermissions && pendingPermissions.length > 0) {
pendingPermissions.forEach(permission => {
rememberSessionDirectory(permission.sessionID, directory)
addPermission(permission)
})
}
const pendingQuestions = await client.listPendingQuestions()
reconcileQuestionsForDirectory(directory, pendingQuestions ?? [])
} catch (error) {
if (import.meta.env.DEV) {
console.warn(`Failed to fetch pending questions for ${directory}:`, error)
}
}
}
}, [repos, addQuestion])
}, [repos, addPermission, rememberSessionDirectory, reconcileQuestionsForDirectory])
const syncQuestionsForSession = useCallback(async (directory: string, sessionID: string) => {
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
const pendingQuestions = await client.listPendingQuestions()
rememberSessionDirectory(sessionID, directory)
reconcileQuestionsForDirectory(directory, pendingQuestions ?? [])
}, [rememberSessionDirectory, reconcileQuestionsForDirectory])
useEffect(() => {
const handleSSEMessage = (data: unknown) => {
@@ -367,6 +434,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
switch (event.type) {
case 'permission.asked':
if ('permission' in event.properties && 'sessionID' in event.properties) {
rememberSessionDirectory(event.properties.sessionID as string, event.directory)
addPermission(event.properties as PermissionRequest)
}
break
@@ -380,6 +448,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
break
case 'question.asked':
if ('questions' in event.properties && 'sessionID' in event.properties && 'id' in event.properties) {
rememberSessionDirectory(event.properties.sessionID as string, event.directory)
addQuestion(event.properties as QuestionRequest)
}
break
@@ -436,7 +505,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange)
return unsubscribe
}, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData, queryClient])
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient])
useEffect(() => {
if (!repos || repos.length === 0) return
@@ -487,6 +556,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
getForCallID: getQuestionForCallID,
hasForSession: hasQuestionsForSession,
navigateToCurrent: navigateToCurrentQuestion,
syncForSession: syncQuestionsForSession,
},
getRepoIdForSession,
getClient,
@@ -509,6 +579,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
getQuestionForCallID,
hasQuestionsForSession,
navigateToCurrentQuestion,
syncQuestionsForSession,
getRepoIdForSession,
getClient,
])