From aec94db9fba50d7babff0069de400e674c22d480 Mon Sep 17 00:00:00 2001 From: Chris Scott <> Date: Mon, 12 Oct 2026 01:08:58 +0000 Subject: [PATCH] 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 --- .../message/PromptInput.command.test.tsx | 27 ++++ .../src/components/message/PromptInput.tsx | 9 ++ frontend/src/contexts/EventContext.test.tsx | 135 +++++++++++++++++- frontend/src/contexts/EventContext.tsx | 76 ++++++---- .../src/stores/sessionStatusStore.test.ts | 59 +++++++- frontend/src/stores/sessionStatusStore.ts | 120 ++++++++++++++-- 6 files changed, 384 insertions(+), 42 deletions(-) diff --git a/frontend/src/components/message/PromptInput.command.test.tsx b/frontend/src/components/message/PromptInput.command.test.tsx index 7a9c8723..cd1d8edf 100644 --- a/frontend/src/components/message/PromptInput.command.test.tsx +++ b/frontend/src/components/message/PromptInput.command.test.tsx @@ -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() + 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 }) => ( + + + + ) + + 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, diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 19859899..4612af3e 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -1473,8 +1473,17 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) + const sessionActivityAnnouncement = isSessionActive + ? 'Session working' + : hasBackgroundActivity + ? 'Background tasks running' + : '' + return (
+
+ {sessionActivityAnnouncement} +
{composerModeStyle && ( { 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>() + mocks.listShells.mockReturnValue(deferred.promise) + + render(, { 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>() + mocks.listShells.mockReturnValue(deferred.promise) + + render(, { 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(, { 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(, { 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>() + mocks.listRepos.mockReturnValueOnce(reposDeferred.promise) + + 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) + }) + + expect(mocks.listShells).not.toHaveBeenCalled() + + await act(async () => { + reposDeferred.resolve([{ id: 123, fullPath: '/repo' }]) + await reposDeferred.promise + }) + + await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo')) + }) }) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index a51433fc..30745182 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -206,6 +206,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const statusPollIntervalRef = useRef | null>(null) const subscriptionRef = useRef | null>(null) const reposRef = useRef(null) + const trackedRepoDirectoriesRef = useRef>(new Set()) const ancestryInFlightRef = useRef>(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 => { let currentID: string | null = startID + const visited = new Set() 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 diff --git a/frontend/src/stores/sessionStatusStore.test.ts b/frontend/src/stores/sessionStatusStore.test.ts index b0374421..f1a71dce 100644 --- a/frontend/src/stores/sessionStatusStore.test.ts +++ b/frontend/src/stores/sessionStatusStore.test.ts @@ -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') diff --git a/frontend/src/stores/sessionStatusStore.ts b/frontend/src/stores/sessionStatusStore.ts index 7e9a3fc9..7f30d424 100644 --- a/frontend/src/stores/sessionStatusStore.ts +++ b/frontend/src/stores/sessionStatusStore.ts @@ -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 parents: Map runningShells: Map + shellRevisions: Map + 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>() const inFlightSnapshots = new Map() let snapshotOrderCounter = 0 let lastAppliedSnapshotOrder = 0 +const inFlightShellSnapshots = new Map() +let shellSnapshotOrderCounter = 0 const clearOptimisticActiveTimer = (sessionID: string): void => { const timer = optimisticActiveTimers.get(sessionID) @@ -90,6 +101,46 @@ const sameRunningShells = (left: Map, right: Map { + 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): Map => { + const oldestSnapshotRevision = oldestInFlightShellSnapshotRevision() + const nextRevisions = new Map() + 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, + shellIDs: string[], +): Pick | 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, sessionID: string): Set | null => { if (knownSessions.has(sessionID)) return null const next = new Set(knownSessions) @@ -195,6 +246,8 @@ export const useSessionStatus = create((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((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((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((set, get) => { outcomes, parents, runningShells, + ...(shellTouchPatch(state, removedShellIDs) ?? {}), ...(recordRevisionPatch(state, sessionID) ?? {}), } })