From a55d9b368e8edd41e109b98533ffcd20fdcdec09 Mon Sep 17 00:00:00 2001 From: Chris Scott <> Date: Mon, 27 Apr 2026 23:18:58 +0000 Subject: [PATCH] fix(frontend): refresh active session after SSE reconnect Refetch the active session and messages when the SSE stream reconnects so missed updates appear without navigating away. --- frontend/src/hooks/useSSE.test.tsx | 128 +++++++++++++++++++++++++++++ frontend/src/hooks/useSSE.ts | 15 +++- 2 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 frontend/src/hooks/useSSE.test.tsx diff --git a/frontend/src/hooks/useSSE.test.tsx b/frontend/src/hooks/useSSE.test.tsx new file mode 100644 index 00000000..ec184383 --- /dev/null +++ b/frontend/src/hooks/useSSE.test.tsx @@ -0,0 +1,128 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useSSE } from './useSSE' + +const mocks = vi.hoisted(() => ({ + getSessionStatuses: vi.fn(), +})) + +vi.mock('@/api/opencode', () => ({ + OpenCodeClient: vi.fn(() => ({ + getSessionStatuses: mocks.getSessionStatuses, + })), +})) + +vi.mock('@/api/settings', () => ({ + settingsApi: { + reloadOpenCodeConfig: vi.fn(), + }, +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + dismiss: vi.fn(), + error: vi.fn(), + info: vi.fn(), + loading: vi.fn(), + success: vi.fn(), + }, +})) + +class MockEventSource { + static instances: MockEventSource[] = [] + + onopen: (() => void) | null = null + onerror: (() => void) | null = null + onmessage: ((event: MessageEvent) => void) | null = null + private listeners = new Map void>>() + + constructor() { + MockEventSource.instances.push(this) + } + + addEventListener(type: string, listener: (event: MessageEvent) => void) { + const listeners = this.listeners.get(type) ?? [] + listeners.push(listener) + this.listeners.set(type, listeners) + } + + close() {} + + emit(type: string, data: unknown) { + const event = { data: JSON.stringify(data) } as MessageEvent + this.listeners.get(type)?.forEach((listener) => listener(event)) + } +} + +describe('useSSE', () => { + const originalEventSource = globalThis.EventSource + const originalFetch = globalThis.fetch + + beforeEach(() => { + vi.clearAllMocks() + MockEventSource.instances = [] + mocks.getSessionStatuses.mockResolvedValue({}) + globalThis.EventSource = MockEventSource as unknown as typeof EventSource + globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response)) + }) + + afterEach(() => { + globalThis.EventSource = originalEventSource + globalThis.fetch = originalFetch + }) + + it('invalidates active session data after reconnecting', async () => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries') + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + + const { result, unmount } = renderHook( + () => useSSE('http://localhost:5551', '/repo', 'session-1'), + { wrapper } + ) + + await waitFor(() => expect(MockEventSource.instances).toHaveLength(1)) + + act(() => { + MockEventSource.instances[0].emit('connected', { clientId: 'client-1' }) + }) + + await waitFor(() => expect(result.current.isConnected).toBe(true)) + invalidateQueries.mockClear() + + act(() => { + MockEventSource.instances[0].onerror?.() + }) + + await waitFor(() => expect(result.current.isConnected).toBe(false)) + + act(() => { + window.dispatchEvent(new Event('focus')) + }) + + await waitFor(() => expect(MockEventSource.instances).toHaveLength(2)) + + act(() => { + MockEventSource.instances[1].emit('connected', { clientId: 'client-2' }) + }) + + await waitFor(() => { + expect(invalidateQueries).toHaveBeenCalledWith({ + queryKey: ['opencode', 'session', 'http://localhost:5551', 'session-1', '/repo'], + }) + expect(invalidateQueries).toHaveBeenCalledWith({ + queryKey: ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], + }) + }) + + unmount() + }) +}) diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 609b70f3..5a71bb58 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -329,6 +329,18 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } }, [client, setSessionStatus]) + const syncCurrentSession = useCallback(() => { + const sessionId = sessionIdRef.current + if (!sessionId || !opcodeUrl) return + + queryClient.invalidateQueries({ + queryKey: ['opencode', 'session', opcodeUrl, sessionId, directory], + }) + queryClient.invalidateQueries({ + queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory], + }) + }, [queryClient, opcodeUrl, directory]) + useEffect(() => { mountedRef.current = true @@ -351,6 +363,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, if (connected) { setError(null) fetchInitialData() + syncCurrentSession() sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current) } else { setError('Connection lost. Reconnecting...') @@ -381,7 +394,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, unsubscribe() directoryCleanup?.() } - }, [opcodeUrl, directory, handleSSEEvent, fetchInitialData]) + }, [opcodeUrl, directory, handleSSEEvent, fetchInitialData, syncCurrentSession]) useEffect(() => { if (isConnected && document.visibilityState === 'visible') {