mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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
@@ -33,6 +33,7 @@ const mocks = vi.hoisted(() => ({
|
||||
useUserBash: vi.fn(),
|
||||
useSessionAgentStore: vi.fn(),
|
||||
useSendErrorStore: vi.fn(),
|
||||
useHasBackgroundActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0 }))
|
||||
@@ -66,6 +67,10 @@ vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAge
|
||||
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
|
||||
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
|
||||
vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore }))
|
||||
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
|
||||
return { ...actual, useHasBackgroundActivity: mocks.useHasBackgroundActivity }
|
||||
})
|
||||
vi.mock('@/lib/toast', () => ({ showToast: mocks.showToast }))
|
||||
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
@@ -206,6 +211,7 @@ describe('PromptInput command submission', () => {
|
||||
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
|
||||
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: mocks.setAgent }))
|
||||
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
|
||||
mocks.useHasBackgroundActivity.mockReturnValue(false)
|
||||
suggestionProps.isOpen = false
|
||||
suggestionProps.selectedIndex = 0
|
||||
})
|
||||
@@ -243,6 +249,27 @@ describe('PromptInput command submission', () => {
|
||||
other.remove()
|
||||
})
|
||||
|
||||
it('announces session activity changes to screen readers', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
|
||||
const buildPrompt = (props: { isSessionActive?: boolean }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PromptInput {...defaultProps} {...props} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
const { rerender } = render(buildPrompt({}))
|
||||
await screen.findByPlaceholderText('Send a message...')
|
||||
expect(screen.getByRole('status').textContent).toBe('')
|
||||
|
||||
rerender(buildPrompt({ isSessionActive: true }))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Session working')
|
||||
|
||||
mocks.useHasBackgroundActivity.mockReturnValue(true)
|
||||
rerender(buildPrompt({}))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Background tasks running')
|
||||
})
|
||||
|
||||
it('disables submit and does not run a command while the model is not ready', async () => {
|
||||
mocks.useModelSelection.mockReturnValue({
|
||||
model: null,
|
||||
|
||||
@@ -1473,8 +1473,17 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
|
||||
|
||||
|
||||
const sessionActivityAnnouncement = isSessionActive
|
||||
? 'Session working'
|
||||
: hasBackgroundActivity
|
||||
? 'Background tasks running'
|
||||
: ''
|
||||
|
||||
return (
|
||||
<div className={`relative isolate border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full before:pointer-events-none before:absolute before:-inset-px before:-z-10 before:rounded-xl before:bg-background/95 before:backdrop-blur-md before:content-[''] ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : composerModeStyle?.frame ?? ''} ${isTakeoverOpen ? 'z-[60]' : ''}`}>
|
||||
<div role="status" aria-live="polite" className="sr-only">
|
||||
{sessionActivityAnnouncement}
|
||||
</div>
|
||||
{composerModeStyle && (
|
||||
<span
|
||||
data-testid="composer-mode-badge"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,6 +10,8 @@ const resetStore = () => {
|
||||
outcomes: new Map(),
|
||||
parents: new Map(),
|
||||
runningShells: new Map(),
|
||||
shellRevisions: new Map(),
|
||||
shellRevision: 0,
|
||||
revision: 0,
|
||||
})
|
||||
}
|
||||
@@ -487,7 +489,8 @@ describe('sessionStatusStore', () => {
|
||||
store.setShellRunning('shell-a', 'session-a', '/repo-a')
|
||||
store.setShellRunning('shell-b', 'session-b', '/repo-b')
|
||||
|
||||
store.replaceRunningShells('/repo-a', [{ id: 'shell-c', sessionID: 'session-c' }])
|
||||
const token = store.beginShellSnapshot()
|
||||
store.replaceRunningShells('/repo-a', [{ id: 'shell-c', sessionID: 'session-c' }], token)
|
||||
|
||||
const shells = useSessionStatus.getState().runningShells
|
||||
expect(shells.has('shell-a')).toBe(false)
|
||||
@@ -495,6 +498,60 @@ describe('sessionStatusStore', () => {
|
||||
expect(shells.get('shell-b')).toEqual({ sessionID: 'session-b', directory: '/repo-b' })
|
||||
})
|
||||
|
||||
it('does not let a shell snapshot resurrect a shell that exited while it was in flight', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
store.setShellRunning('shell-1', 'session-a', '/repo')
|
||||
|
||||
const token = store.beginShellSnapshot()
|
||||
store.clearShell('shell-1')
|
||||
|
||||
useSessionStatus.getState().replaceRunningShells(
|
||||
'/repo',
|
||||
[{ id: 'shell-1', sessionID: 'session-a' }],
|
||||
token,
|
||||
)
|
||||
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('does not let a shell snapshot drop a shell created while it was in flight', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
const token = store.beginShellSnapshot()
|
||||
store.setShellRunning('shell-2', 'session-b', '/repo')
|
||||
|
||||
useSessionStatus.getState().replaceRunningShells('/repo', [], token)
|
||||
|
||||
expect(useSessionStatus.getState().runningShells.get('shell-2')).toEqual({
|
||||
sessionID: 'session-b',
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
it('records a shell exit for an unknown shell so a snapshot cannot resurrect it', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
const token = store.beginShellSnapshot()
|
||||
store.clearShell('shell-ghost')
|
||||
|
||||
useSessionStatus.getState().replaceRunningShells(
|
||||
'/repo',
|
||||
[{ id: 'shell-ghost', sessionID: 'session-a' }],
|
||||
token,
|
||||
)
|
||||
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-ghost')).toBe(false)
|
||||
})
|
||||
|
||||
it('clears shell revisions once the last shell snapshot ends', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
const token = store.beginShellSnapshot()
|
||||
store.setShellRunning('shell-1', 'session-a', '/repo')
|
||||
expect(useSessionStatus.getState().shellRevisions.size).toBe(1)
|
||||
|
||||
store.replaceRunningShells('/repo', [{ id: 'shell-1', sessionID: 'session-a' }], token)
|
||||
|
||||
expect(useSessionStatus.getState().shellRevisions.size).toBe(0)
|
||||
})
|
||||
|
||||
it('forgets a session parent and its running shells', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
store.setSessionParent('child-a', 'parent')
|
||||
|
||||
@@ -13,6 +13,11 @@ interface StatusSnapshotToken {
|
||||
order: number
|
||||
}
|
||||
|
||||
interface ShellSnapshotToken {
|
||||
revision: number
|
||||
order: number
|
||||
}
|
||||
|
||||
interface RunningShell {
|
||||
sessionID: string
|
||||
directory: string
|
||||
@@ -26,6 +31,8 @@ interface SessionStatusStore {
|
||||
outcomes: Map<string, ChildOutcome>
|
||||
parents: Map<string, string | null>
|
||||
runningShells: Map<string, RunningShell>
|
||||
shellRevisions: Map<string, number>
|
||||
shellRevision: number
|
||||
revision: number
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => void
|
||||
setOutcome: (sessionID: string, outcome: ChildOutcome) => void
|
||||
@@ -40,7 +47,9 @@ interface SessionStatusStore {
|
||||
setSessionParent: (sessionID: string, parentID: string | null) => void
|
||||
setShellRunning: (shellID: string, sessionID: string, directory: string) => void
|
||||
clearShell: (shellID: string) => void
|
||||
replaceRunningShells: (directory: string, shells: Array<{ id: string; sessionID: string }>) => void
|
||||
replaceRunningShells: (directory: string, shells: Array<{ id: string; sessionID: string }>, token: ShellSnapshotToken) => void
|
||||
beginShellSnapshot: () => ShellSnapshotToken
|
||||
endShellSnapshot: (token: ShellSnapshotToken) => void
|
||||
forgetSession: (sessionID: string) => void
|
||||
}
|
||||
|
||||
@@ -50,6 +59,8 @@ const optimisticActiveTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
const inFlightSnapshots = new Map<number, number>()
|
||||
let snapshotOrderCounter = 0
|
||||
let lastAppliedSnapshotOrder = 0
|
||||
const inFlightShellSnapshots = new Map<number, number>()
|
||||
let shellSnapshotOrderCounter = 0
|
||||
|
||||
const clearOptimisticActiveTimer = (sessionID: string): void => {
|
||||
const timer = optimisticActiveTimers.get(sessionID)
|
||||
@@ -90,6 +101,46 @@ const sameRunningShells = (left: Map<string, RunningShell>, right: Map<string, R
|
||||
return true
|
||||
}
|
||||
|
||||
const registerShellSnapshot = (token: ShellSnapshotToken): void => {
|
||||
inFlightShellSnapshots.set(token.order, token.revision)
|
||||
}
|
||||
|
||||
const releaseShellSnapshot = (token: ShellSnapshotToken): void => {
|
||||
inFlightShellSnapshots.delete(token.order)
|
||||
}
|
||||
|
||||
const oldestInFlightShellSnapshotRevision = (): number | null => {
|
||||
let oldest: number | null = null
|
||||
for (const revision of inFlightShellSnapshots.values()) {
|
||||
if (oldest === null || revision < oldest) oldest = revision
|
||||
}
|
||||
return oldest
|
||||
}
|
||||
|
||||
const prunedShellRevisions = (currentRevisions: Map<string, number>): Map<string, number> => {
|
||||
const oldestSnapshotRevision = oldestInFlightShellSnapshotRevision()
|
||||
const nextRevisions = new Map<string, number>()
|
||||
if (oldestSnapshotRevision === null) return nextRevisions
|
||||
for (const [shellID, revision] of currentRevisions.entries()) {
|
||||
if (revision > oldestSnapshotRevision) nextRevisions.set(shellID, revision)
|
||||
}
|
||||
return nextRevisions
|
||||
}
|
||||
|
||||
const shellTouchPatch = (
|
||||
state: Pick<SessionStatusStore, 'shellRevisions' | 'shellRevision'>,
|
||||
shellIDs: string[],
|
||||
): Pick<SessionStatusStore, 'shellRevisions' | 'shellRevision'> | null => {
|
||||
if (inFlightShellSnapshots.size === 0 || shellIDs.length === 0) return null
|
||||
let shellRevision = state.shellRevision
|
||||
const shellRevisions = new Map(state.shellRevisions)
|
||||
for (const shellID of shellIDs) {
|
||||
shellRevision += 1
|
||||
shellRevisions.set(shellID, shellRevision)
|
||||
}
|
||||
return { shellRevisions, shellRevision }
|
||||
}
|
||||
|
||||
const markSessionKnown = (knownSessions: Set<string>, sessionID: string): Set<string> | null => {
|
||||
if (knownSessions.has(sessionID)) return null
|
||||
const next = new Set(knownSessions)
|
||||
@@ -195,6 +246,8 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
outcomes: new Map(),
|
||||
parents: new Map(),
|
||||
runningShells: new Map(),
|
||||
shellRevisions: new Map(),
|
||||
shellRevision: 0,
|
||||
revision: 0,
|
||||
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => {
|
||||
@@ -397,34 +450,77 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
|
||||
setShellRunning: (shellID: string, sessionID: string, directory: string) => {
|
||||
const current = get().runningShells.get(shellID)
|
||||
if (current && current.sessionID === sessionID && current.directory === directory) return
|
||||
if (current && current.sessionID === sessionID && current.directory === directory) {
|
||||
const touch = shellTouchPatch(get(), [shellID])
|
||||
if (touch) set(touch)
|
||||
return
|
||||
}
|
||||
set((state) => {
|
||||
const runningShells = new Map(state.runningShells)
|
||||
runningShells.set(shellID, { sessionID, directory })
|
||||
return { runningShells }
|
||||
return { runningShells, ...(shellTouchPatch(state, [shellID]) ?? {}) }
|
||||
})
|
||||
},
|
||||
|
||||
clearShell: (shellID: string) => {
|
||||
if (!get().runningShells.has(shellID)) return
|
||||
if (!get().runningShells.has(shellID)) {
|
||||
const touch = shellTouchPatch(get(), [shellID])
|
||||
if (touch) set(touch)
|
||||
return
|
||||
}
|
||||
set((state) => {
|
||||
const runningShells = new Map(state.runningShells)
|
||||
runningShells.delete(shellID)
|
||||
return { runningShells }
|
||||
return { runningShells, ...(shellTouchPatch(state, [shellID]) ?? {}) }
|
||||
})
|
||||
},
|
||||
|
||||
replaceRunningShells: (directory: string, shells: Array<{ id: string; sessionID: string }>) => {
|
||||
replaceRunningShells: (directory: string, shells: Array<{ id: string; sessionID: string }>, token: ShellSnapshotToken) => {
|
||||
releaseShellSnapshot(token)
|
||||
|
||||
const current = get().runningShells
|
||||
const currentRevisions = get().shellRevisions
|
||||
const runningShells = new Map(current)
|
||||
const isTouched = (shellID: string): boolean => {
|
||||
const revision = currentRevisions.get(shellID)
|
||||
return revision !== undefined && revision > token.revision
|
||||
}
|
||||
|
||||
for (const [shellID, shell] of runningShells.entries()) {
|
||||
if (shell.directory === directory) runningShells.delete(shellID)
|
||||
if (shell.directory !== directory) continue
|
||||
if (isTouched(shellID)) continue
|
||||
runningShells.delete(shellID)
|
||||
}
|
||||
for (const shell of shells) {
|
||||
if (isTouched(shell.id)) continue
|
||||
runningShells.set(shell.id, { sessionID: shell.sessionID, directory })
|
||||
}
|
||||
if (sameRunningShells(current, runningShells)) return
|
||||
set({ runningShells })
|
||||
|
||||
const nextRevisions = prunedShellRevisions(currentRevisions)
|
||||
const shellsChanged = !sameRunningShells(current, runningShells)
|
||||
const revisionsChanged = !sameEntries(currentRevisions, nextRevisions)
|
||||
if (!shellsChanged && !revisionsChanged) return
|
||||
|
||||
set({
|
||||
...(shellsChanged ? { runningShells } : {}),
|
||||
...(revisionsChanged ? { shellRevisions: nextRevisions } : {}),
|
||||
})
|
||||
},
|
||||
|
||||
beginShellSnapshot: () => {
|
||||
const token: ShellSnapshotToken = {
|
||||
revision: get().shellRevision,
|
||||
order: ++shellSnapshotOrderCounter,
|
||||
}
|
||||
registerShellSnapshot(token)
|
||||
return token
|
||||
},
|
||||
|
||||
endShellSnapshot: (token: ShellSnapshotToken) => {
|
||||
releaseShellSnapshot(token)
|
||||
if (inFlightShellSnapshots.size > 0) return
|
||||
if (get().shellRevisions.size === 0) return
|
||||
set({ shellRevisions: new Map() })
|
||||
},
|
||||
|
||||
forgetSession: (sessionID: string) => {
|
||||
@@ -452,8 +548,11 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
knownSessions.delete(sessionID)
|
||||
outcomes.delete(sessionID)
|
||||
parents.delete(sessionID)
|
||||
const removedShellIDs: string[] = []
|
||||
for (const [shellID, shell] of runningShells.entries()) {
|
||||
if (shell.sessionID === sessionID) runningShells.delete(shellID)
|
||||
if (shell.sessionID !== sessionID) continue
|
||||
runningShells.delete(shellID)
|
||||
removedShellIDs.push(shellID)
|
||||
}
|
||||
return {
|
||||
statuses,
|
||||
@@ -462,6 +561,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
outcomes,
|
||||
parents,
|
||||
runningShells,
|
||||
...(shellTouchPatch(state, removedShellIDs) ?? {}),
|
||||
...(recordRevisionPatch(state, sessionID) ?? {}),
|
||||
}
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user