Merge pull request #419 from chriswritescode-dev/feat/session-background-activity

feat(sessions): show background activity for shells and child sessions
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-12 00:17:55 -04:00
commit eca2275909
11 files changed
+1033 -19

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
import type { APIRequestContext, Page } from '@playwright/test'
import { test, expect } from './fixtures'
const SHELL_COMMAND = 'sleep 300'
function locationQuery(directory: string): string {
return new URLSearchParams({ 'location[directory]': directory }).toString()
}
function backgroundIndicator(page: Page) {
return page.getByRole('main').getByLabel('Background tasks running')
}
function backgroundStatus(page: Page) {
return page.getByRole('status').filter({ hasText: 'Background tasks running' })
}
async function requireOk(response: Awaited<ReturnType<APIRequestContext['post']>>, label: string): Promise<unknown> {
if (!response.ok()) {
throw new Error(`${label} failed: ${response.status()} ${await response.text()}`)
}
return response.json()
}
async function createSession(request: APIRequestContext, directory: string, parentID?: string): Promise<string> {
const body = await requireOk(
await request.post('/api/opencode/api/session', {
data: { location: { directory }, ...(parentID ? { parentID } : {}) },
}),
'create session',
)
return (body as { data: { id: string } }).data.id
}
async function startBackgroundShell(
request: APIRequestContext,
directory: string,
sessionID: string,
): Promise<string> {
const body = await requireOk(
await request.post(`/api/opencode/api/shell?${locationQuery(directory)}`, {
data: { command: SHELL_COMMAND, timeout: 0, metadata: { sessionID, background: true } },
}),
'start background shell',
)
return (body as { data: { id: string } }).data.id
}
async function removeShell(request: APIRequestContext, directory: string, shellID: string): Promise<void> {
const response = await request.delete(`/api/opencode/api/shell/${shellID}?${locationQuery(directory)}`)
if (!response.ok() && response.status() !== 404) {
throw new Error(`remove shell failed: ${response.status()} ${await response.text()}`)
}
}
const createdShells: Array<{ directory: string; id: string }> = []
test.afterEach(async ({ request }) => {
const shells = createdShells.splice(0)
const results = await Promise.allSettled(shells.map(({ directory, id }) => removeShell(request, directory, id)))
const failures = results.flatMap((result) => (result.status === 'rejected' ? [String(result.reason)] : []))
expect(failures, 'background shell cleanup failed').toEqual([])
})
test.describe('session background activity', () => {
test('shows the background indicator for a shell running before page load and clears it when removed', async ({
page,
request,
repo,
}) => {
const sessionId = await createSession(request, repo.fullPath)
const shellId = await startBackgroundShell(request, repo.fullPath, sessionId)
createdShells.push({ directory: repo.fullPath, id: shellId })
await page.goto(`/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toBeVisible()
await expect(backgroundStatus(page)).toBeAttached()
await removeShell(request, repo.fullPath, shellId)
await expect(backgroundIndicator(page)).toBeHidden()
await expect(backgroundStatus(page)).toHaveCount(0)
})
test('shows the background indicator when a shell starts while the page is open and clears it when removed', async ({
page,
request,
repo,
}) => {
const sessionId = await createSession(request, repo.fullPath)
await page.goto(`/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toHaveCount(0)
const shellId = await startBackgroundShell(request, repo.fullPath, sessionId)
createdShells.push({ directory: repo.fullPath, id: shellId })
await expect(backgroundIndicator(page)).toBeVisible()
await expect(backgroundStatus(page)).toBeAttached()
await removeShell(request, repo.fullPath, shellId)
await expect(backgroundIndicator(page)).toBeHidden()
await expect(backgroundStatus(page)).toHaveCount(0)
})
test('shows the background indicator on a parent session when a child session owns the running shell', async ({
page,
request,
repo,
}) => {
const parentId = await createSession(request, repo.fullPath)
const childId = await createSession(request, repo.fullPath, parentId)
const shellId = await startBackgroundShell(request, repo.fullPath, childId)
createdShells.push({ directory: repo.fullPath, id: shellId })
await page.goto(`/repos/${repo.id}/sessions/${parentId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toBeVisible()
await expect(backgroundStatus(page)).toBeAttached()
await removeShell(request, repo.fullPath, shellId)
await expect(backgroundIndicator(page)).toBeHidden()
await expect(backgroundStatus(page)).toHaveCount(0)
})
test('shows no background indicator for a session with no running shells', async ({ page, request, repo }) => {
const sessionId = await createSession(request, repo.fullPath)
await page.goto(`/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toHaveCount(0)
await expect(backgroundStatus(page)).toHaveCount(0)
})
})
@@ -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,
@@ -12,6 +12,7 @@ import { useUserBash } from '@/stores/userBashStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
import { useHasBackgroundActivity } from '@/stores/sessionStatusStore'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
import { useMobile } from '@/hooks/useMobile'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
@@ -248,6 +249,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}, [])
const sessionAgent = useSessionAgent(sessionID, directory)
const hasBackgroundActivity = useHasBackgroundActivity(sessionID)
const currentMode = localMode ?? sessionAgent.agent
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
const sendPrompt = useSendPrompt(directory)
@@ -1471,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"
@@ -1540,7 +1551,7 @@ return (
<ArrowDown className="w-4 h-4" />
<span>Latest</span>
</button>
{isSessionActive && (
{(isSessionActive || hasBackgroundActivity) && (
<div className="px-2.5 py-1.5 rounded-lg text-xs font-medium text-muted-foreground max-w-[120px]">
<SessionStatusIndicator sessionID={sessionID} showLabel />
</div>
@@ -1573,7 +1584,7 @@ return (
</IconToggleButton>
</>
)}
{isSessionActive && (
{(isSessionActive || hasBackgroundActivity) && (
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
<SessionStatusIndicator sessionID={sessionID} showLabel />
</div>
@@ -0,0 +1,37 @@
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it } from 'vitest'
import { SessionStatusIndicator } from './session-status-indicator'
import { useSessionStatus } from '@/stores/sessionStatusStore'
const resetStore = () => {
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,
})
}
describe('SessionStatusIndicator background activity', () => {
beforeEach(() => {
resetStore()
})
it('shows the background tasks label when idle with a running shell', () => {
useSessionStatus.getState().setShellRunning('shell-1', 'session-a', '/repo')
render(<SessionStatusIndicator sessionID="session-a" showLabel />)
expect(screen.getByLabelText('Background tasks running')).toBeInTheDocument()
})
it('renders nothing when idle without background activity', () => {
const { container } = render(<SessionStatusIndicator sessionID="session-a" showLabel />)
expect(container).toBeEmptyDOMElement()
})
})
@@ -1,5 +1,5 @@
import { memo, useEffect, useState } from 'react'
import { useSessionStatusForSession, type SessionStatusType } from '@/stores/sessionStatusStore'
import { useHasBackgroundActivity, useSessionStatusForSession, type SessionStatusType } from '@/stores/sessionStatusStore'
interface SessionStatusIndicatorProps {
sessionID: string
@@ -18,12 +18,14 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
showLabel = false
}: SessionStatusIndicatorProps) {
const status = useSessionStatusForSession(sessionID)
const hasBackground = useHasBackgroundActivity(sessionID)
const [position, setPosition] = useState(0)
const [direction, setDirection] = useState(1)
const [retryCountdown, setRetryCountdown] = useState(0)
const backgroundOnly = status.type === 'idle' && hasBackground
useEffect(() => {
if (status.type !== 'busy' && status.type !== 'retry' && status.type !== 'compact') {
if (status.type === 'idle' && !hasBackground) {
return
}
@@ -43,7 +45,7 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
}, 60)
return () => clearInterval(interval)
}, [status.type, direction])
}, [status.type, hasBackground, direction])
useEffect(() => {
if (!showLabel || status.type !== 'retry') {
@@ -62,11 +64,11 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
return () => clearInterval(interval)
}, [status, showLabel])
if (status.type === 'idle') {
if (status.type === 'idle' && !hasBackground) {
return null
}
const getSegmentColor = (index: number, statusType: SessionStatusType['type']) => {
const getSegmentColor = (index: number, statusType: SessionStatusType['type'], background: boolean) => {
const distance = Math.abs(index - (position + SCANNER_WIDTH / 2))
const maxDistance = SCANNER_WIDTH / 2
@@ -76,6 +78,13 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
const intensity = Math.max(0, 1 - distance / (maxDistance + 2))
if (background) {
if (intensity > 0.8) return 'bg-muted-foreground'
if (intensity > 0.5) return 'bg-muted-foreground/70'
if (intensity > 0.2) return 'bg-muted-foreground/40'
return 'bg-muted-foreground/20'
}
if (statusType === 'retry') {
if (intensity > 0.8) return 'bg-warning'
if (intensity > 0.5) return 'bg-warning/70'
@@ -100,12 +109,16 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
const containerGap = showLabel ? 'gap-2' : ''
return (
<div className={`flex items-center ${containerGap} ${className}`}>
<div
className={`flex items-center ${containerGap} ${className}`}
title={backgroundOnly ? 'Background tasks running' : undefined}
aria-label={backgroundOnly ? 'Background tasks running' : undefined}
>
<div className="flex gap-0.5">
{Array.from({ length: SCANNER_SEGMENTS }).map((_, i) => (
<div
key={i}
className={`${segmentClass} rounded-sm transition-colors duration-75 ${getSegmentColor(i, status.type)}`}
className={`${segmentClass} rounded-sm transition-colors duration-75 ${getSegmentColor(i, status.type, backgroundOnly)}`}
/>
))}
</div>
+257 -2
View File
@@ -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'
@@ -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(), shellRevisions: new Map(), shellRevision: 0, revision: 0 })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
@@ -1733,4 +1739,253 @@ 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)
})
})
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'))
})
})
+105 -5
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,8 @@ 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({
queryKey: ['repos'],
@@ -420,6 +424,62 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return [...directories]
}, [])
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)) {
currentID = parents.get(currentID) ?? null
continue
}
if (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 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
@@ -452,13 +512,14 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
if (becameUnknown.length > 0) {
invalidateChildSessionCaches(queryClient, becameUnknown)
}
await resolveSessionAncestry(Object.keys(active))
} 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 +616,44 @@ 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
) {
const sessionID = info.metadata.sessionID
useSessionStatus.getState().setShellRunning(info.id, sessionID, event.directory)
if (!useSessionStatus.getState().parents.has(sessionID)) {
void resolveSessionAncestry([sessionID])
}
}
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 +700,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 +713,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,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])
}, [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,7 @@ import type {
import { useSessionTranscript } from './useSessionTranscript'
import { ContextUsageIndicator } from '@/components/session/ContextUsageIndicator'
import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection'
import type { TranscriptCache } from '@/lib/session-projection'
import { sessionTranscriptQueryKey } from '@/lib/queryInvalidation'
import {
ASSISTANT_MESSAGE_ID,
@@ -44,6 +45,7 @@ vi.mock('@/lib/opencode-event-stream', async () => {
})
const DIRECTORY = '/repo'
const SECOND_SESSION_ID = 'ses_2'
interface SnapshotValue {
messages: SessionMessageInfo[]
@@ -214,6 +216,113 @@ describe('useSessionTranscript', () => {
})
})
it('reads the newest page once on a fresh mount with no cached transcript', async () => {
const queryClient = createQueryClient()
const { result } = renderHook(() => useSessionTranscript(SESSION_ID, DIRECTORY), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(result.current.messages).toHaveLength(2))
await act(async () => {})
expect(mocks.readSessionSnapshot).toHaveBeenCalledTimes(1)
})
it('refreshes a cached transcript when switching to another session', async () => {
const queryClient = createQueryClient()
const { result, rerender } = renderHook(
({ sessionID }: { sessionID: string }) => useSessionTranscript(sessionID, DIRECTORY),
{
wrapper: createWrapper(queryClient),
initialProps: { sessionID: SESSION_ID },
},
)
await waitFor(() => expect(result.current.messages).toHaveLength(2))
expect(mocks.readSessionSnapshot).toHaveBeenCalledTimes(1)
const staleBusy: TranscriptCache = {
transcript: { messages: seededMessages, pending: [], status: 'busy' },
}
queryClient.setQueryData(sessionTranscriptQueryKey(SECOND_SESSION_ID), staleBusy)
rerender({ sessionID: SECOND_SESSION_ID })
await waitFor(() => expect(result.current.status).toBe('idle'))
expect(mocks.readSessionSnapshot).toHaveBeenCalledTimes(2)
expect(mocks.readSessionSnapshot).toHaveBeenLastCalledWith(SECOND_SESSION_ID)
})
it('refreshes a stale cached transcript when the hook remounts', async () => {
const queryClient = createQueryClient()
mocks.readSessionSnapshot.mockResolvedValue({
messages: seededMessages,
pending: [],
status: 'busy',
})
const first = renderHook(() => useSessionTranscript(SESSION_ID, DIRECTORY), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(first.result.current.status).toBe('busy'))
first.unmount()
mocks.readSessionSnapshot.mockResolvedValue({
messages: seededMessages,
pending: [],
status: 'idle',
})
const second = renderHook(() => useSessionTranscript(SESSION_ID, DIRECTORY), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(second.result.current.status).toBe('idle'))
expect(mocks.readSessionSnapshot).toHaveBeenCalledTimes(2)
})
it('applies events buffered during the refresh read triggered by an existing cache', async () => {
const queryClient = createQueryClient()
const settledAssistant: SessionMessageInfo = {
id: ASSISTANT_MESSAGE_ID,
type: 'assistant',
agent: 'build',
model: { id: 'claude-sonnet-4-5', providerID: 'anthropic' },
content: [],
time: { created: 1020, completed: 1030 },
}
queryClient.setQueryData<TranscriptCache>(sessionTranscriptQueryKey(SESSION_ID), {
transcript: {
messages: [seededMessages[0], settledAssistant],
pending: [],
status: 'busy',
},
})
const refreshRead = deferred<SnapshotValue>()
mocks.readSessionSnapshot.mockReturnValueOnce(refreshRead.promise)
const { result } = renderHook(() => useSessionTranscript(SESSION_ID, DIRECTORY), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(mocks.readSessionSnapshot).toHaveBeenCalledTimes(1))
act(() => {
testTransport().message(executionSequence[1])
})
await act(async () => {
refreshRead.resolve({
messages: [seededMessages[0], settledAssistant],
pending: [],
status: 'busy',
})
})
await waitFor(() => expect(result.current.status).toBe('idle'))
expect(mocks.readSessionSnapshot).toHaveBeenCalledTimes(1)
})
it('seeds a queued prompt and a busy session from the snapshot on mount', async () => {
mocks.readSessionSnapshot.mockResolvedValue({
messages: seededMessages,
+4 -1
View File
@@ -83,7 +83,6 @@ export function useSessionTranscript(sessionID: string, directory: string) {
enabled: Boolean(sessionID && directory),
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnMount: 'always',
refetchInterval: isStreamConnected ? false : TRANSCRIPT_FALLBACK_POLL_INTERVAL_MS,
})
@@ -155,6 +154,10 @@ export function useSessionTranscript(sessionID: string, directory: string) {
onResync: refreshNewestPage,
})
if (queryClient.getQueryData<TranscriptCache>(queryKey)) {
refreshNewestPage()
}
return () => {
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current)
+118 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { busyStatusesFromActiveSessions, useSessionStatus } from './sessionStatusStore'
import { busyStatusesFromActiveSessions, hasBackgroundActivity, useSessionStatus } from './sessionStatusStore'
const resetStore = () => {
useSessionStatus.setState({
@@ -8,6 +8,10 @@ const resetStore = () => {
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,
revision: 0,
})
}
@@ -446,4 +450,117 @@ describe('sessionStatusStore', () => {
expect(after.knownSessions.has('child-a')).toBe(false)
expect(after.outcomes.has('child-a')).toBe(false)
})
it('reports background activity when the session owns a running shell', () => {
const store = useSessionStatus.getState()
store.setShellRunning('shell-1', 'session-a', '/repo')
expect(hasBackgroundActivity(useSessionStatus.getState(), 'session-a')).toBe(true)
})
it('reports background activity up the parent chain through a busy descendant', () => {
const store = useSessionStatus.getState()
store.setSessionParent('child', 'parent')
store.setSessionParent('parent', 'grandparent')
store.setStatus('child', { type: 'busy' })
expect(hasBackgroundActivity(useSessionStatus.getState(), 'parent')).toBe(true)
expect(hasBackgroundActivity(useSessionStatus.getState(), 'grandparent')).toBe(true)
})
it('reports no background activity when children are idle', () => {
const store = useSessionStatus.getState()
store.setSessionParent('child', 'parent')
store.setStatus('child', { type: 'idle' })
expect(hasBackgroundActivity(useSessionStatus.getState(), 'parent')).toBe(false)
})
it('does not hang on a parent cycle', () => {
const store = useSessionStatus.getState()
store.setSessionParent('a', 'b')
store.setSessionParent('b', 'a')
expect(hasBackgroundActivity(useSessionStatus.getState(), 'a')).toBe(false)
})
it('replaces running shells only for the given directory', () => {
const store = useSessionStatus.getState()
store.setShellRunning('shell-a', 'session-a', '/repo-a')
store.setShellRunning('shell-b', 'session-b', '/repo-b')
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)
expect(shells.get('shell-c')).toEqual({ sessionID: 'session-c', directory: '/repo-a' })
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')
store.setShellRunning('shell-1', 'child-a', '/repo')
store.forgetSession('child-a')
const after = useSessionStatus.getState()
expect(after.parents.has('child-a')).toBe(false)
expect(after.runningShells.has('shell-1')).toBe(false)
})
})
+202 -1
View File
@@ -13,12 +13,26 @@ interface StatusSnapshotToken {
order: number
}
interface ShellSnapshotToken {
revision: number
order: number
}
interface RunningShell {
sessionID: string
directory: string
}
interface SessionStatusStore {
statuses: Map<string, SessionStatusType>
statusCache: Map<string, string>
statusRevisions: Map<string, number>
knownSessions: Set<string>
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
@@ -30,6 +44,12 @@ interface SessionStatusStore {
endStatusSnapshot: (token: StatusSnapshotToken) => void
getStatus: (sessionID: string) => SessionStatusType
clearStatus: (sessionID: string) => void
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 }>, token: ShellSnapshotToken) => void
beginShellSnapshot: () => ShellSnapshotToken
endShellSnapshot: (token: ShellSnapshotToken) => void
forgetSession: (sessionID: string) => void
}
@@ -39,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)
@@ -70,6 +92,55 @@ const sameSets = (left: Set<string>, right: Set<string>): boolean => {
return true
}
const sameRunningShells = (left: Map<string, RunningShell>, right: Map<string, RunningShell>): boolean => {
if (left.size !== right.size) return false
for (const [shellID, shell] of right.entries()) {
const existing = left.get(shellID)
if (!existing || existing.sessionID !== shell.sessionID || existing.directory !== shell.directory) return false
}
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)
@@ -109,6 +180,28 @@ export function busyStatusesFromActiveSessions(active: Record<string, unknown>):
)
}
export function hasBackgroundActivity(
state: Pick<SessionStatusStore, 'statuses' | 'parents' | 'runningShells'>,
sessionID: string,
): boolean {
const visited = new Set<string>()
const visit = (id: string): boolean => {
if (visited.has(id)) return false
visited.add(id)
for (const shell of state.runningShells.values()) {
if (shell.sessionID === id) return true
}
for (const [childID, parentID] of state.parents.entries()) {
if (parentID !== id) continue
const childStatus = state.statuses.get(childID)
if (childStatus && childStatus.type !== 'idle') return true
if (visit(childID)) return true
}
return false
}
return visit(sessionID)
}
export const useSessionStatus = create<SessionStatusStore>((set, get) => {
const recordRevisionPatch = (
state: SessionStatusStore,
@@ -151,6 +244,10 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,
revision: 0,
setStatus: (sessionID: string, status: SessionStatusType) => {
@@ -341,14 +438,102 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
})
},
setSessionParent: (sessionID: string, parentID: string | null) => {
const current = get().parents
if (current.has(sessionID) && current.get(sessionID) === parentID) return
set((state) => {
const parents = new Map(state.parents)
parents.set(sessionID, parentID)
return { parents }
})
},
setShellRunning: (shellID: string, sessionID: string, directory: string) => {
const current = get().runningShells.get(shellID)
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, ...(shellTouchPatch(state, [shellID]) ?? {}) }
})
},
clearShell: (shellID: string) => {
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, ...(shellTouchPatch(state, [shellID]) ?? {}) }
})
},
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) 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 })
}
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) => {
clearOptimisticActiveTimer(sessionID)
const current = get()
const ownsShell = Array.from(current.runningShells.values()).some((shell) => shell.sessionID === sessionID)
const hasSession =
current.statuses.has(sessionID) ||
current.statusCache.has(sessionID) ||
current.knownSessions.has(sessionID) ||
current.outcomes.has(sessionID)
current.outcomes.has(sessionID) ||
current.parents.has(sessionID) ||
ownsShell
if (!hasSession && inFlightSnapshots.size === 0) return
set((state) => {
@@ -356,15 +541,27 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
const statusCache = new Map(state.statusCache)
const knownSessions = new Set(state.knownSessions)
const outcomes = new Map(state.outcomes)
const parents = new Map(state.parents)
const runningShells = new Map(state.runningShells)
statuses.delete(sessionID)
statusCache.delete(sessionID)
knownSessions.delete(sessionID)
outcomes.delete(sessionID)
parents.delete(sessionID)
const removedShellIDs: string[] = []
for (const [shellID, shell] of runningShells.entries()) {
if (shell.sessionID !== sessionID) continue
runningShells.delete(shellID)
removedShellIDs.push(shellID)
}
return {
statuses,
statusCache,
knownSessions,
outcomes,
parents,
runningShells,
...(shellTouchPatch(state, removedShellIDs) ?? {}),
...(recordRevisionPatch(state, sessionID) ?? {}),
}
})
@@ -385,3 +582,7 @@ export const useChildLifecycleForSession = (sessionID: string | undefined): Back
return childLifecycle(status, state.knownSessions.has(sessionID), state.outcomes.get(sessionID))
})
}
export const useHasBackgroundActivity = (sessionID: string | undefined): boolean => {
return useSessionStatus((state) => (sessionID ? hasBackgroundActivity(state, sessionID) : false))
}