mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(events): clear stale pending questions from remote servers
- Drop pending forms and permissions when a session is deleted or its page returns 404 - Reconcile remembered remote directories on browser reconnect, not only local repos - Purge pending items from remote servers that are disabled or removed - Prefer the viewed session's pending item over a pinned item from another session - Time out remote proxy GET/HEAD requests that never send headers (504)
This commit is contained in:
1 parent
b00b74f5a1
commit
382b26806e
7 files changed
+307
-21
No files matched your search
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
|
||||
getHealth: vi.fn(),
|
||||
listProjects: vi.fn(),
|
||||
servers: [] as Array<{ id: string; enabled: boolean }>,
|
||||
serversLoaded: false,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
@@ -48,7 +49,7 @@ vi.mock('@/hooks/useAuth', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: () => ({ servers: mocks.servers }),
|
||||
useOpenCodeServers: () => ({ servers: mocks.servers, isSuccess: mocks.serversLoaded }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/opencode-event-stream', () => ({
|
||||
@@ -244,6 +245,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
mocks.listRepos.mockResolvedValue([])
|
||||
mocks.listProjects.mockResolvedValue([])
|
||||
mocks.servers = []
|
||||
mocks.serversLoaded = false
|
||||
mocks.listPendingPermissions.mockResolvedValue([])
|
||||
mocks.listPendingForms.mockResolvedValue([])
|
||||
mocks.listActiveSessions.mockResolvedValue({})
|
||||
@@ -522,6 +524,34 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('reconciles a remembered remote directory on reconnect', async () => {
|
||||
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
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/srv/app', serverId: 'srv_remote' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1')
|
||||
})
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listPendingForms).toHaveBeenCalledWith('/srv/app', 'srv_remote')
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0')
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('none')
|
||||
})
|
||||
})
|
||||
|
||||
it('reconciles a linked server enabled after the browser stream connects', async () => {
|
||||
const busySessionID = 'session-remote-busy'
|
||||
mocks.listActiveSessions.mockImplementation((serverId?: string) =>
|
||||
@@ -989,6 +1019,36 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('clears pending forms and permissions for a deleted session', async () => {
|
||||
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: 'form.created', data: { form: pendingForm }, directory: '/repo' })
|
||||
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1')
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
|
||||
})
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.deleted', data: { sessionID: 'session-1' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0')
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('0')
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('none')
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('none')
|
||||
})
|
||||
})
|
||||
|
||||
it('does not invalidate the transcript on form reply or cancel events', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listPendingForms.mockResolvedValue([pendingForm, secondPendingForm])
|
||||
@@ -1455,7 +1515,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the shown permission when a viewed-session permission arrives, then advances once it is answered', async () => {
|
||||
it('replaces a pinned out-of-view permission with the viewed-session one, then advances to the remaining pinned one', async () => {
|
||||
render(<Harness />, {
|
||||
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
|
||||
})
|
||||
@@ -1479,21 +1539,53 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
|
||||
})
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'permission.replied',
|
||||
data: { sessionID: 'session-other', requestID: 'permission-other', reply: 'reject' },
|
||||
data: { sessionID: 'session-view', requestID: 'permission-view', reply: 'reject' },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a shown in-view permission when another in-view permission arrives', async () => {
|
||||
act(() => {
|
||||
useSessionStatus.getState().setSessionParent('child-1', 'session-view')
|
||||
})
|
||||
|
||||
render(<Harness />, {
|
||||
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
|
||||
})
|
||||
|
||||
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: 'permission.asked', data: viewedSessionPermission, directory: '/repo' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
|
||||
})
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'permission.asked', data: childSessionPermission, directory: '/repo' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
|
||||
})
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
|
||||
})
|
||||
|
||||
it('prioritizes the viewed session form over an earlier unrelated one', async () => {
|
||||
@@ -1562,7 +1654,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the shown form when a viewed-session form arrives, then advances once it is answered', async () => {
|
||||
it('replaces a pinned out-of-view form with the viewed-session one, then advances to the remaining pinned one', async () => {
|
||||
render(<Harness />, {
|
||||
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
|
||||
})
|
||||
@@ -1586,20 +1678,20 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('2')
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('form-view')
|
||||
})
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'form.cancelled',
|
||||
data: { id: 'form-other', sessionID: 'session-other' },
|
||||
data: { id: 'form-view', sessionID: 'session-view' },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1')
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('form-view')
|
||||
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2931,6 +3023,37 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(mocks.listActiveSessions).not.toHaveBeenCalledWith('srv_disabled')
|
||||
})
|
||||
|
||||
it('purges pending actions from a server that is not enabled once servers load', async () => {
|
||||
const { rerender } = 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: 'form.created', data: { form: pendingForm }, directory: '/srv/app', serverId: 'srv_removed' })
|
||||
onEvent({ type: 'form.created', data: { form: secondPendingForm }, directory: '/srv/app', serverId: 'srv_remote' })
|
||||
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/srv/app', serverId: 'srv_removed' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('2')
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
|
||||
})
|
||||
|
||||
mocks.servers = [{ id: 'srv_remote', enabled: true }]
|
||||
mocks.serversLoaded = true
|
||||
rerender(<Harness />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1')
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('0')
|
||||
})
|
||||
expect(screen.getByTestId('for-session-2')).toHaveTextContent('form-2')
|
||||
expect(screen.getByTestId('for-session-1')).toHaveTextContent('none')
|
||||
})
|
||||
|
||||
it('subscribes the project directories of enabled remote servers', async () => {
|
||||
mocks.servers = [{ id: 'srv_remote', enabled: true }]
|
||||
mocks.listProjects.mockResolvedValue([{ id: 'proj-1', canonical: '/remote/repo' }])
|
||||
|
||||
@@ -104,9 +104,10 @@ function isSessionWithinView(
|
||||
}
|
||||
|
||||
/**
|
||||
* Pins the item currently on screen until it leaves `items`, then advances to the first item whose
|
||||
* session is the viewed session or one of its descendants, falling back to the first item.
|
||||
* The selection is derived during render so a newly arriving item never displaces the shown one.
|
||||
* Selects the pinned item while it belongs to the viewed session or no session is viewed,
|
||||
* otherwise the first item within the viewed session, otherwise the pinned item while it is still
|
||||
* present, otherwise the first item. The selection is derived during render so a newly arriving
|
||||
* item never displaces a shown item that is within the view.
|
||||
*/
|
||||
function usePinnedViewedItem<T extends SessionScopedItem>(
|
||||
items: T[],
|
||||
@@ -116,15 +117,15 @@ function usePinnedViewedItem<T extends SessionScopedItem>(
|
||||
const [pinnedId, setPinnedId] = useState<string | null>(null)
|
||||
|
||||
const selected = useMemo(() => {
|
||||
if (pinnedId) {
|
||||
const pinned = items.find((item) => item.id === pinnedId)
|
||||
if (pinned) return pinned
|
||||
const pinned = pinnedId ? items.find((item) => item.id === pinnedId) ?? null : null
|
||||
if (pinned && (viewedSessionId === null || isSessionWithinView(pinned.sessionID, viewedSessionId, parents))) {
|
||||
return pinned
|
||||
}
|
||||
|
||||
const forViewedSession = viewedSessionId
|
||||
? items.find((item) => isSessionWithinView(item.sessionID, viewedSessionId, parents)) ?? null
|
||||
: null
|
||||
return forViewedSession ?? items[0] ?? null
|
||||
return forViewedSession ?? pinned ?? items[0] ?? null
|
||||
}, [items, viewedSessionId, parents, pinnedId])
|
||||
|
||||
const selectedId = selected?.id ?? null
|
||||
@@ -158,6 +159,33 @@ function reconcileBySessionForDirectory<T extends SessionScopedItem & { serverId
|
||||
return next
|
||||
}
|
||||
|
||||
function withoutSessionKey<T>(bySession: Record<string, T[]>, sessionID: string): Record<string, T[]> {
|
||||
if (!(sessionID in bySession)) return bySession
|
||||
const next = { ...bySession }
|
||||
delete next[sessionID]
|
||||
return next
|
||||
}
|
||||
|
||||
function withoutItemsFromUnavailableServers<T extends SessionScopedItem & { serverId: string }>(
|
||||
bySession: Record<string, T[]>,
|
||||
isServerEnabled: (serverId: string) => boolean,
|
||||
): Record<string, T[]> {
|
||||
let changed = false
|
||||
const next: Record<string, T[]> = {}
|
||||
|
||||
for (const [sessionID, items] of Object.entries(bySession)) {
|
||||
const kept = items.filter((item) => isLocalOpenCodeServer(item.serverId) || isServerEnabled(item.serverId))
|
||||
if (kept.length === items.length) {
|
||||
next[sessionID] = items
|
||||
continue
|
||||
}
|
||||
changed = true
|
||||
if (kept.length > 0) next[sessionID] = kept
|
||||
}
|
||||
|
||||
return changed ? next : bySession
|
||||
}
|
||||
|
||||
interface SSHHostKeyState {
|
||||
request: SSHHostKeyRequest | null
|
||||
respond: (requestId: string, approved: boolean) => Promise<void>
|
||||
@@ -226,6 +254,11 @@ interface EventContextValue {
|
||||
hasForSession: (sessionID: string) => boolean
|
||||
navigateToCurrent: () => void
|
||||
syncForSession: (directory: string, sessionID: string, serverId?: string) => Promise<void>
|
||||
/**
|
||||
* Drops every pending form and permission recorded for the session, used when the session no
|
||||
* longer exists on its server.
|
||||
*/
|
||||
forgetPendingActionsForSession: (sessionID: string) => void
|
||||
}
|
||||
sseHealth: SSEHealthState
|
||||
getRepoIdForSession: (sessionID: string) => number | null
|
||||
@@ -324,7 +357,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
})
|
||||
|
||||
const { isAuthenticated } = useAuth()
|
||||
const { servers } = useOpenCodeServers({ enabled: isAuthenticated })
|
||||
const { servers, isSuccess: serversLoaded } = useOpenCodeServers({ enabled: isAuthenticated })
|
||||
const enabledRemoteServers = useMemo(() => servers.filter((server) => server.enabled), [servers])
|
||||
const enabledRemoteServersRef = useRef(enabledRemoteServers)
|
||||
useEffect(() => {
|
||||
@@ -355,6 +388,14 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const pendingPermissionSessionIDs = usePendingSessionIDs(permissionsBySession)
|
||||
const pendingFormSessionIDs = usePendingSessionIDs(formsBySession)
|
||||
|
||||
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])
|
||||
|
||||
const viewedSessionId = useMemo(
|
||||
() => parseServerSessionRoute(location.pathname)?.sessionId ?? parseRepoRoute(location.pathname).sessionId,
|
||||
[location.pathname],
|
||||
@@ -468,6 +509,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
removeFromSessionKeyedState(setFormsBySession, formID, sessionID)
|
||||
}, [])
|
||||
|
||||
const forgetPendingActionsForSession = useCallback((sessionID: string) => {
|
||||
setPermissionsBySession((prev) => withoutSessionKey(prev, sessionID))
|
||||
setFormsBySession((prev) => withoutSessionKey(prev, sessionID))
|
||||
}, [])
|
||||
|
||||
const reconcilePermissionsForDirectory = useCallback((
|
||||
directory: string,
|
||||
permissions: PermissionRequest[],
|
||||
@@ -912,6 +958,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
case 'session.deleted': {
|
||||
useSessionStatus.getState().forgetSession(event.data.sessionID)
|
||||
forgetPendingActionsForSession(event.data.sessionID)
|
||||
invalidateSessionListCachesDebounced(queryClient, event.directory, serverId)
|
||||
break
|
||||
}
|
||||
@@ -1011,7 +1058,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
streamConnectedRef.current = true
|
||||
reconciledRemoteServerIdsRef.current.clear()
|
||||
initialFetchDoneRef.current = false
|
||||
fetchInitialPendingData()
|
||||
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
|
||||
fetchInitialSessionStatuses()
|
||||
reconcileRemoteServersOnce(enabledRemoteServersRef.current)
|
||||
void syncRunningShells(collectTrackedDirectories())
|
||||
@@ -1073,7 +1120,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
subscription.dispose()
|
||||
subscriptionRef.current = null
|
||||
}
|
||||
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories, syncRunningShells, resolveSessionAncestry, reconcileRemoteSessionStatuses, reconcileRemoteServersOnce, invalidateRemoteStatusSyncs])
|
||||
}, [addPermission, removePermission, addForm, removeForm, forgetPendingActionsForSession, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories, syncRunningShells, resolveSessionAncestry, reconcileRemoteSessionStatuses, reconcileRemoteServersOnce, invalidateRemoteStatusSyncs])
|
||||
|
||||
useEffect(() => {
|
||||
reposRef.current = repos
|
||||
@@ -1127,6 +1174,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
hasForSession: hasFormsForSession,
|
||||
navigateToCurrent: navigateToCurrentForm,
|
||||
syncForSession: syncFormsForSession,
|
||||
forgetPendingActionsForSession,
|
||||
},
|
||||
sseHealth,
|
||||
getRepoIdForSession,
|
||||
@@ -1156,6 +1204,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
hasFormsForSession,
|
||||
navigateToCurrentForm,
|
||||
syncFormsForSession,
|
||||
forgetPendingActionsForSession,
|
||||
sseHealth,
|
||||
getRepoIdForSession,
|
||||
])
|
||||
|
||||
Reference in new issue
Block a user