Refactor SSE event handling and consolidate notification contexts

This commit is contained in:
Chris Scott committed 2026-01-12 23:56:50 -05:00
1 parent 9851ec06e0
commit f7fd3176d4
30 files changed
+2226 -988

No files matched your search

+343
View File
@@ -0,0 +1,343 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import { OpenCodeClient } from '@/api/opencode'
import { listRepos } from '@/api/repos'
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent } from '@/api/types'
import { showToast } from '@/lib/toast'
import { subscribeToSSE } from '@/lib/sseManager'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
type PermissionsBySession = Record<string, PermissionRequest[]>
type QuestionsBySession = Record<string, QuestionRequest[]>
interface EventContextValue {
permissions: {
current: PermissionRequest | null
pendingCount: number
respond: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
dismiss: (permissionID: string, sessionID?: string) => void
getForCallID: (callID: string, sessionID: string) => PermissionRequest | null
hasForSession: (sessionID: string) => boolean
showDialog: boolean
setShowDialog: (show: boolean) => void
}
questions: {
current: QuestionRequest | null
pendingCount: number
reply: (requestID: string, answers: string[][]) => Promise<void>
reject: (requestID: string) => Promise<void>
dismiss: (requestID: string, sessionID?: string) => void
getForCallID: (callID: string, sessionID: string) => QuestionRequest | null
hasForSession: (sessionID: string) => boolean
navigateToCurrent: () => void
}
getRepoIdForSession: (sessionID: string) => number | null
getClient: (sessionID: string) => OpenCodeClient | null
}
const EventContext = createContext<EventContextValue | null>(null)
export function EventProvider({ children }: { children: React.ReactNode }) {
const queryClient = useQueryClient()
const navigate = useNavigate()
const location = useLocation()
const [permissionsBySession, setPermissionsBySession] = useState<PermissionsBySession>({})
const [questionsBySession, setQuestionsBySession] = useState<QuestionsBySession>({})
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
const prevPermissionCountRef = useRef(0)
const MAX_CACHED_CLIENTS = 50
useEffect(() => {
const clients = clientsRef.current
return () => {
clients.clear()
}
}, [])
const { data: repos } = useQuery({
queryKey: ['repos'],
queryFn: listRepos,
})
const allPermissions = useMemo(() => Object.values(permissionsBySession).flat(), [permissionsBySession])
const allQuestions = useMemo(() => Object.values(questionsBySession).flat(), [questionsBySession])
const currentPermission = allPermissions[0] ?? null
const currentQuestion = allQuestions[0] ?? null
const getRepoIdForSession = useCallback((sessionID: string): number | null => {
if (!repos) return null
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
for (const query of queries) {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
const sessionData = query.state.data as { id: string } | undefined
if (sessionData?.id === sessionID) {
const directory = key[4] as string | undefined
if (directory) {
const repo = repos.find(r => r.fullPath === directory)
if (repo) return repo.id
}
}
}
}
return null
}, [repos, queryClient])
const getClient = useCallback((sessionID: string): OpenCodeClient | null => {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
for (const query of queries) {
const key = query.queryKey
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 | undefined
if (!url || typeof url !== 'string') continue
const clientKey = `${url}|${directory ?? ''}`
let client = clientsRef.current.get(clientKey)
if (!client) {
if (clientsRef.current.size >= MAX_CACHED_CLIENTS) {
const firstKey = clientsRef.current.keys().next().value
if (firstKey) clientsRef.current.delete(firstKey)
}
client = new OpenCodeClient(url, directory)
clientsRef.current.set(clientKey, client)
}
return client
}
}
}
return null
}, [queryClient])
const addPermission = useCallback((permission: PermissionRequest) => {
addToSessionKeyedState(setPermissionsBySession, permission)
}, [])
const removePermission = useCallback((permissionID: string, sessionID?: string) => {
removeFromSessionKeyedState(setPermissionsBySession, permissionID, sessionID)
}, [])
const addQuestion = useCallback((question: QuestionRequest) => {
addToSessionKeyedState(setQuestionsBySession, question)
}, [])
const removeQuestion = useCallback((requestID: string, sessionID?: string) => {
removeFromSessionKeyedState(setQuestionsBySession, requestID, sessionID)
}, [])
useEffect(() => {
const permissionCount = allPermissions.length
if (permissionCount > prevPermissionCountRef.current && permissionCount > 0 && !showPermissionDialog) {
showToast.info(`${permissionCount} pending permission${permissionCount > 1 ? 's' : ''}`, {
duration: 5000,
action: {
label: 'View',
onClick: () => setShowPermissionDialog(true),
},
})
}
prevPermissionCountRef.current = permissionCount
}, [allPermissions.length, showPermissionDialog])
const respondToPermission = useCallback(async (permissionID: string, sessionID: string, response: PermissionResponse) => {
const client = getClient(sessionID)
if (!client) throw new Error('No client found for session')
await client.respondToPermission(sessionID, permissionID, response)
removePermission(permissionID, sessionID)
}, [getClient, removePermission])
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
if (!question) throw new Error('Question not found')
const client = getClient(question.sessionID)
if (!client) throw new Error('No client found for session')
await client.replyToQuestion(requestID, answers)
removeQuestion(requestID, question.sessionID)
}, [getClient, removeQuestion, questionsBySession])
const rejectQuestion = useCallback(async (requestID: string) => {
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
if (!question) throw new Error('Question not found')
const client = getClient(question.sessionID)
if (!client) throw new Error('No client found for session')
await client.rejectQuestion(requestID)
removeQuestion(requestID, question.sessionID)
}, [getClient, removeQuestion, questionsBySession])
const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => {
const perms = permissionsBySession[sessionID] ?? []
return perms.find(p => {
const metadata = p.metadata as { tool?: { id?: string } } | undefined
return metadata?.tool?.id === callID
}) ?? null
}, [permissionsBySession])
const getQuestionForCallID = useCallback((callID: string, sessionID: string): QuestionRequest | null => {
const questions = questionsBySession[sessionID] ?? []
return questions.find(q => q.tool?.callID === callID) ?? null
}, [questionsBySession])
const hasPermissionsForSession = useCallback((sessionID: string): boolean => {
return (permissionsBySession[sessionID]?.length ?? 0) > 0
}, [permissionsBySession])
const hasQuestionsForSession = useCallback((sessionID: string): boolean => {
return (questionsBySession[sessionID]?.length ?? 0) > 0
}, [questionsBySession])
const navigateToCurrentQuestion = useCallback(() => {
if (!currentQuestion) return
const repoId = getRepoIdForSession(currentQuestion.sessionID)
if (repoId) {
const targetPath = `/repos/${repoId}/sessions/${currentQuestion.sessionID}`
if (location.pathname !== targetPath) {
navigate(targetPath)
}
}
}, [currentQuestion, getRepoIdForSession, navigate, location.pathname])
const fetchInitialPendingData = useCallback(async () => {
if (!repos || repos.length === 0) return
const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))]
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)
}
} catch (error) {
if (import.meta.env.DEV) {
console.warn(`Failed to fetch pending questions for ${directory}:`, error)
}
}
}
}, [repos, addQuestion])
useEffect(() => {
const handleSSEMessage = (data: unknown) => {
if (!data || typeof data !== 'object' || !('type' in data)) return
const event = data as SSEEvent
switch (event.type) {
case 'permission.asked':
if ('permission' in event.properties && 'sessionID' in event.properties) {
addPermission(event.properties as PermissionRequest)
}
break
case 'permission.replied':
if ('requestID' in event.properties && 'sessionID' in event.properties) {
removePermission(
event.properties.requestID as string,
event.properties.sessionID as string
)
}
break
case 'question.asked':
if ('questions' in event.properties && 'sessionID' in event.properties && 'id' in event.properties) {
addQuestion(event.properties as QuestionRequest)
}
break
case 'question.replied':
case 'question.rejected':
if ('requestID' in event.properties && 'sessionID' in event.properties) {
removeQuestion(
event.properties.requestID as string,
event.properties.sessionID as string
)
}
break
}
}
const handleStatusChange = (connected: boolean) => {
if (connected) {
fetchInitialPendingData()
}
}
const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange)
return unsubscribe
}, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData])
const value: EventContextValue = useMemo(() => ({
permissions: {
current: currentPermission,
pendingCount: allPermissions.length,
respond: respondToPermission,
dismiss: removePermission,
getForCallID: getPermissionForCallID,
hasForSession: hasPermissionsForSession,
showDialog: showPermissionDialog,
setShowDialog: setShowPermissionDialog,
},
questions: {
current: currentQuestion,
pendingCount: allQuestions.length,
reply: replyToQuestion,
reject: rejectQuestion,
dismiss: removeQuestion,
getForCallID: getQuestionForCallID,
hasForSession: hasQuestionsForSession,
navigateToCurrent: navigateToCurrentQuestion,
},
getRepoIdForSession,
getClient,
}), [
currentPermission,
allPermissions.length,
respondToPermission,
removePermission,
getPermissionForCallID,
hasPermissionsForSession,
showPermissionDialog,
currentQuestion,
allQuestions.length,
replyToQuestion,
rejectQuestion,
removeQuestion,
getQuestionForCallID,
hasQuestionsForSession,
navigateToCurrentQuestion,
getRepoIdForSession,
getClient,
])
return <EventContext.Provider value={value}>{children}</EventContext.Provider>
}
export function useEventContext() {
const context = useContext(EventContext)
if (!context) {
throw new Error('useEventContext must be used within EventProvider')
}
return context
}
export function usePermissions() {
const { permissions } = useEventContext()
return permissions
}
export function useQuestions() {
const { questions } = useEventContext()
return questions
}
-395
View File
@@ -1,395 +0,0 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
import { OpenCodeClient } from '@/api/opencode'
import { permissionEvents, usePermissionRequests } from '@/hooks/usePermissionRequests'
import type { PermissionRequest, PermissionResponse } from '@/api/types'
import { useQueryClient } from '@tanstack/react-query'
import { showToast } from '@/lib/toast'
type SessionInfo = {
id: string
directory?: string
}
type ActiveRepo = {
url: string
directory?: string
sessions: SessionInfo[]
}
interface PermissionContextValue {
currentPermission: PermissionRequest | null
pendingCount: number
isFromDifferentSession: boolean
respondToPermission: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
dismissPermission: (permissionID: string, sessionID?: string) => void
showDialog: boolean
setShowDialog: (show: boolean) => void
currentSessionId: string | null
getPermissionForCallID: (callID: string, sessionID: string) => PermissionRequest | null
hasPermissionsForSession: (sessionID: string) => boolean
currentRepoDirectory: string | null
getRepoForSession: (sessionID: string) => ActiveRepo | null
}
const PermissionContext = createContext<PermissionContextValue | null>(null)
function useActiveRepos(queryClient: ReturnType<typeof useQueryClient>): ActiveRepo[] {
const [activeRepos, setActiveRepos] = useState<ActiveRepo[]>([])
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const lastProcessedRef = useRef<string[]>([])
useEffect(() => {
const checkRepos = () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
timeoutRef.current = setTimeout(() => {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
const repoMap = new Map<string, { directory?: string, sessionIds: Set<string> }>()
queries.forEach((query) => {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'sessions' && key.length >= 4) {
const url = key[2] as string
const directory = key[3] as string | undefined
if (!url || typeof url !== 'string') return
const repoKey = `${url}|${directory ?? ''}`
if (!repoMap.has(repoKey)) {
repoMap.set(repoKey, { directory, sessionIds: new Set() })
}
const sessionsData = query.state.data as Array<{ id: string }> | undefined
if (sessionsData) {
sessionsData.forEach((session) => {
repoMap.get(repoKey)!.sessionIds.add(session.id)
})
}
} else if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
const url = key[2] as string
const directory = key[4] as string | undefined
const sessionData = query.state.data as { id: string } | undefined
if (!url || typeof url !== 'string') return
const repoKey = `${url}|${directory ?? ''}`
if (!repoMap.has(repoKey)) {
repoMap.set(repoKey, { directory, sessionIds: new Set() })
}
if (sessionData && sessionData.id) {
repoMap.get(repoKey)!.sessionIds.add(sessionData.id)
}
}
})
const repos = Array.from(repoMap.entries())
.filter(([repoKey]) => {
const url = repoKey.split('|')[0]
try {
new URL(url)
return true
} catch {
return false
}
})
.map(([repoKey, { directory, sessionIds }]) => ({
url: repoKey.split('|')[0],
directory,
sessions: Array.from(sessionIds).map((id) => ({ id })),
}))
const currentKeys = repos.map(r => `${r.url}|${r.directory ?? ''}`)
const prevKeys = lastProcessedRef.current
const currentSet = new Set(currentKeys)
const prevSet = new Set(prevKeys)
const hasChanged = currentSet.size !== prevSet.size ||
currentKeys.some(k => !prevSet.has(k))
if (hasChanged) {
setActiveRepos(repos)
lastProcessedRef.current = currentKeys
}
}, 100)
}
checkRepos()
const unsubscribe = queryClient.getQueryCache().subscribe(checkRepos)
return () => {
unsubscribe()
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
}
}, [queryClient])
return activeRepos
}
type SessionRepoInfo = { url: string; directory?: string }
export function PermissionProvider({ children }: { children: React.ReactNode }) {
const [showDialog, setShowDialog] = useState(true)
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null)
const queryClient = useQueryClient()
const activeRepos = useActiveRepos(queryClient)
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
const eventSourceRefs = useRef<Map<string, EventSource>>(new Map())
const prevPendingCountRef = useRef(0)
const sessionRepoMapRef = useRef<Map<string, SessionRepoInfo>>(new Map())
const {
currentPermission,
pendingCount,
isFromDifferentSession,
dismissPermission: dismiss,
getPermissionForCallID,
hasPermissionsForSession,
} = usePermissionRequests()
useEffect(() => {
if (currentPermission?.sessionID) {
setCurrentSessionId(currentPermission.sessionID)
}
}, [currentPermission])
useEffect(() => {
if (pendingCount > prevPendingCountRef.current && pendingCount > 0 && !showDialog) {
showToast.info(`${pendingCount} pending permission${pendingCount > 1 ? 's' : ''}`, {
duration: 5000,
action: {
label: 'View',
onClick: () => setShowDialog(true),
},
})
}
prevPendingCountRef.current = pendingCount
}, [pendingCount, showDialog])
const getClient = useCallback((sessionID: string): OpenCodeClient | null => {
for (const repo of activeRepos) {
if (repo.sessions.some((s) => s.id === sessionID)) {
const clientKey = `${repo.url}|${repo.directory ?? ''}`
let client = clientsRef.current.get(clientKey)
if (!client) {
client = new OpenCodeClient(repo.url, repo.directory)
clientsRef.current.set(clientKey, client)
}
return client
}
}
const repoInfo = sessionRepoMapRef.current.get(sessionID)
if (repoInfo) {
const clientKey = `${repoInfo.url}|${repoInfo.directory ?? ''}`
let client = clientsRef.current.get(clientKey)
if (!client) {
client = new OpenCodeClient(repoInfo.url, repoInfo.directory)
clientsRef.current.set(clientKey, client)
}
return client
}
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
for (const query of queries) {
const key = query.queryKey
if (key[0] === 'opencode' && key.length >= 5 && key[1] === 'session') {
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 | undefined
if (!url || typeof url !== 'string') continue
const clientKey = `${url}|${directory ?? ''}`
let client = clientsRef.current.get(clientKey)
if (!client) {
client = new OpenCodeClient(url, directory)
clientsRef.current.set(clientKey, client)
}
return client
}
}
}
return null
}, [activeRepos, queryClient])
useEffect(() => {
const currentRefs = eventSourceRefs.current
const currentClients = clientsRef.current
const newKeys = new Set(activeRepos.map((r) => `${r.url}|${r.directory ?? ''}`))
const existingKeys = new Set(currentRefs.keys())
existingKeys.forEach((key) => {
if (!newKeys.has(key)) {
const es = currentRefs.get(key)
if (es) {
es.close()
currentRefs.delete(key)
}
if (currentClients.has(key)) {
currentClients.delete(key)
}
}
})
return () => {
currentRefs.forEach((es) => es.close())
}
}, [activeRepos])
useEffect(() => {
const currentRefs = eventSourceRefs.current
activeRepos.forEach((repo) => {
if (!repo.url) return
const repoKey = `${repo.url}|${repo.directory ?? ''}`
const existingES = currentRefs.get(repoKey)
if (existingES) return
let url: URL
try {
url = new URL(repo.url)
} catch {
console.error('Invalid URL for SSE:', repo.url)
return
}
if (url.pathname.endsWith('/')) {
url.pathname += 'stream'
} else {
url.pathname += '/stream'
}
if (repo.directory) {
url.searchParams.set('directory', repo.directory)
}
const es = new EventSource(url.toString())
currentRefs.set(repoKey, es)
es.addEventListener('permission.asked', (e) => {
try {
const event = JSON.parse(e.data)
if ('permission' in event.properties && 'sessionID' in event.properties) {
sessionRepoMapRef.current.set(event.properties.sessionID, {
url: repo.url,
directory: repo.directory,
})
permissionEvents.emit({ type: 'add', permission: event.properties })
}
} catch (err) {
console.error('Failed to parse permission.asked event:', err)
}
})
es.addEventListener('permission.replied', (e) => {
try {
const event = JSON.parse(e.data)
const requestID = event.properties.requestID || event.properties.permissionID
if (requestID && 'sessionID' in event.properties) {
permissionEvents.emit({
type: 'remove',
sessionID: event.properties.sessionID,
permissionID: requestID,
})
}
} catch (err) {
console.error('Failed to parse permission.replied event:', err)
}
})
es.onerror = (err) => {
console.error(`SSE connection error for ${repo.url}:`, err)
setTimeout(() => {
currentRefs.delete(repoKey)
}, 1000)
}
})
return () => {
currentRefs.forEach((es) => es.close())
currentRefs.clear()
}
}, [activeRepos])
const respondToPermission = useCallback(
async (permissionID: string, sessionID: string, response: PermissionResponse) => {
const client = getClient(sessionID)
if (!client) {
throw new Error('No client found for session')
}
await client.respondToPermission(sessionID, permissionID, response)
dismiss(permissionID, sessionID)
},
[getClient, dismiss],
)
const getRepoForSession = useCallback((sessionID: string): ActiveRepo | null => {
for (const repo of activeRepos) {
if (repo.sessions.some((s) => s.id === sessionID)) {
return repo
}
}
return null
}, [activeRepos])
const currentRepoDirectory = useMemo(() => {
if (!currentPermission) return null
const repo = getRepoForSession(currentPermission.sessionID)
return repo?.directory ?? null
}, [currentPermission, getRepoForSession])
const value: PermissionContextValue = useMemo(
() => ({
currentPermission,
pendingCount,
isFromDifferentSession,
respondToPermission,
dismissPermission: dismiss,
showDialog,
setShowDialog,
currentSessionId,
getPermissionForCallID,
hasPermissionsForSession,
currentRepoDirectory,
getRepoForSession,
}),
[
currentPermission,
pendingCount,
isFromDifferentSession,
respondToPermission,
dismiss,
showDialog,
currentSessionId,
getPermissionForCallID,
hasPermissionsForSession,
currentRepoDirectory,
getRepoForSession,
],
)
return <PermissionContext.Provider value={value}>{children}</PermissionContext.Provider>
}
export function usePermissionContext() {
const context = useContext(PermissionContext)
if (!context) {
throw new Error('usePermissionContext must be used within PermissionProvider')
}
return context
}