mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(sessions): show background activity for shells and child sessions
This commit is contained in:
1 parent
51e92d8cf2
commit
2e2eff05af
7 files changed
+434
-15
No files matched your search
@@ -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)
|
||||
@@ -1540,7 +1542,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 +1575,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>
|
||||
|
||||
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
|
||||
listPendingPermissions: vi.fn(),
|
||||
listPendingForms: vi.fn(),
|
||||
listActiveSessions: vi.fn(),
|
||||
listShells: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
replyPermission: vi.fn(),
|
||||
replyForm: vi.fn(),
|
||||
cancelForm: vi.fn(),
|
||||
@@ -31,6 +33,8 @@ vi.mock('@/api/opencode', () => ({
|
||||
listActiveSessions: mocks.listActiveSessions,
|
||||
listPendingPermissions: mocks.listPendingPermissions,
|
||||
listPendingForms: mocks.listPendingForms,
|
||||
listShells: mocks.listShells,
|
||||
getSession: mocks.getSession,
|
||||
replyPermission: mocks.replyPermission,
|
||||
replyForm: mocks.replyForm,
|
||||
cancelForm: mocks.cancelForm,
|
||||
@@ -173,11 +177,13 @@ describe('EventProvider permissions and forms', () => {
|
||||
mocks.listPendingPermissions.mockResolvedValue([])
|
||||
mocks.listPendingForms.mockResolvedValue([])
|
||||
mocks.listActiveSessions.mockResolvedValue({})
|
||||
mocks.listShells.mockResolvedValue([])
|
||||
mocks.getSession.mockRejectedValue(new Error('Session not found'))
|
||||
mocks.replyPermission.mockResolvedValue(undefined)
|
||||
mocks.replyForm.mockResolvedValue(undefined)
|
||||
mocks.cancelForm.mockResolvedValue(undefined)
|
||||
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), runningShells: new Map(), revision: 0 })
|
||||
mocks.subscribeGlobalMonitor.mockReturnValue({
|
||||
dispose: vi.fn(),
|
||||
updateDirectories: vi.fn(),
|
||||
@@ -1733,4 +1739,122 @@ describe('EventProvider permissions and forms', () => {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('records the parent of a session created with a parentID', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.created', data: { sessionID: 'child-1', parentID: 'parent-1' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
|
||||
})
|
||||
|
||||
it('tracks a running background shell and clears it when it exits', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'shell.created',
|
||||
data: { info: { id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } } },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.get('shell-1')).toEqual({
|
||||
sessionID: 'session-1',
|
||||
directory: '/repo',
|
||||
})
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'shell.exited', data: { id: 'shell-1', status: 'exited' }, directory: '/repo' })
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('clears a running background shell when it is deleted', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'shell.created',
|
||||
data: { info: { id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } } },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(true)
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'shell.deleted', data: { id: 'shell-1' }, directory: '/repo' })
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('resolves active session ancestry from the snapshot, walking up to a known root', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listActiveSessions.mockResolvedValue({ 'child-1': { type: 'running' } })
|
||||
mocks.getSession.mockImplementation((sessionID: string) => {
|
||||
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
|
||||
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
|
||||
return Promise.reject(new Error('Session not found'))
|
||||
})
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
|
||||
expect(useSessionStatus.getState().parents.get('parent-1')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('populates running shells from the directory snapshot on connect', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listShells.mockResolvedValue([
|
||||
{ id: 'shell-1', status: 'running', metadata: { sessionID: 'session-1' } },
|
||||
{ id: 'shell-2', status: 'exited', metadata: { sessionID: 'session-2' } },
|
||||
])
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo'))
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listShells).toHaveBeenCalledWith('/repo')
|
||||
expect(useSessionStatus.getState().runningShells.get('shell-1')).toEqual({
|
||||
sessionID: 'session-1',
|
||||
directory: '/repo',
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-2')).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,9 +4,11 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useQueryClient, useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
cancelForm,
|
||||
getSession,
|
||||
listActiveSessions,
|
||||
listPendingForms,
|
||||
listPendingPermissions,
|
||||
listShells,
|
||||
replyForm,
|
||||
replyPermission,
|
||||
} from '@/api/opencode'
|
||||
@@ -204,6 +206,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const statusPollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
|
||||
const reposRef = useRef<typeof repos>(null)
|
||||
const ancestryInFlightRef = useRef<Set<string>>(new Set())
|
||||
|
||||
const { data: repos } = useQuery({
|
||||
queryKey: ['repos'],
|
||||
@@ -420,6 +423,52 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
return [...directories]
|
||||
}, [])
|
||||
|
||||
const syncRunningShells = useCallback(async (directories: string[]) => {
|
||||
await Promise.all(directories.map(async (directory) => {
|
||||
try {
|
||||
const shells = await listShells(directory)
|
||||
useSessionStatus.getState().replaceRunningShells(
|
||||
directory,
|
||||
shells.flatMap((shell) => {
|
||||
const sessionID = shell.metadata.sessionID
|
||||
if (shell.status !== 'running' || typeof sessionID !== 'string') return []
|
||||
return [{ id: shell.id, sessionID }]
|
||||
}),
|
||||
)
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to fetch running shells for ${directory}:`, error)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}, [])
|
||||
|
||||
const resolveSessionAncestry = useCallback(async (sessionIDs: string[]) => {
|
||||
const resolveUp = async (startID: string): Promise<void> => {
|
||||
let currentID: string | null = startID
|
||||
while (currentID !== null) {
|
||||
const parents = useSessionStatus.getState().parents
|
||||
if (parents.has(currentID) || ancestryInFlightRef.current.has(currentID)) return
|
||||
const lookupID = currentID
|
||||
ancestryInFlightRef.current.add(lookupID)
|
||||
try {
|
||||
const session = await getSession(lookupID)
|
||||
useSessionStatus.getState().setSessionParent(lookupID, session.parentID ?? null)
|
||||
currentID = session.parentID ?? null
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to resolve session ancestry for ${lookupID}:`, error)
|
||||
}
|
||||
return
|
||||
} finally {
|
||||
ancestryInFlightRef.current.delete(lookupID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.allSettled(sessionIDs.map((sessionID) => resolveUp(sessionID)))
|
||||
}, [])
|
||||
|
||||
const fetchInitialPendingData = useCallback(async () => {
|
||||
const reposToUse = reposRef.current
|
||||
if (!reposToUse || reposToUse.length === 0) return
|
||||
@@ -452,13 +501,17 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
if (becameUnknown.length > 0) {
|
||||
invalidateChildSessionCaches(queryClient, becameUnknown)
|
||||
}
|
||||
const unresolvedSessionIDs = Object.keys(active).filter(
|
||||
(sessionID) => !useSessionStatus.getState().parents.has(sessionID),
|
||||
)
|
||||
await resolveSessionAncestry(unresolvedSessionIDs)
|
||||
} catch (error) {
|
||||
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('Failed to fetch active sessions:', error)
|
||||
}
|
||||
}
|
||||
}, [queryClient])
|
||||
}, [queryClient, resolveSessionAncestry])
|
||||
|
||||
const stopStatusPoll = useCallback(() => {
|
||||
if (statusPollIntervalRef.current === null) return
|
||||
@@ -555,13 +608,40 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
invalidateSessionListCachesDebounced(queryClient, event.directory)
|
||||
break
|
||||
}
|
||||
case 'session.created':
|
||||
case 'session.created': {
|
||||
invalidateSessionListCachesDebounced(queryClient, event.directory)
|
||||
if (typeof event.data.parentID === 'string') {
|
||||
useSessionStatus.getState().setSessionParent(event.data.sessionID, event.data.parentID)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'session.forked':
|
||||
case 'session.renamed':
|
||||
case 'session.moved':
|
||||
case 'session.metadata.updated':
|
||||
invalidateSessionListCachesDebounced(queryClient, event.directory)
|
||||
break
|
||||
case 'shell.created': {
|
||||
const info = event.data.info
|
||||
if (
|
||||
info.status === 'running' &&
|
||||
typeof info.metadata.sessionID === 'string' &&
|
||||
event.directory
|
||||
) {
|
||||
useSessionStatus.getState().setShellRunning(info.id, info.metadata.sessionID, event.directory)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'shell.exited': {
|
||||
if (event.data.status !== 'running') {
|
||||
useSessionStatus.getState().clearShell(event.data.id)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'shell.deleted': {
|
||||
useSessionStatus.getState().clearShell(event.data.id)
|
||||
break
|
||||
}
|
||||
case 'credential.updated':
|
||||
case 'credential.switched':
|
||||
case 'integration.updated':
|
||||
@@ -608,6 +688,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
initialFetchDoneRef.current = false
|
||||
fetchInitialPendingData()
|
||||
fetchInitialSessionStatuses()
|
||||
void syncRunningShells(collectTrackedDirectories())
|
||||
invalidateChildSessionCaches(queryClient)
|
||||
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
|
||||
startStatusPoll()
|
||||
@@ -620,6 +701,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const handleResync = () => {
|
||||
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
|
||||
void fetchInitialSessionStatuses()
|
||||
void syncRunningShells(collectTrackedDirectories())
|
||||
invalidateChildSessionCaches(queryClient)
|
||||
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
|
||||
}
|
||||
@@ -640,7 +722,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
subscription.dispose()
|
||||
subscriptionRef.current = null
|
||||
}
|
||||
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories])
|
||||
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories, syncRunningShells])
|
||||
|
||||
useEffect(() => {
|
||||
reposRef.current = repos
|
||||
|
||||
@@ -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,8 @@ const resetStore = () => {
|
||||
statusRevisions: new Map(),
|
||||
knownSessions: new Set(),
|
||||
outcomes: new Map(),
|
||||
parents: new Map(),
|
||||
runningShells: new Map(),
|
||||
revision: 0,
|
||||
})
|
||||
}
|
||||
@@ -446,4 +448,62 @@ 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')
|
||||
|
||||
store.replaceRunningShells('/repo-a', [{ id: 'shell-c', sessionID: 'session-c' }])
|
||||
|
||||
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('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)
|
||||
})
|
||||
})
|
||||
@@ -13,12 +13,19 @@ interface StatusSnapshotToken {
|
||||
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>
|
||||
revision: number
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => void
|
||||
setOutcome: (sessionID: string, outcome: ChildOutcome) => void
|
||||
@@ -30,6 +37,10 @@ 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 }>) => void
|
||||
forgetSession: (sessionID: string) => void
|
||||
}
|
||||
|
||||
@@ -70,6 +81,15 @@ 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 markSessionKnown = (knownSessions: Set<string>, sessionID: string): Set<string> | null => {
|
||||
if (knownSessions.has(sessionID)) return null
|
||||
const next = new Set(knownSessions)
|
||||
@@ -109,6 +129,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 +193,8 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
statusRevisions: new Map(),
|
||||
knownSessions: new Set(),
|
||||
outcomes: new Map(),
|
||||
parents: new Map(),
|
||||
runningShells: new Map(),
|
||||
revision: 0,
|
||||
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => {
|
||||
@@ -341,14 +385,59 @@ 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) return
|
||||
set((state) => {
|
||||
const runningShells = new Map(state.runningShells)
|
||||
runningShells.set(shellID, { sessionID, directory })
|
||||
return { runningShells }
|
||||
})
|
||||
},
|
||||
|
||||
clearShell: (shellID: string) => {
|
||||
if (!get().runningShells.has(shellID)) return
|
||||
set((state) => {
|
||||
const runningShells = new Map(state.runningShells)
|
||||
runningShells.delete(shellID)
|
||||
return { runningShells }
|
||||
})
|
||||
},
|
||||
|
||||
replaceRunningShells: (directory: string, shells: Array<{ id: string; sessionID: string }>) => {
|
||||
const current = get().runningShells
|
||||
const runningShells = new Map(current)
|
||||
for (const [shellID, shell] of runningShells.entries()) {
|
||||
if (shell.directory === directory) runningShells.delete(shellID)
|
||||
}
|
||||
for (const shell of shells) {
|
||||
runningShells.set(shell.id, { sessionID: shell.sessionID, directory })
|
||||
}
|
||||
if (sameRunningShells(current, runningShells)) return
|
||||
set({ runningShells })
|
||||
},
|
||||
|
||||
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 +445,23 @@ 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)
|
||||
for (const [shellID, shell] of runningShells.entries()) {
|
||||
if (shell.sessionID === sessionID) runningShells.delete(shellID)
|
||||
}
|
||||
return {
|
||||
statuses,
|
||||
statusCache,
|
||||
knownSessions,
|
||||
outcomes,
|
||||
parents,
|
||||
runningShells,
|
||||
...(recordRevisionPatch(state, sessionID) ?? {}),
|
||||
}
|
||||
})
|
||||
@@ -385,3 +482,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))
|
||||
}
|
||||
Reference in new issue
Block a user