mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)
This commit is contained in:
1 parent
3cc24288a6
commit
c3d6549f01
133 files changed
+7284
-6293
No files matched your search
@@ -1,11 +1,11 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { act, 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 { PermissionRequest, QuestionRequest } from '@/api/types'
|
||||
import { EventProvider, usePermissions, useQuestions } from './EventContext'
|
||||
import { EventProvider, usePermissions, useQuestions, useSSEHealth } from './EventContext'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listRepos: vi.fn(),
|
||||
@@ -13,9 +13,8 @@ const mocks = vi.hoisted(() => ({
|
||||
listPendingQuestions: vi.fn(),
|
||||
replyToQuestion: vi.fn(),
|
||||
rejectQuestion: vi.fn(),
|
||||
subscribeToSSE: vi.fn(),
|
||||
addSSEDirectory: vi.fn(),
|
||||
ensureSSEConnected: vi.fn(),
|
||||
subscribeGlobalMonitor: vi.fn(),
|
||||
getHealth: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
@@ -31,10 +30,11 @@ vi.mock('@/api/opencode', () => ({
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sseManager', () => ({
|
||||
subscribeToSSE: mocks.subscribeToSSE,
|
||||
addSSEDirectory: mocks.addSSEDirectory,
|
||||
ensureSSEConnected: mocks.ensureSSEConnected,
|
||||
vi.mock('@/lib/opencode-event-stream', () => ({
|
||||
openCodeEventStream: {
|
||||
subscribeGlobalMonitor: mocks.subscribeGlobalMonitor,
|
||||
getHealth: mocks.getHealth,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
@@ -140,9 +140,13 @@ describe('EventProvider questions', () => {
|
||||
mocks.listPendingQuestions.mockResolvedValue([])
|
||||
mocks.replyToQuestion.mockResolvedValue(undefined)
|
||||
mocks.rejectQuestion.mockResolvedValue(undefined)
|
||||
mocks.subscribeToSSE.mockReturnValue(() => {})
|
||||
mocks.addSSEDirectory.mockReturnValue(() => {})
|
||||
mocks.ensureSSEConnected.mockResolvedValue(true)
|
||||
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
|
||||
mocks.subscribeGlobalMonitor.mockReturnValue({
|
||||
dispose: vi.fn(),
|
||||
updateDirectories: vi.fn(),
|
||||
reconnect: vi.fn(),
|
||||
reportVisibility: vi.fn(),
|
||||
})
|
||||
})
|
||||
|
||||
it('syncs missed pending questions for a session', async () => {
|
||||
@@ -247,8 +251,8 @@ describe('EventProvider questions', () => {
|
||||
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
|
||||
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(() => {
|
||||
@@ -313,4 +317,63 @@ describe('EventProvider questions', () => {
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('none')
|
||||
})
|
||||
})
|
||||
|
||||
it('adds a pending question 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: 'question.asked',
|
||||
properties: pendingQuestion,
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1')
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('question-1')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
|
||||
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')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@ import { OpenCodeClient } from '@/api/opencode'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { subscribeToSSE, addSSEDirectory, ensureSSEConnected } from '@/lib/sseManager'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
|
||||
@@ -149,6 +149,7 @@ interface EventContextValue {
|
||||
navigateToCurrent: () => void
|
||||
syncForSession: (directory: string, sessionID: string) => Promise<void>
|
||||
}
|
||||
sseHealth: EventStreamHealthState
|
||||
getRepoIdForSession: (sessionID: string) => number | null
|
||||
getClient: (sessionID: string) => OpenCodeClient | null
|
||||
}
|
||||
@@ -160,6 +161,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
|
||||
const [sseHealth, setSseHealth] = useState<EventStreamHealthState>(() => openCodeEventStream.getHealth())
|
||||
|
||||
const respondToSSHHostKey = useCallback(async (requestId: string, approved: boolean) => {
|
||||
try {
|
||||
@@ -179,6 +181,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
|
||||
const prevPermissionCountRef = useRef(0)
|
||||
const initialFetchDoneRef = useRef(false)
|
||||
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
|
||||
const reposRef = useRef<typeof repos>(null)
|
||||
const MAX_CACHED_CLIENTS = 50
|
||||
|
||||
useEffect(() => {
|
||||
@@ -320,11 +324,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [allPermissions.length, showPermissionDialog])
|
||||
|
||||
const respondToPermission = useCallback(async (permissionID: string, sessionID: string, response: PermissionResponse) => {
|
||||
const connected = await ensureSSEConnected()
|
||||
if (!connected) {
|
||||
showToast.error('Unable to connect. Please try again.')
|
||||
throw new Error('SSE connection failed')
|
||||
}
|
||||
const client = getClient(sessionID)
|
||||
if (!client) throw new Error('No client found for session')
|
||||
|
||||
@@ -340,11 +339,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [getClient, permissionsBySession, queryClient, removePermission])
|
||||
|
||||
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
|
||||
const connected = await ensureSSEConnected()
|
||||
if (!connected) {
|
||||
showToast.error('Unable to connect. Please try again.')
|
||||
throw new Error('SSE connection failed')
|
||||
}
|
||||
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
|
||||
if (!question) throw new Error('Question not found')
|
||||
const client = getClient(question.sessionID)
|
||||
@@ -354,11 +348,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [getClient, questionsBySession, removeQuestion])
|
||||
|
||||
const rejectQuestion = useCallback(async (requestID: string) => {
|
||||
const connected = await ensureSSEConnected()
|
||||
if (!connected) {
|
||||
showToast.error('Unable to connect. Please try again.')
|
||||
throw new Error('SSE connection failed')
|
||||
}
|
||||
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
|
||||
if (!question) throw new Error('Question not found')
|
||||
const client = getClient(question.sessionID)
|
||||
@@ -416,9 +405,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [currentPermission, getRepoIdForSession, navigate])
|
||||
|
||||
const fetchInitialPendingData = useCallback(async () => {
|
||||
if (!repos || repos.length === 0) return
|
||||
const reposToUse = reposRef.current
|
||||
if (!reposToUse || reposToUse.length === 0) return
|
||||
|
||||
const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))]
|
||||
const uniqueDirectories = [...new Set(reposToUse.map(r => r.fullPath))]
|
||||
|
||||
for (const directory of uniqueDirectories) {
|
||||
try {
|
||||
@@ -433,7 +423,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [repos, reconcilePermissionsForDirectory, reconcileQuestionsForDirectory])
|
||||
}, [reconcilePermissionsForDirectory, reconcileQuestionsForDirectory])
|
||||
|
||||
const syncPermissionsForSession = useCallback(async (directory: string, sessionID: string) => {
|
||||
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
|
||||
@@ -527,24 +517,27 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange)
|
||||
return unsubscribe
|
||||
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient])
|
||||
const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))]
|
||||
const subscription = openCodeEventStream.subscribeGlobalMonitor({
|
||||
directories: initialDirectories,
|
||||
onEvent: handleSSEMessage,
|
||||
onStatusChange: handleStatusChange,
|
||||
onHealthChange: setSseHealth,
|
||||
})
|
||||
subscriptionRef.current = subscription
|
||||
|
||||
return () => {
|
||||
subscription.dispose()
|
||||
subscriptionRef.current = null
|
||||
}
|
||||
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient, setSseHealth])
|
||||
|
||||
useEffect(() => {
|
||||
if (!repos || repos.length === 0) return
|
||||
|
||||
const cleanupFns: (() => void)[] = []
|
||||
const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))]
|
||||
|
||||
uniqueDirectories.forEach(directory => {
|
||||
const cleanup = addSSEDirectory(directory)
|
||||
cleanupFns.push(cleanup)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cleanupFns.forEach(fn => fn())
|
||||
}
|
||||
reposRef.current = repos
|
||||
const sub = subscriptionRef.current
|
||||
if (!sub) return
|
||||
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
|
||||
sub.updateDirectories(directories)
|
||||
}, [repos])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -583,6 +576,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
navigateToCurrent: navigateToCurrentQuestion,
|
||||
syncForSession: syncQuestionsForSession,
|
||||
},
|
||||
sseHealth,
|
||||
getRepoIdForSession,
|
||||
getClient,
|
||||
}), [
|
||||
@@ -606,6 +600,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
hasQuestionsForSession,
|
||||
navigateToCurrentQuestion,
|
||||
syncQuestionsForSession,
|
||||
sseHealth,
|
||||
getRepoIdForSession,
|
||||
getClient,
|
||||
])
|
||||
@@ -635,3 +630,7 @@ export function usePendingAlerts(): boolean {
|
||||
const { permissions, questions } = useEventContext()
|
||||
return permissions.pendingCount + questions.pendingCount > 0
|
||||
}
|
||||
|
||||
export function useSSEHealth(): EventStreamHealthState {
|
||||
return useEventContext().sseHealth
|
||||
}
|
||||
Reference in new issue
Block a user