mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
refactor sse directory management with reference counting and improve message invalidation
This commit is contained in:
1 parent
504ad64b58
commit
910f18f2aa
3 files changed
+76
-45
No files matched your search
@@ -6,7 +6,7 @@ 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 { subscribeToSSE, addSSEDirectory } from '@/lib/sseManager'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
|
||||
@@ -51,6 +51,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
|
||||
const prevPermissionCountRef = useRef(0)
|
||||
const initialFetchDoneRef = useRef(false)
|
||||
const MAX_CACHED_CLIENTS = 50
|
||||
|
||||
useEffect(() => {
|
||||
@@ -259,10 +260,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
case 'question.replied':
|
||||
case 'question.rejected':
|
||||
if ('requestID' in event.properties && 'sessionID' in event.properties) {
|
||||
const sessionID = event.properties.sessionID as string
|
||||
removeQuestion(
|
||||
event.properties.requestID as string,
|
||||
event.properties.sessionID as string
|
||||
sessionID
|
||||
)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages'],
|
||||
predicate: (query) => query.queryKey.includes(sessionID)
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -270,13 +276,38 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const handleStatusChange = (connected: boolean) => {
|
||||
if (connected) {
|
||||
initialFetchDoneRef.current = false
|
||||
fetchInitialPendingData()
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange)
|
||||
return unsubscribe
|
||||
}, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData])
|
||||
}, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData, queryClient])
|
||||
|
||||
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())
|
||||
}
|
||||
}, [repos])
|
||||
|
||||
useEffect(() => {
|
||||
if (!repos || repos.length === 0) return
|
||||
if (initialFetchDoneRef.current) return
|
||||
|
||||
initialFetchDoneRef.current = true
|
||||
fetchInitialPendingData()
|
||||
}, [repos, fetchInitialPendingData])
|
||||
|
||||
const value: EventContextValue = useMemo(() => ({
|
||||
permissions: {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { showToast } from '@/lib/toast'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
import { subscribeToSSE, reconnectSSE, addSSEDirectory, removeSSEDirectory } from '@/lib/sseManager'
|
||||
import { subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager'
|
||||
import { parseOpenCodeError } from '@/lib/opencode-errors'
|
||||
|
||||
const handleRestartServer = async () => {
|
||||
@@ -309,6 +309,16 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
break
|
||||
}
|
||||
|
||||
case 'question.replied':
|
||||
case 'question.rejected': {
|
||||
if (!('sessionID' in event.properties)) break
|
||||
const { sessionID } = event.properties
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages', opcodeUrl, sessionID, directory]
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -358,9 +368,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
}
|
||||
}
|
||||
|
||||
if (directory) {
|
||||
addSSEDirectory(directory)
|
||||
}
|
||||
const directoryCleanup = directory ? addSSEDirectory(directory) : undefined
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleMessage, handleStatusChange)
|
||||
|
||||
@@ -376,9 +384,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
window.removeEventListener('focus', handleReconnect)
|
||||
window.removeEventListener('online', handleReconnect)
|
||||
unsubscribe()
|
||||
if (directory) {
|
||||
removeSSEDirectory(directory)
|
||||
}
|
||||
directoryCleanup?.()
|
||||
}
|
||||
}, [opcodeUrl, directory, handleSSEEvent, fetchInitialData])
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ class SSEManager {
|
||||
private static instance: SSEManager
|
||||
private eventSource: EventSource | null = null
|
||||
private subscribers: Map<string, SSESubscriber> = new Map()
|
||||
private directories: Set<string> = new Set()
|
||||
private directoryRefCounts: Map<string, number> = new Map()
|
||||
private pendingDirectories: Set<string> = new Set()
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private reconnectDelay: number = RECONNECT_DELAY_MS
|
||||
@@ -65,18 +65,17 @@ class SSEManager {
|
||||
}
|
||||
|
||||
addDirectory(directory: string): () => void {
|
||||
if (this.directories.has(directory)) {
|
||||
return () => this.cleanupDirectory(directory)
|
||||
}
|
||||
const currentCount = this.directoryRefCounts.get(directory) ?? 0
|
||||
this.directoryRefCounts.set(directory, currentCount + 1)
|
||||
|
||||
this.directories.add(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
this.subscribeToDirectory(directory)
|
||||
} else {
|
||||
this.pendingDirectories.add(directory)
|
||||
if (!this.eventSource) {
|
||||
this.reconnect()
|
||||
if (currentCount === 0) {
|
||||
if (this.clientId && this.isConnected) {
|
||||
this.subscribeToDirectory(directory)
|
||||
} else {
|
||||
this.pendingDirectories.add(directory)
|
||||
if (!this.eventSource) {
|
||||
this.reconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,15 +83,20 @@ class SSEManager {
|
||||
}
|
||||
|
||||
private cleanupDirectory(directory: string): void {
|
||||
this.directories.delete(directory)
|
||||
this.pendingDirectories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
const currentCount = this.directoryRefCounts.get(directory) ?? 0
|
||||
if (currentCount <= 1) {
|
||||
this.directoryRefCounts.delete(directory)
|
||||
this.pendingDirectories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
}
|
||||
} else {
|
||||
this.directoryRefCounts.set(directory, currentCount - 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,27 +137,17 @@ class SSEManager {
|
||||
}
|
||||
|
||||
removeDirectory(directory: string): void {
|
||||
if (!this.directories.has(directory)) return
|
||||
|
||||
this.directories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
}
|
||||
this.cleanupDirectory(directory)
|
||||
}
|
||||
|
||||
getDirectories(): string[] {
|
||||
return Array.from(this.directories)
|
||||
return Array.from(this.directoryRefCounts.keys())
|
||||
}
|
||||
|
||||
private buildUrl(): string {
|
||||
const url = new URL('/api/sse/stream', window.location.origin)
|
||||
if (this.directories.size > 0) {
|
||||
url.searchParams.set('directories', Array.from(this.directories).join(','))
|
||||
if (this.directoryRefCounts.size > 0) {
|
||||
url.searchParams.set('directories', Array.from(this.directoryRefCounts.keys()).join(','))
|
||||
}
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user