feat(sessions): show background activity for shells and child sessions

This commit is contained in:
Chris Scott committed 2026-10-11 21:52:03 +00:00
1 parent 51e92d8cf2
commit 2e2eff05af
7 files changed
+434 -15

No files matched your search

+125 -1
View File
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
listPendingPermissions: vi.fn(),
listPendingForms: vi.fn(),
listActiveSessions: vi.fn(),
listShells: vi.fn(),
getSession: vi.fn(),
replyPermission: vi.fn(),
replyForm: vi.fn(),
cancelForm: vi.fn(),
@@ -31,6 +33,8 @@ vi.mock('@/api/opencode', () => ({
listActiveSessions: mocks.listActiveSessions,
listPendingPermissions: mocks.listPendingPermissions,
listPendingForms: mocks.listPendingForms,
listShells: mocks.listShells,
getSession: mocks.getSession,
replyPermission: mocks.replyPermission,
replyForm: mocks.replyForm,
cancelForm: mocks.cancelForm,
@@ -173,11 +177,13 @@ describe('EventProvider permissions and forms', () => {
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingForms.mockResolvedValue([])
mocks.listActiveSessions.mockResolvedValue({})
mocks.listShells.mockResolvedValue([])
mocks.getSession.mockRejectedValue(new Error('Session not found'))
mocks.replyPermission.mockResolvedValue(undefined)
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(), 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(), revision: 0 })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
@@ -1733,4 +1739,122 @@ describe('EventProvider permissions and forms', () => {
vi.useRealTimers()
}
})
it('records the parent of a session created with a parentID', 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: 'session.created', data: { sessionID: 'child-1', parentID: 'parent-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
})
it('tracks a running background shell and clears it when it exits', 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: 'shell.created',
data: { info: { id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } } },
directory: '/repo',
})
})
expect(useSessionStatus.getState().runningShells.get('shell-1')).toEqual({
sessionID: 'session-1',
directory: '/repo',
})
act(() => {
onEvent({ type: 'shell.exited', data: { id: 'shell-1', status: 'exited' }, directory: '/repo' })
})
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(false)
})
it('clears a running background shell when it is deleted', 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: 'shell.created',
data: { info: { id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } } },
directory: '/repo',
})
})
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(true)
act(() => {
onEvent({ type: 'shell.deleted', data: { id: 'shell-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(false)
})
it('resolves active session ancestry from the snapshot, walking up to a known root', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({ 'child-1': { type: 'running' } })
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(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('child-1')).toBe('parent-1')
expect(useSessionStatus.getState().parents.get('parent-1')).toBeNull()
})
})
it('populates running shells from the directory snapshot on connect', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listShells.mockResolvedValue([
{ id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } },
{ id: 'shell-2', status: 'exited', metadata: { sessionID: 'session-2' } },
])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo'))
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(mocks.listShells).toHaveBeenCalledWith('/repo')
expect(useSessionStatus.getState().runningShells.get('shell-1')).toEqual({
sessionID: 'session-1',
directory: '/repo',
})
expect(useSessionStatus.getState().runningShells.has('shell-2')).toBe(false)
})
})
})
+85 -3
View File
@@ -4,9 +4,11 @@ import { useNavigate } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import {
cancelForm,
getSession,
listActiveSessions,
listPendingForms,
listPendingPermissions,
listShells,
replyForm,
replyPermission,
} from '@/api/opencode'
@@ -204,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 ancestryInFlightRef = useRef<Set<string>>(new Set())
const { data: repos } = useQuery({
queryKey: ['repos'],
@@ -420,6 +423,52 @@ 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
while (currentID !== null) {
const parents = useSessionStatus.getState().parents
if (parents.has(currentID) || ancestryInFlightRef.current.has(currentID)) return
const lookupID = currentID
ancestryInFlightRef.current.add(lookupID)
try {
const session = await getSession(lookupID)
useSessionStatus.getState().setSessionParent(lookupID, session.parentID ?? null)
currentID = session.parentID ?? null
} catch (error) {
if (import.meta.env.DEV) {
console.warn(`Failed to resolve session ancestry for ${lookupID}:`, error)
}
return
} finally {
ancestryInFlightRef.current.delete(lookupID)
}
}
}
await Promise.allSettled(sessionIDs.map((sessionID) => resolveUp(sessionID)))
}, [])
const fetchInitialPendingData = useCallback(async () => {
const reposToUse = reposRef.current
if (!reposToUse || reposToUse.length === 0) return
@@ -452,13 +501,17 @@ 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)
} catch (error) {
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
if (import.meta.env.DEV) {
console.warn('Failed to fetch active sessions:', error)
}
}
}, [queryClient])
}, [queryClient, resolveSessionAncestry])
const stopStatusPoll = useCallback(() => {
if (statusPollIntervalRef.current === null) return
@@ -555,13 +608,40 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
}
case 'session.created':
case 'session.created': {
invalidateSessionListCachesDebounced(queryClient, event.directory)
if (typeof event.data.parentID === 'string') {
useSessionStatus.getState().setSessionParent(event.data.sessionID, event.data.parentID)
}
break
}
case 'session.forked':
case 'session.renamed':
case 'session.moved':
case 'session.metadata.updated':
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
case 'shell.created': {
const info = event.data.info
if (
info.status === 'running' &&
typeof info.metadata.sessionID === 'string' &&
event.directory
) {
useSessionStatus.getState().setShellRunning(info.id, info.metadata.sessionID, event.directory)
}
break
}
case 'shell.exited': {
if (event.data.status !== 'running') {
useSessionStatus.getState().clearShell(event.data.id)
}
break
}
case 'shell.deleted': {
useSessionStatus.getState().clearShell(event.data.id)
break
}
case 'credential.updated':
case 'credential.switched':
case 'integration.updated':
@@ -608,6 +688,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
initialFetchDoneRef.current = false
fetchInitialPendingData()
fetchInitialSessionStatuses()
void syncRunningShells(collectTrackedDirectories())
invalidateChildSessionCaches(queryClient)
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
startStatusPoll()
@@ -620,6 +701,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const handleResync = () => {
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
void fetchInitialSessionStatuses()
void syncRunningShells(collectTrackedDirectories())
invalidateChildSessionCaches(queryClient)
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
}
@@ -640,7 +722,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])
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories, syncRunningShells])
useEffect(() => {
reposRef.current = repos