mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
fix(sessions): address background activity review feedback
- keep shell state changed by events that arrive while a shell snapshot is in flight, so an exited shell is not restored and a new one is not dropped - resolve session ancestry for the owners of running shells and for new shells - follow already-known parent links when resolving ancestry - sync running shells for repository directories added after the stream connects - announce session and background activity to screen readers from the prompt bar
This commit is contained in:
1 parent
5dbf9766a5
commit
aec94db9fb
6 files changed
+384
-42
No files matched your search
@@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSessionStatus, hasBackgroundActivity } from '@/stores/sessionStatusStore'
|
||||
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
|
||||
import { EventProvider, useEventContext, useForms, usePermissions, useSSEHealth } from './EventContext'
|
||||
|
||||
@@ -183,7 +183,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
mocks.replyForm.mockResolvedValue(undefined)
|
||||
mocks.cancelForm.mockResolvedValue(undefined)
|
||||
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), runningShells: new Map(), revision: 0 })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), runningShells: new Map(), shellRevisions: new Map(), shellRevision: 0, revision: 0 })
|
||||
mocks.subscribeGlobalMonitor.mockReturnValue({
|
||||
dispose: vi.fn(),
|
||||
updateDirectories: vi.fn(),
|
||||
@@ -1857,4 +1857,135 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-2')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not let a directory shell snapshot resurrect a shell that exited while it was in flight', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
const deferred = createDeferred<Array<{ id: string; status: string; metadata: { sessionID: string } }>>()
|
||||
mocks.listShells.mockReturnValue(deferred.promise)
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'shell.exited', data: { id: 'shell-1', status: 'exited' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve([{ id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } }])
|
||||
await deferred.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('does not let a directory shell snapshot drop a shell created while it was in flight', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
const deferred = createDeferred<Array<{ id: string; status: string; metadata: { sessionID: string } }>>()
|
||||
mocks.listShells.mockReturnValue(deferred.promise)
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'shell.created',
|
||||
data: { info: { id: 'shell-2', status: 'running', metadata: { sessionID: 'session-2' } } },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve([])
|
||||
await deferred.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().runningShells.get('shell-2')).toEqual({
|
||||
sessionID: 'session-2',
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves ancestry for a shell owner from the directory snapshot', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listShells.mockResolvedValue([
|
||||
{ id: 'shell-1', status: 'running', metadata: { sessionID: 'child-1' } },
|
||||
])
|
||||
mocks.getSession.mockImplementation((sessionID: string) => {
|
||||
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
|
||||
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
|
||||
return Promise.reject(new Error('Session not found'))
|
||||
})
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
|
||||
})
|
||||
|
||||
expect(hasBackgroundActivity(useSessionStatus.getState(), 'parent-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('continues a known child to parent link up to the grandparent', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listActiveSessions.mockResolvedValue({ 'child-1': { type: 'running' } })
|
||||
mocks.getSession.mockImplementation((sessionID: string) => {
|
||||
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', parentID: 'grandparent-1' })
|
||||
if (sessionID === 'grandparent-1') return Promise.resolve({ id: 'grandparent-1' })
|
||||
return Promise.reject(new Error('Session not found'))
|
||||
})
|
||||
|
||||
act(() => {
|
||||
useSessionStatus.getState().setSessionParent('child-1', 'parent-1')
|
||||
})
|
||||
|
||||
render(<Harness />, { 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)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().parents.get('parent-1')).toBe('grandparent-1')
|
||||
expect(useSessionStatus.getState().parents.get('grandparent-1')).toBeNull()
|
||||
})
|
||||
expect(mocks.getSession).toHaveBeenCalledWith('parent-1')
|
||||
})
|
||||
|
||||
it('syncs running shells for a directory whose repo arrives after connect', async () => {
|
||||
const reposDeferred = createDeferred<Array<{ id: number; fullPath: string }>>()
|
||||
mocks.listRepos.mockReturnValueOnce(reposDeferred.promise)
|
||||
|
||||
render(<Harness />, { 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)
|
||||
})
|
||||
|
||||
expect(mocks.listShells).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
reposDeferred.resolve([{ id: 123, fullPath: '/repo' }])
|
||||
await reposDeferred.promise
|
||||
})
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
})
|
||||
})
|
||||
@@ -206,6 +206,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const statusPollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
|
||||
const reposRef = useRef<typeof repos>(null)
|
||||
const trackedRepoDirectoriesRef = useRef<Set<string>>(new Set())
|
||||
const ancestryInFlightRef = useRef<Set<string>>(new Set())
|
||||
|
||||
const { data: repos } = useQuery({
|
||||
@@ -423,32 +424,21 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
return [...directories]
|
||||
}, [])
|
||||
|
||||
const syncRunningShells = useCallback(async (directories: string[]) => {
|
||||
await Promise.all(directories.map(async (directory) => {
|
||||
try {
|
||||
const shells = await listShells(directory)
|
||||
useSessionStatus.getState().replaceRunningShells(
|
||||
directory,
|
||||
shells.flatMap((shell) => {
|
||||
const sessionID = shell.metadata.sessionID
|
||||
if (shell.status !== 'running' || typeof sessionID !== 'string') return []
|
||||
return [{ id: shell.id, sessionID }]
|
||||
}),
|
||||
)
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to fetch running shells for ${directory}:`, error)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}, [])
|
||||
|
||||
const resolveSessionAncestry = useCallback(async (sessionIDs: string[]) => {
|
||||
const resolveUp = async (startID: string): Promise<void> => {
|
||||
let currentID: string | null = startID
|
||||
const visited = new Set<string>()
|
||||
while (currentID !== null) {
|
||||
if (visited.has(currentID)) return
|
||||
visited.add(currentID)
|
||||
|
||||
const parents = useSessionStatus.getState().parents
|
||||
if (parents.has(currentID) || ancestryInFlightRef.current.has(currentID)) return
|
||||
if (parents.has(currentID)) {
|
||||
currentID = parents.get(currentID) ?? null
|
||||
continue
|
||||
}
|
||||
if (ancestryInFlightRef.current.has(currentID)) return
|
||||
|
||||
const lookupID = currentID
|
||||
ancestryInFlightRef.current.add(lookupID)
|
||||
try {
|
||||
@@ -469,6 +459,27 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
await Promise.allSettled(sessionIDs.map((sessionID) => resolveUp(sessionID)))
|
||||
}, [])
|
||||
|
||||
const syncRunningShells = useCallback(async (directories: string[]) => {
|
||||
await Promise.all(directories.map(async (directory) => {
|
||||
const token = useSessionStatus.getState().beginShellSnapshot()
|
||||
try {
|
||||
const shells = await listShells(directory)
|
||||
const runningShells = shells.flatMap((shell) => {
|
||||
const sessionID = shell.metadata.sessionID
|
||||
if (shell.status !== 'running' || typeof sessionID !== 'string') return []
|
||||
return [{ id: shell.id, sessionID }]
|
||||
})
|
||||
useSessionStatus.getState().replaceRunningShells(directory, runningShells, token)
|
||||
await resolveSessionAncestry(runningShells.map((shell) => shell.sessionID))
|
||||
} catch (error) {
|
||||
useSessionStatus.getState().endShellSnapshot(token)
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to fetch running shells for ${directory}:`, error)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}, [resolveSessionAncestry])
|
||||
|
||||
const fetchInitialPendingData = useCallback(async () => {
|
||||
const reposToUse = reposRef.current
|
||||
if (!reposToUse || reposToUse.length === 0) return
|
||||
@@ -501,10 +512,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
if (becameUnknown.length > 0) {
|
||||
invalidateChildSessionCaches(queryClient, becameUnknown)
|
||||
}
|
||||
const unresolvedSessionIDs = Object.keys(active).filter(
|
||||
(sessionID) => !useSessionStatus.getState().parents.has(sessionID),
|
||||
)
|
||||
await resolveSessionAncestry(unresolvedSessionIDs)
|
||||
await resolveSessionAncestry(Object.keys(active))
|
||||
} catch (error) {
|
||||
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
|
||||
if (import.meta.env.DEV) {
|
||||
@@ -628,7 +636,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
typeof info.metadata.sessionID === 'string' &&
|
||||
event.directory
|
||||
) {
|
||||
useSessionStatus.getState().setShellRunning(info.id, info.metadata.sessionID, event.directory)
|
||||
const sessionID = info.metadata.sessionID
|
||||
useSessionStatus.getState().setShellRunning(info.id, sessionID, event.directory)
|
||||
if (!useSessionStatus.getState().parents.has(sessionID)) {
|
||||
void resolveSessionAncestry([sessionID])
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -722,15 +734,21 @@ 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])
|
||||
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories, syncRunningShells, resolveSessionAncestry])
|
||||
|
||||
useEffect(() => {
|
||||
reposRef.current = repos
|
||||
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
|
||||
const previousDirectories = trackedRepoDirectoriesRef.current
|
||||
const addedDirectories = directories.filter((directory) => !previousDirectories.has(directory))
|
||||
trackedRepoDirectoriesRef.current = new Set(directories)
|
||||
const sub = subscriptionRef.current
|
||||
if (!sub) return
|
||||
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
|
||||
sub.updateDirectories(directories)
|
||||
}, [repos])
|
||||
if (addedDirectories.length > 0) {
|
||||
void syncRunningShells(addedDirectories)
|
||||
}
|
||||
}, [repos, syncRunningShells])
|
||||
|
||||
useEffect(() => {
|
||||
if (!repos || repos.length === 0) return
|
||||
|
||||
Reference in new issue
Block a user