diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index 157b50cd..bd5deea8 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -525,6 +525,9 @@ describe('EventProvider permissions and forms', () => { }) it('reconciles a remembered remote directory on reconnect', async () => { + mocks.servers = [{ id: 'srv_remote', enabled: true }] + mocks.serversLoaded = true + render(, { wrapper: createWrapper() }) await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) @@ -3081,4 +3084,119 @@ describe('EventProvider permissions and forms', () => { await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) expect(mocks.listProjects).not.toHaveBeenCalled() }) + + it('drops pending forms of a remote server that becomes unreachable', async () => { + render(, { 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 + const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void + + act(() => { + onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/srv/app', serverId: 'srv_remote' }) + }) + + await waitFor(() => expect(screen.getByTestId('count')).toHaveTextContent('1')) + + mocks.listPendingForms.mockRejectedValue(new FetchError('Bad gateway', 502)) + + await act(async () => { + onDirectoriesSubscribed(['srv_remote|/srv/app']) + }) + + await waitFor(() => { + expect(screen.getByTestId('count')).toHaveTextContent('0') + expect(screen.getByTestId('current')).toHaveTextContent('none') + }) + }) + + it('drops a pending remote form whose session no longer exists on reconnect', async () => { + mocks.servers = [{ id: 'srv_remote', enabled: true }] + mocks.getSession.mockRejectedValue(new FetchError('Session not found', 404)) + + render(, { 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 + const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void + + act(() => { + useSessionStatus.getState().setSessionParent('session-1', null) + onEvent({ type: 'form.created', data: { form: pendingForm }, serverId: 'srv_remote' }) + }) + + await waitFor(() => expect(screen.getByTestId('count')).toHaveTextContent('1')) + + act(() => { + handleStatusChange(true) + }) + + await waitFor(() => { + expect(mocks.getSession).toHaveBeenCalledWith('session-1', 'srv_remote') + expect(screen.getByTestId('count')).toHaveTextContent('0') + expect(screen.getByTestId('current')).toHaveTextContent('none') + }) + }) + + it('resolves an unknown remote session directory on reconnect', async () => { + mocks.servers = [{ id: 'srv_remote', enabled: true }] + mocks.getSession.mockImplementation((sessionID: string) => + sessionID === 'session-1' + ? Promise.resolve({ id: 'session-1', location: { directory: '/srv/resolved' } }) + : Promise.reject(new FetchError('Session not found', 404)), + ) + + render(, { 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 + const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void + + act(() => { + useSessionStatus.getState().setSessionParent('session-1', null) + onEvent({ type: 'form.created', data: { form: pendingForm }, serverId: 'srv_remote' }) + }) + + await waitFor(() => expect(screen.getByTestId('count')).toHaveTextContent('1')) + expect(useSessionStatus.getState().directories.has('session-1')).toBe(false) + + act(() => { + handleStatusChange(true) + }) + + await waitFor(() => { + expect(mocks.listPendingForms).toHaveBeenCalledWith('/srv/resolved', 'srv_remote') + expect(useSessionStatus.getState().directories.get('session-1')).toBe('srv_remote|/srv/resolved') + }) + }) + + it('reconciles pending actions for a remote server enabled after the browser stream connects', async () => { + const { rerender } = render(, { wrapper: createWrapper() }) + + await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()) + + const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1] + const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void + + act(() => { + handleStatusChange(true) + }) + + act(() => { + useSessionStatus.getState().setSessionDirectory('remote-session', 'srv_remote|/remote/repo') + }) + + mocks.servers = [{ id: 'srv_remote', enabled: true }] + rerender() + + await waitFor(() => { + expect(mocks.listPendingForms).toHaveBeenCalledWith('/remote/repo', 'srv_remote') + }) + }) }) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 2173eeb0..023db05a 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -166,15 +166,19 @@ function withoutSessionKey(bySession: Record, sessionID: string) return next } -function withoutItemsFromUnavailableServers( +/** + * Drops every item matched by `shouldRemove` and deletes a session key left empty. Returns the + * input record itself when no item matched. + */ +function withoutMatchingItems( bySession: Record, - isServerEnabled: (serverId: string) => boolean, + shouldRemove: (item: T) => boolean, ): Record { let changed = false const next: Record = {} for (const [sessionID, items] of Object.entries(bySession)) { - const kept = items.filter((item) => isLocalOpenCodeServer(item.serverId) || isServerEnabled(item.serverId)) + const kept = items.filter((item) => !shouldRemove(item)) if (kept.length === items.length) { next[sessionID] = items continue @@ -186,6 +190,15 @@ function withoutItemsFromUnavailableServers Promise @@ -340,7 +353,17 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const [formsBySession, setFormsBySession] = useState({}) const [showPermissionDialog, setShowPermissionDialog] = useState(true) + const prunePendingActions = useCallback( + (shouldRemove: (item: { sessionID: string; serverId: string }) => boolean) => { + setPermissionsBySession((prev) => withoutMatchingItems(prev, shouldRemove)) + setFormsBySession((prev) => withoutMatchingItems(prev, shouldRemove)) + }, + [], + ) + const prevPermissionCountRef = useRef(0) + const permissionsBySessionRef = useRef({}) + const formsBySessionRef = useRef({}) const initialFetchDoneRef = useRef(false) const statusSyncVersionRef = useRef(0) const remoteStatusSyncVersionsRef = useRef(new Map()) @@ -391,10 +414,16 @@ export function EventProvider({ children }: { children: React.ReactNode }) { useEffect(() => { if (!serversLoaded) return const enabledServerIds = new Set(enabledRemoteServers.map((server) => server.id)) - const isServerEnabled = (serverId: string) => enabledServerIds.has(serverId) - setPermissionsBySession((prev) => withoutItemsFromUnavailableServers(prev, isServerEnabled)) - setFormsBySession((prev) => withoutItemsFromUnavailableServers(prev, isServerEnabled)) - }, [enabledRemoteServers, serversLoaded]) + prunePendingActions((item) => !isLocalOpenCodeServer(item.serverId) && !enabledServerIds.has(item.serverId)) + }, [enabledRemoteServers, serversLoaded, prunePendingActions]) + + useEffect(() => { + permissionsBySessionRef.current = permissionsBySession + }, [permissionsBySession]) + + useEffect(() => { + formsBySessionRef.current = formsBySession + }, [formsBySession]) const viewedSessionId = useMemo( () => parseServerSessionRoute(location.pathname)?.sessionId ?? parseRepoRoute(location.pathname).sessionId, @@ -665,12 +694,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) { reconcilePermissionsForDirectory(directory, pendingPermissions, serverId) reconcileFormsForDirectory(directory, pendingForms, serverId) } catch (error) { + if (!isLocalOpenCodeServer(serverId) && isUnreachableServerError(error)) { + prunePendingActions((item) => item.serverId === serverId) + } if (import.meta.env.DEV) { console.warn(`Failed to fetch pending actions for ${directory}:`, error) } } })) - }, [reconcilePermissionsForDirectory, reconcileFormsForDirectory]) + }, [reconcilePermissionsForDirectory, reconcileFormsForDirectory, prunePendingActions]) const collectTrackedDirectories = useCallback((): string[] => { const directories = new Set() @@ -683,6 +715,47 @@ export function EventProvider({ children }: { children: React.ReactNode }) { return [...directories] }, []) + const reconcilePendingActionsForServer = useCallback(async ( + serverId: string, + extraDirectories: string[] = [], + ) => { + const directoryKeys = new Set( + [...collectTrackedDirectories(), ...extraDirectories] + .filter((key) => parseServerDirectoryKey(key).serverId === serverId), + ) + + const unresolvedSessionIDs = new Set() + for (const bySession of [permissionsBySessionRef.current, formsBySessionRef.current]) { + for (const [sessionID, items] of Object.entries(bySession)) { + if (!items.some((item) => item.serverId === serverId)) continue + if (findSessionDirectoryKey(sessionID) !== null) continue + unresolvedSessionIDs.add(sessionID) + } + } + + if (unresolvedSessionIDs.size > 0) { + await Promise.all([...unresolvedSessionIDs].map(async (sessionID) => { + try { + const session = await getSession(sessionID, serverId) + rememberSessionDirectory(sessionID, session.location.directory, serverId) + directoryKeys.add(buildServerDirectoryKey(serverId, session.location.directory)) + } catch (error) { + if (error instanceof FetchError && error.statusCode === 404) { + prunePendingActions((item) => item.sessionID === sessionID && item.serverId === serverId) + } + } + })) + } + + await reconcilePendingActionsForDirectories([...directoryKeys]) + }, [ + collectTrackedDirectories, + findSessionDirectoryKey, + rememberSessionDirectory, + prunePendingActions, + reconcilePendingActionsForDirectories, + ]) + const resolveSessionAncestry = useCallback(async ( sessionIDs: string[], serverId: string = LOCAL_OPENCODE_SERVER_ID, @@ -830,8 +903,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) { if (reconciled.has(server.id)) continue reconciled.add(server.id) void reconcileRemoteSessionStatuses(server.id) + void reconcilePendingActionsForServer(server.id) } - }, [reconcileRemoteSessionStatuses]) + }, [reconcileRemoteSessionStatuses, reconcilePendingActionsForServer]) useEffect(() => { const enabledIds = new Set(enabledRemoteServers.map((server) => server.id)) @@ -1058,7 +1132,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { streamConnectedRef.current = true reconciledRemoteServerIdsRef.current.clear() initialFetchDoneRef.current = false - void reconcilePendingActionsForDirectories(collectTrackedDirectories()) + void reconcilePendingActionsForServer(LOCAL_OPENCODE_SERVER_ID) fetchInitialSessionStatuses() reconcileRemoteServersOnce(enabledRemoteServersRef.current) void syncRunningShells(collectTrackedDirectories()) @@ -1079,7 +1153,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const directories = subscribedDirectories.filter( (key) => parseServerDirectoryKey(key).serverId === serverId, ) - void reconcilePendingActionsForDirectories(directories) + void reconcilePendingActionsForServer(serverId, subscribedDirectories) void reconcileRemoteSessionStatuses(serverId) void syncRunningShells(directories) invalidateSessionListCachesDebounced(queryClient, undefined, serverId) @@ -1090,7 +1164,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { return } const directories = [...new Set([...collectTrackedDirectories(), ...subscribedDirectories])] - void reconcilePendingActionsForDirectories(directories) + void reconcilePendingActionsForServer(LOCAL_OPENCODE_SERVER_ID, subscribedDirectories) void fetchInitialSessionStatuses() void syncRunningShells(directories) invalidateChildSessionCaches(queryClient) @@ -1120,7 +1194,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { subscription.dispose() subscriptionRef.current = null } - }, [addPermission, removePermission, addForm, removeForm, forgetPendingActionsForSession, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories, syncRunningShells, resolveSessionAncestry, reconcileRemoteSessionStatuses, reconcileRemoteServersOnce, invalidateRemoteStatusSyncs]) + }, [addPermission, removePermission, addForm, removeForm, forgetPendingActionsForSession, rememberSessionDirectory, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, reconcilePendingActionsForServer, collectTrackedDirectories, syncRunningShells, resolveSessionAncestry, reconcileRemoteSessionStatuses, reconcileRemoteServersOnce, invalidateRemoteStatusSyncs]) useEffect(() => { reposRef.current = repos