fix: stabilize scheduled runs and background task tracking

This commit is contained in:
Chris Scott committed 2026-09-28 20:39:51 +00:00
1 parent 5bd688de4b
commit a75d86c339
25 files changed
+3330 -221

No files matched your search

@@ -9,11 +9,12 @@ type AssistantContentPart = SessionMessageAssistant['content'][number]
interface MessagePartProps {
part: AssistantContentPart
messageID?: string
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
}
export const MessagePart = memo(function MessagePart({ part, messageID, onFileClick, onChildSessionClick }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, messageID, directory, onFileClick, onChildSessionClick }: MessagePartProps) {
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
@@ -40,6 +41,7 @@ export const MessagePart = memo(function MessagePart({ part, messageID, onFileCl
<ToolCallPart
part={part}
messageID={messageID}
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { render as rtlRender, screen, fireEvent } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactElement } from 'react'
import { MessageThread } from './MessageThread'
import { useUIState } from '@/stores/uiStateStore'
import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection'
@@ -47,6 +49,12 @@ vi.mock('@/hooks/useTTS', () => ({
}),
}))
vi.mock('@/api/opencode', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/opencode')>()),
getSession: () => new Promise(() => {}),
listShells: () => Promise.resolve([]),
}))
interface MockSettingsReturn {
preferences: {
simpleChatMode: boolean
@@ -63,6 +71,11 @@ const setupSettings = (preferences: MockSettingsReturn['preferences']) => {
})
}
const render = (ui: ReactElement) => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return rtlRender(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)
}
const project = (events: V2Event[]): SessionMessageInfo[] =>
events.reduce(applySessionEvent, emptySessionTranscript).messages
@@ -479,6 +479,7 @@ const MessageRow = memo(function MessageRow({
<MessagePart
part={part}
messageID={message.id}
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -516,6 +517,7 @@ const MessageRow = memo(function MessageRow({
<MessagePart
part={part}
messageID={message.id}
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -1,10 +1,11 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { act, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import type { PermissionRequest, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { ToolCallPart } from './ToolCallPart'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionStatus } from '@/stores/sessionStatusStore'
const mocks = vi.hoisted(() => ({
useSettings: vi.fn(),
@@ -19,8 +20,13 @@ vi.mock('@/contexts/EventContext', () => ({
useToolCallPermission: mocks.useToolCallPermission,
}))
const renderWithProviders = (ui: React.ReactElement) => {
const queryClient = new QueryClient()
vi.mock('@/api/opencode', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/opencode')>()),
getSession: () => new Promise(() => {}),
listShells: () => Promise.resolve([]),
}))
const renderWithProviders = (ui: React.ReactElement, queryClient = new QueryClient()) => {
return render(
<QueryClientProvider client={queryClient}>
<MemoryRouter>{ui}</MemoryRouter>
@@ -112,6 +118,13 @@ describe('ToolCallPart background indicator', () => {
})
mocks.useToolCallPermission.mockReturnValue(null)
useUserBash.setState({ userBashCommands: new Map() })
useSessionStatus.setState({
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
revision: 0,
})
})
const completedShell = (metadata: Record<string, unknown>): SessionMessageAssistantTool => ({
@@ -127,6 +140,20 @@ describe('ToolCallPart background indicator', () => {
},
})
const completedSubagent = (metadata: Record<string, unknown>): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_3',
name: 'subagent',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { description: 'Explore' },
content: [{ type: 'text', text: 'Task moved to the background (session ID: ses_child).' }],
metadata,
},
})
it('marks a shell call that returned while its command keeps running', () => {
renderWithProviders(<ToolCallPart part={completedShell({ status: 'running', shellID: 'sh_1' })} messageID="msg_1" />)
@@ -147,4 +174,64 @@ describe('ToolCallPart background indicator', () => {
expect(screen.getByText('background')).toBeInTheDocument()
expect(screen.queryByText('✓')).not.toBeInTheDocument()
})
it('clears the background badge once the live shell completes', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{
id: 'sh_1',
status: 'exited',
exit: 0,
command: 'npm run dev',
cwd: '/repo',
shell: 'zsh',
file: '/tmp/sh_1.log',
metadata: { sessionID: 'ses_1' },
time: { started: 1, completed: 2 },
},
])
renderWithProviders(
<ToolCallPart part={completedShell({ status: 'running', shellID: 'sh_1' })} messageID="msg_1" directory="/repo" />,
queryClient,
)
await waitFor(() => expect(screen.queryByText('background')).not.toBeInTheDocument())
expect(screen.getByText('completed')).toBeInTheDocument()
})
it('shows a background shell missing from a loaded list as unavailable', async () => {
renderWithProviders(
<ToolCallPart
part={completedShell({ status: 'running', shellID: 'sh_missing' })}
messageID="msg_1"
directory="/repo"
/>,
)
await waitFor(() => expect(screen.getByText('unavailable')).toBeInTheDocument())
expect(screen.queryByText('background')).not.toBeInTheDocument()
})
it('treats an unknown child session as running, not finished', () => {
renderWithProviders(
<ToolCallPart part={completedSubagent({ status: 'running', sessionID: 'child-unknown' })} messageID="msg_1" />,
)
expect(screen.getByText('background')).toBeInTheDocument()
expect(screen.queryByText('✓')).not.toBeInTheDocument()
})
it('completes a backgrounded subagent when the child session is known idle', async () => {
act(() => {
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
})
renderWithProviders(
<ToolCallPart part={completedSubagent({ status: 'running', sessionID: 'child-1' })} messageID="msg_1" />,
)
await waitFor(() => expect(screen.getByText('✓')).toBeInTheDocument())
expect(screen.queryByText('background')).not.toBeInTheDocument()
})
})
@@ -3,12 +3,24 @@ import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import { toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { useSettings } from '@/hooks/useSettings'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { useChildLifecycleForSession } from '@/stores/sessionStatusStore'
import { useToolCallPermission } from '@/contexts/EventContext'
import { useChildSessionReconciliation } from '@/hooks/useOpenCode'
import { useShell } from '@/hooks/useSessionShells'
import { detectFileReferences } from '@/lib/fileReferences'
import { ExternalLink, Loader2, Shield } from 'lucide-react'
import { ExternalLink, Loader2, Shield, Square } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { CopyButton } from '@/components/ui/copy-button'
import {
backgroundChildSessionID,
backgroundShellID,
isRunningLifecycle,
lifecycleLabel,
shellToolLifecycle,
subagentLifecycle,
toolMetadata,
type BackgroundTaskLifecycle,
} from '@/lib/backgroundWork'
import { getToolSpecificRender } from './FileToolRender'
const DISPLAY_LIMIT = 30_000
@@ -41,6 +53,7 @@ function BoundedPre({ content, className }: { content: string; className: string
interface ToolCallPartProps {
part: SessionMessageAssistantTool
messageID?: string
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
}
@@ -50,11 +63,6 @@ function toolInput(part: SessionMessageAssistantTool): Record<string, unknown> |
return part.state.input
}
function toolMetadata(part: SessionMessageAssistantTool): Record<string, unknown> {
if (part.state.status === 'streaming') return {}
return part.state.metadata ?? {}
}
function toolOutputText(part: SessionMessageAssistantTool): string {
if (part.state.status === 'streaming') return ''
return toolContentText(part.state.status === 'running' ? undefined : part.state.content)
@@ -105,12 +113,28 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
}
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFileClick, onChildSessionClick }: ToolCallPartProps) {
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, onFileClick, onChildSessionClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const isSubagent = part.name === 'subagent'
const subagentSessionId = isSubagent ? getSubagentSessionId(part) : undefined
const subagentSessionStatus = useSessionStatusForSession(subagentSessionId)
const backgroundSubagent = isSubagent ? backgroundChildSessionID(part) : undefined
const subagentSessionLifecycle = useChildLifecycleForSession(subagentSessionId)
useChildSessionReconciliation(
subagentSessionId && (backgroundSubagent !== undefined || part.state.status === 'running')
? subagentSessionId
: undefined,
)
const subagentStatus = subagentLifecycle(
part.state.status,
backgroundSubagent !== undefined,
subagentSessionLifecycle,
)
const backgroundShell = part.name === 'shell' ? backgroundShellID(part) : undefined
const { shell, listLoaded: shellListLoaded } = useShell(backgroundShell, directory)
const shellStatus = shellToolLifecycle(backgroundShell, shell, shellListLoaded)
const isBackgroundShell = backgroundShell !== undefined
const isBackgroundShellRunning = isBackgroundShell && isRunningLifecycle(shellStatus)
const pendingPermission = useToolCallPermission(part.id, messageID)
const isWaitingPermission = part.state.status === 'running' && pendingPermission !== null
const outputRef = useRef<HTMLDivElement>(null)
@@ -138,6 +162,12 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
}, [expanded, part.name])
const getStatusColor = () => {
if (isBackgroundShell) {
if (shellStatus === 'completed') return 'text-success'
if (shellStatus === 'failed') return 'text-destructive'
if (shellStatus === 'killed') return 'text-warning'
return 'text-warning'
}
switch (part.state.status) {
case 'completed':
return 'text-success'
@@ -151,7 +181,15 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
}
}
const renderShellLifecycleIcon = (status: BackgroundTaskLifecycle) => {
if (status === 'completed') return <span className="text-success">✓</span>
if (status === 'failed') return <span className="text-destructive">✗</span>
if (status === 'killed') return <Square className="w-3.5 h-3.5 text-warning" />
return <Loader2 className="w-3.5 h-3.5 animate-spin text-warning" />
}
const getStatusIcon = () => {
if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus)
switch (part.state.status) {
case 'completed':
return <span>✓</span>
@@ -193,7 +231,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit', 'patch'].includes(part.name)
const isBackgrounded = part.state.status === 'completed' && toolMetadata(part).status === 'running'
const isBackgroundSubagent = backgroundSubagent !== undefined
const isBackgroundSubagentRunning = isBackgroundSubagent && isRunningLifecycle(subagentStatus)
const isBackgrounded = isBackgroundShell ? isBackgroundShellRunning : isBackgroundSubagentRunning
const backgroundIndicator = isBackgrounded ? (
<Badge
variant="outline"
@@ -216,9 +256,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
if (isSubagent) {
const status = part.state.status
const isRunning = (status === 'running' || isBackgrounded) && subagentSessionStatus.type !== 'idle'
const isCompleted = !isRunning && (status === 'completed' || (status === 'running' && !!subagentSessionId && subagentSessionStatus.type === 'idle'))
const isError = status === 'error'
const isRunning = status !== 'streaming' && isRunningLifecycle(subagentStatus)
const isCompleted = subagentStatus === 'completed'
const isError = subagentStatus === 'failed'
const description = previewText || 'Sub-agent task'
const content = (
@@ -278,11 +318,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
return (
<div className="my-2">
<div className="flex items-center gap-2 text-sm mb-2">
{isBackgrounded ? (
<Loader2 className="w-3.5 h-3.5 animate-spin text-warning" />
) : (
<span className="text-success">✓</span>
)}
{isBackgroundShell ? renderShellLifecycleIcon(shellStatus) : <span className="text-success">✓</span>}
<span className="font-medium">$</span>
<span className="text-foreground">{command}</span>
{sandboxIndicator}
@@ -347,7 +383,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
) : null}
<span className="text-muted-foreground text-xs ml-auto">{isWaitingPermission ? 'awaiting permission' : part.state.status}</span>
<span className="text-muted-foreground text-xs ml-auto">
{isWaitingPermission ? 'awaiting permission' : isBackgroundShell ? lifecycleLabel(shellStatus) : part.state.status}
</span>
</button>
{expanded && (
@@ -1,13 +1,16 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import type { SessionMessageAssistant, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { ShellInfo } from '@/api/opencode'
import { clearShellExitRecord, recordShellExit } from '@/lib/backgroundWork'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { BackgroundWorkBar } from './BackgroundWorkBar'
const api = vi.hoisted(() => ({
backgroundSession: vi.fn(),
getSession: vi.fn(),
listShells: vi.fn(),
readShellOutput: vi.fn(),
removeShell: vi.fn(),
@@ -50,17 +53,68 @@ const runningShellTool = (): SessionMessageAssistant => ({
time: { created: 1 },
})
function renderBar(messages: SessionMessageInfo[], isSessionActive: boolean) {
const backgroundShellTool = (shellID: string, command = 'npm run dev'): SessionMessageAssistant => ({
id: 'msg-shell',
type: 'assistant',
agent: 'build',
model: { providerID: 'p', id: 'm' },
content: [
{
type: 'tool',
id: 'tool-shell',
name: 'shell',
state: {
status: 'completed',
input: { command },
content: [{ type: 'text', text: 'started in the background' }],
metadata: { status: 'running', shellID },
},
time: { created: 1, completed: 2 },
},
],
time: { created: 1 },
})
const backgroundSubagentTool = (childSessionID: string, description = 'Explore'): SessionMessageAssistant => ({
id: 'msg-sub',
type: 'assistant',
agent: 'build',
model: { providerID: 'p', id: 'm' },
content: [
{
type: 'tool',
id: 'tool-sub',
name: 'subagent',
state: {
status: 'completed',
input: { description },
content: [{ type: 'text', text: 'started in the background' }],
metadata: { status: 'running', sessionID: childSessionID },
},
time: { created: 1, completed: 2 },
},
],
time: { created: 1 },
})
function renderBar(messages: SessionMessageInfo[], isSessionActive: boolean, onChildSessionClick = vi.fn()) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
return {
...render(
<BackgroundWorkBar sessionID="session-1" directory="/repo" messages={messages} isSessionActive={isSessionActive} />,
<BackgroundWorkBar
sessionID="session-1"
directory="/repo"
messages={messages}
isSessionActive={isSessionActive}
onChildSessionClick={onChildSessionClick}
/>,
{ wrapper },
),
queryClient,
onChildSessionClick,
}
}
@@ -68,9 +122,18 @@ describe('BackgroundWorkBar', () => {
beforeEach(() => {
vi.clearAllMocks()
api.listShells.mockResolvedValue([])
api.getSession.mockImplementation(() => new Promise(() => {}))
api.backgroundSession.mockResolvedValue(undefined)
api.removeShell.mockResolvedValue(undefined)
api.readShellOutput.mockResolvedValue({ output: '', cursor: 0, size: 0, truncated: false })
useSessionStatus.setState({
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
revision: 0,
})
})
it('renders nothing when there is no running or background work', async () => {
@@ -93,20 +156,267 @@ describe('BackgroundWorkBar', () => {
expect(screen.queryByRole('button', { name: /Move to background/ })).not.toBeInTheDocument()
})
it('lists only this session\'s running shells and kills one', async () => {
it('keeps this session\'s completed shells visible and marks a killed shell', async () => {
api.listShells.mockResolvedValue([shell('dev'), shell('other', 'session-2'), shell('done', 'session-1', 'exited')])
renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background shell$/ }))
fireEvent.click(await screen.findByRole('button', { name: /2 background tasks$/ }))
expect(screen.getByText('npm run dev')).toBeInTheDocument()
expect(screen.getByText('npm run done')).toBeInTheDocument()
expect(screen.queryByText('npm run other')).not.toBeInTheDocument()
expect(screen.queryByText('npm run done')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Kill npm run dev' }))
await waitFor(() => expect(api.removeShell).toHaveBeenCalledWith('dev', '/repo'))
await waitFor(() => expect(screen.queryByText(/background shell/)).not.toBeInTheDocument())
expect(await screen.findByText('killed')).toBeInTheDocument()
expect(screen.getByText('npm run dev')).toBeInTheDocument()
})
it('updates a shell row from running to completed without removing it', async () => {
api.listShells.mockResolvedValue([shell('dev')])
const { queryClient } = renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(screen.getByText('running')).toBeInTheDocument()
await act(async () => {
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{ ...shell('dev', 'session-1', 'exited'), exit: 0, time: { started: 1, completed: 2 } },
])
})
expect(await screen.findByText('completed')).toBeInTheDocument()
expect(screen.getByText('npm run dev')).toBeInTheDocument()
})
it('preserves a shell created while a stale list fetch was in flight', async () => {
let resolveList: ((value: ShellInfo[]) => void) | undefined
api.listShells.mockImplementation(() => new Promise<ShellInfo[]>((resolve) => { resolveList = resolve }))
const { queryClient } = renderBar([], false)
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
await act(async () => {
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{ ...shell('dev'), time: { started: Date.now() + 60_000 } },
])
})
await act(async () => {
resolveList?.([])
})
expect(await screen.findByRole('button', { name: /1 background task$/ })).toBeInTheDocument()
expect(screen.queryByText('unavailable')).not.toBeInTheDocument()
})
it('marks a running shell omitted from a fresh list as unavailable', async () => {
api.listShells.mockResolvedValue([])
const { queryClient } = renderBar([], false)
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
await act(async () => {
queryClient.setQueryData(['opencode', 'shells', '/repo'], [shell('dev')])
await queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
})
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('unavailable')).toBeInTheDocument()
expect(screen.queryByText('running')).not.toBeInTheDocument()
})
it('does not resurrect a completed shell from a stale list fetch', async () => {
api.listShells.mockResolvedValue([shell('dev')])
const { queryClient } = renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(screen.getByText('running')).toBeInTheDocument()
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{ ...shell('dev', 'session-1', 'exited'), exit: 0, time: { started: 1, completed: 2 } },
])
await act(async () => {
await queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
})
await waitFor(() => expect(screen.getByText('completed')).toBeInTheDocument())
expect(screen.getByText('npm run dev')).toBeInTheDocument()
})
it('shows a backgrounded subagent and completes it when the child goes idle', async () => {
renderBar([backgroundSubagentTool('child-1')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(screen.getByText('Explore')).toBeInTheDocument()
expect(screen.getByText('running')).toBeInTheDocument()
act(() => {
useSessionStatus.getState().setStatus('child-1', { type: 'busy' })
})
expect(screen.getByText('running')).toBeInTheDocument()
act(() => {
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
})
expect(await screen.findByText('completed')).toBeInTheDocument()
expect(screen.getByText('Explore')).toBeInTheDocument()
})
it('treats an unknown child session as still running', async () => {
renderBar([backgroundSubagentTool('child-unknown')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(screen.getByText('running')).toBeInTheDocument()
expect(screen.queryByText('completed')).not.toBeInTheDocument()
})
it('reconciles a child session that finished before it was observed', async () => {
api.getSession.mockResolvedValue({
id: 'child-1',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
outcome: 'succeeded',
time: { created: 1, updated: 2, idle: 2 },
location: { directory: '/repo' },
})
renderBar([backgroundSubagentTool('child-1')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
await waitFor(() => expect(screen.getByText('completed')).toBeInTheDocument())
expect(screen.queryByText('running')).not.toBeInTheDocument()
})
it('shows a failed child session outcome as failed', async () => {
act(() => {
useSessionStatus.getState().setOutcome('child-1', 'failed')
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
})
renderBar([backgroundSubagentTool('child-1')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('failed')).toBeInTheDocument()
expect(screen.queryByText('completed')).not.toBeInTheDocument()
})
it('shows an interrupted child session outcome as interrupted', async () => {
act(() => {
useSessionStatus.getState().setOutcome('child-1', 'interrupted')
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
})
renderBar([backgroundSubagentTool('child-1')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('interrupted')).toBeInTheDocument()
expect(screen.queryByText('completed')).not.toBeInTheDocument()
})
it('keeps a deleted shell visible as unavailable', async () => {
api.listShells.mockResolvedValue([shell('dev')])
const { queryClient } = renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
await act(async () => {
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{ ...shell('dev'), status: 'unavailable', time: { started: 1, completed: 2 } },
])
})
expect(await screen.findByText('unavailable')).toBeInTheDocument()
expect(screen.getByText('npm run dev')).toBeInTheDocument()
expect(screen.queryByText('running')).not.toBeInTheDocument()
})
it('shows a historical shell absent from the fetched list as unavailable', async () => {
api.listShells.mockResolvedValue([])
renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('unavailable')).toBeInTheDocument()
expect(screen.getByText('npm run history')).toBeInTheDocument()
expect(screen.queryByText('running')).not.toBeInTheDocument()
})
it('keeps a historical shell unknown while its list is still loading', async () => {
api.listShells.mockImplementation(() => new Promise(() => {}))
renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(screen.getByText('running')).toBeInTheDocument()
expect(screen.queryByText('unavailable')).not.toBeInTheDocument()
})
it('uses an already cached shell list when the bar remounts', async () => {
const messages = [backgroundShellTool('sh-history', 'npm run history')]
const { queryClient, unmount } = renderBar(messages, false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('unavailable')).toBeInTheDocument()
unmount()
render(
<QueryClientProvider client={queryClient}>
<BackgroundWorkBar sessionID="session-1" directory="/repo" messages={messages} isSessionActive={false} />
</QueryClientProvider>,
)
fireEvent.click(screen.getByRole('button', { name: /1 background task$/ }))
expect(screen.getByText('unavailable')).toBeInTheDocument()
expect(api.listShells).toHaveBeenCalledTimes(1)
})
it('does not overwrite a newer live child status with a stale child query', async () => {
let resolveSession: ((value: unknown) => void) | undefined
api.getSession.mockImplementation(() => new Promise((resolve) => { resolveSession = resolve }))
renderBar([backgroundSubagentTool('child-1')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
act(() => {
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
})
expect(screen.getByText('completed')).toBeInTheDocument()
await act(async () => {
resolveSession?.({
id: 'child-1',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
location: { directory: '/repo' },
})
})
expect(screen.getByText('completed')).toBeInTheDocument()
expect(screen.queryByText('running')).not.toBeInTheDocument()
})
it('applies a shell exit recorded before the list was seeded', async () => {
recordShellExit('/repo', { id: 'sh-seeded', status: 'exited', exit: 0 })
api.listShells.mockResolvedValue([shell('sh-seeded')])
renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('completed')).toBeInTheDocument()
clearShellExitRecord('/repo', 'sh-seeded')
})
it('navigates to a backgrounded subagent session', async () => {
const { onChildSessionClick } = renderBar([backgroundSubagentTool('child-1')], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
fireEvent.click(screen.getByRole('button', { name: 'View Explore' }))
expect(onChildSessionClick).toHaveBeenCalledWith('child-1')
})
it('shows the tail of a background shell output', async () => {
@@ -114,7 +424,7 @@ describe('BackgroundWorkBar', () => {
api.readShellOutput.mockResolvedValue({ output: 'server listening on 3000', cursor: 24, size: 24, truncated: false })
renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background shell$/ }))
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
fireEvent.click(screen.getByRole('button', { name: 'Output' }))
expect(await screen.findByText('server listening on 3000')).toBeInTheDocument()
@@ -136,7 +446,7 @@ describe('BackgroundWorkBar', () => {
})
const { queryClient } = renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background shell$/ }))
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
fireEvent.click(screen.getByRole('button', { name: 'Output' }))
await waitFor(() => expect(calls).toBe(1))
@@ -1,15 +1,26 @@
import { useEffect, useRef, useState } from 'react'
import { ChevronDown, ChevronUp, Loader2, MoveDownRight, Square, Terminal } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { Ban, Bot, Check, ChevronDown, ChevronUp, ExternalLink, Loader2, MoveDownRight, Square, Terminal, XCircle } from 'lucide-react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { readShellOutput, type ShellInfo } from '@/api/opencode'
import { readShellOutput } from '@/api/opencode'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useBackgroundSession } from '@/hooks/useOpenCode'
import { useBackgroundSession, useChildSessionReconciliation } from '@/hooks/useOpenCode'
import { useKillShell, useSessionShells } from '@/hooks/useSessionShells'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import {
BACKGROUNDABLE_TOOLS,
isRunningLifecycle,
lifecycleLabel,
shellBackgroundTasks,
shellLifecycle,
subagentBackgroundTasks,
type BackgroundTask,
type BackgroundTaskLifecycle,
type ShellRecord,
} from '@/lib/backgroundWork'
const SHELL_OUTPUT_LIMIT = 50_000
const SHELL_OUTPUT_POLL_INTERVAL_MS = 1000
const BACKGROUNDABLE_TOOLS = new Set(['shell', 'subagent'])
function hasBackgroundableWork(messages: SessionMessageInfo[]): boolean {
for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -89,7 +100,7 @@ function useShellOutput(shellID: string, directory: string, running: boolean): S
return state
}
function ShellOutputView({ shell, directory, running }: { shell: ShellInfo; directory: string; running: boolean }) {
function ShellOutputView({ shell, directory, running }: { shell: ShellRecord; directory: string; running: boolean }) {
const { output, truncated } = useShellOutput(shell.id, directory, running)
const bottomRef = useRef<HTMLDivElement>(null)
@@ -108,28 +119,121 @@ function ShellOutputView({ shell, directory, running }: { shell: ShellInfo; dire
)
}
function BackgroundTaskStatusIcon({ status }: { status: BackgroundTaskLifecycle }) {
if (status === 'completed') return <Check className="h-3 w-3 text-success" />
if (status === 'failed') return <XCircle className="h-3 w-3 text-destructive" />
if (status === 'interrupted') return <Ban className="h-3 w-3 text-warning" />
if (status === 'killed') return <Square className="h-3 w-3 text-warning" />
if (status === 'unavailable') return <XCircle className="h-3 w-3 text-muted-foreground" />
return <Loader2 className="h-3 w-3 animate-spin text-warning" />
}
function BackgroundTaskKindIcon({ task }: { task: BackgroundTask }) {
return task.kind === 'shell'
? <Terminal className="h-3 w-3 shrink-0 text-success" />
: <Bot className="h-3 w-3 shrink-0 text-info" />
}
function BackgroundTaskReconciler({ sessionID }: { sessionID: string }) {
useChildSessionReconciliation(sessionID)
return null
}
function BackgroundTaskRow({
task,
killShell,
onChildSessionClick,
onView,
}: {
task: BackgroundTask
killShell: ReturnType<typeof useKillShell>
onChildSessionClick?: (sessionId: string) => void
onView: (shell: ShellRecord) => void
}) {
return (
<li className="flex flex-wrap items-center gap-2 border-b border-border px-2 py-1 last:border-b-0">
<BackgroundTaskKindIcon task={task} />
<span className="min-w-0 flex-1 truncate font-mono" title={task.label}>{task.label}</span>
<span className="flex items-center gap-1 text-muted-foreground">
<BackgroundTaskStatusIcon status={task.status} />
{lifecycleLabel(task.status)}
</span>
{task.kind === 'shell' && task.shell && (
<Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => onView(task.shell!)}>
Output
</Button>
)}
{task.kind === 'shell' && task.status === 'running' && task.shell && (
<Button
variant="ghost"
size="sm"
className="h-6 gap-1 px-2 text-xs text-destructive hover:text-destructive"
disabled={killShell.isPending && killShell.variables === task.shell.id}
onClick={() => killShell.mutate(task.shell!.id)}
aria-label={`Kill ${task.label}`}
>
<Square className="h-3 w-3" />
Kill
</Button>
)}
{task.kind === 'subagent' && task.childSessionID && onChildSessionClick && (
<Button
variant="ghost"
size="sm"
className="h-6 gap-1 px-2 text-xs"
onClick={() => onChildSessionClick(task.childSessionID!)}
aria-label={`View ${task.label}`}
>
<ExternalLink className="h-3 w-3" />
View
</Button>
)}
</li>
)
}
interface BackgroundWorkBarProps {
sessionID: string
directory: string
messages: SessionMessageInfo[]
isSessionActive: boolean
onChildSessionClick?: (sessionId: string) => void
}
export function BackgroundWorkBar({ sessionID, directory, messages, isSessionActive }: BackgroundWorkBarProps) {
const shells = useSessionShells(sessionID, directory)
export function BackgroundWorkBar({ sessionID, directory, messages, isSessionActive, onChildSessionClick }: BackgroundWorkBarProps) {
const { shells, listLoaded } = useSessionShells(sessionID, directory)
const statuses = useSessionStatus((state) => state.statuses)
const knownSessions = useSessionStatus((state) => state.knownSessions)
const outcomes = useSessionStatus((state) => state.outcomes)
const killShell = useKillShell(directory)
const backgroundSession = useBackgroundSession()
const [expanded, setExpanded] = useState(false)
const [viewing, setViewing] = useState<ShellInfo | null>(null)
const [viewing, setViewing] = useState<ShellRecord | null>(null)
const tasks = useMemo(
() => [
...shellBackgroundTasks(shells, messages, listLoaded),
...subagentBackgroundTasks(messages, statuses, knownSessions, outcomes),
],
[shells, messages, listLoaded, statuses, knownSessions, outcomes],
)
const hasRunningTask = tasks.some((task) => isRunningLifecycle(task.status))
const canBackground = isSessionActive && hasBackgroundableWork(messages)
const viewingRunning = viewing !== null && shells.some((shell) => shell.id === viewing.id)
const liveViewingShell = viewing ? shells.find((shell) => shell.id === viewing.id) : undefined
const viewingShell = liveViewingShell ?? viewing
const viewingRunning = liveViewingShell !== undefined && isRunningLifecycle(shellLifecycle(liveViewingShell))
if (!canBackground && shells.length === 0 && viewing === null) return null
if (!canBackground && tasks.length === 0 && viewing === null) return null
return (
<div className="mb-1 flex flex-col gap-1 px-1 text-xs">
<div className="flex items-center gap-2">
{tasks.map((task) =>
task.kind === 'subagent' && task.childSessionID ? (
<BackgroundTaskReconciler key={`reconcile:${task.id}`} sessionID={task.childSessionID} />
) : null,
)}
<div className="flex flex-wrap items-center gap-2">
{canBackground && (
<Button
variant="outline"
@@ -143,41 +247,32 @@ export function BackgroundWorkBar({ sessionID, directory, messages, isSessionAct
Move to background
</Button>
)}
{shells.length > 0 && (
{tasks.length > 0 && (
<button
type="button"
onClick={() => setExpanded((value) => !value)}
className="ml-auto flex items-center gap-1 rounded-md border border-border bg-card/60 px-2 py-1 text-muted-foreground hover:text-foreground"
aria-expanded={expanded}
>
<Loader2 className="h-3 w-3 animate-spin text-warning" />
{shells.length} background shell{shells.length === 1 ? '' : 's'}
{hasRunningTask
? <Loader2 className="h-3 w-3 animate-spin text-warning" />
: <Check className="h-3 w-3 text-success" />}
{tasks.length} background task{tasks.length === 1 ? '' : 's'}
{expanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
)}
</div>
{expanded && shells.length > 0 && (
{expanded && tasks.length > 0 && (
<ul className="rounded-md border border-border bg-card/60">
{shells.map((shell) => (
<li key={shell.id} className="flex items-center gap-2 border-b border-border px-2 py-1 last:border-b-0">
<Terminal className="h-3 w-3 shrink-0 text-success" />
<span className="min-w-0 flex-1 truncate font-mono" title={shell.command}>{shell.command}</span>
<Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setViewing(shell)}>
Output
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 gap-1 px-2 text-xs text-destructive hover:text-destructive"
disabled={killShell.isPending && killShell.variables === shell.id}
onClick={() => killShell.mutate(shell.id)}
aria-label={`Kill ${shell.command}`}
>
<Square className="h-3 w-3" />
Kill
</Button>
</li>
{tasks.map((task) => (
<BackgroundTaskRow
key={`${task.kind}:${task.id}`}
task={task}
killShell={killShell}
onChildSessionClick={onChildSessionClick}
onView={setViewing}
/>
))}
</ul>
)}
@@ -185,10 +280,12 @@ export function BackgroundWorkBar({ sessionID, directory, messages, isSessionAct
<Dialog open={viewing !== null} onOpenChange={(open) => { if (!open) setViewing(null) }}>
<DialogContent className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle className="truncate font-mono text-sm">{viewing?.command}</DialogTitle>
<DialogDescription>{viewingRunning ? 'Running in the background' : 'Finished'}</DialogDescription>
<DialogTitle className="truncate font-mono text-sm">{viewingShell?.command ?? viewing?.command}</DialogTitle>
<DialogDescription>
{viewingRunning ? 'Running in the background' : liveViewingShell === undefined ? 'Status unavailable' : 'Finished'}
</DialogDescription>
</DialogHeader>
{viewing && <ShellOutputView key={viewing.id} shell={viewing} directory={directory} running={viewingRunning} />}
{viewingShell && <ShellOutputView key={viewingShell.id} shell={viewingShell} directory={directory} running={viewingRunning} />}
</DialogContent>
</Dialog>
</div>
+126 -1
View File
@@ -169,7 +169,7 @@ describe('EventProvider permissions and forms', () => {
mocks.replyForm.mockResolvedValue(undefined)
mocks.cancelForm.mockResolvedValue(undefined)
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
@@ -1014,6 +1014,131 @@ describe('EventProvider permissions and forms', () => {
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' })
})
it('marks a child session as known from its execution lifecycle events', 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.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(true)
expect(useSessionStatus.getState().isSessionKnown('child-unknown')).toBe(false)
})
it('does not treat a child omitted from a global snapshot as finished', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({})
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
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
act(() => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'busy' })
act(() => {
onResync?.()
})
await waitFor(() => {
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(false)
})
})
it('records a failed child outcome and preserves it when the child goes idle', 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.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
act(() => {
onEvent({ type: 'session.idle', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
})
it('records an interrupted child outcome', 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.execution.interrupted', data: { sessionID: 'child-1', reason: 'user' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('interrupted')
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
})
it('does not turn a failed child into completed across a reconnect snapshot', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({})
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
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
act(() => {
handleStatusChange(true)
})
await waitFor(() => {
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(true)
})
})
it('clears a previous child outcome when a new execution starts', 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.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' })
onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBeUndefined()
})
it('reconciles the global active snapshot on reconnect and clears omitted sessions', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({ 'session-other': { type: 'running' } })
+18 -2
View File
@@ -18,6 +18,7 @@ import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
invalidateChildSessionCaches,
invalidateProviderCachesDebounced,
invalidateQueryKeysDebounced,
invalidateRepoGitCachesDebounced,
@@ -469,12 +470,24 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
break
}
case 'session.execution.started': {
useSessionStatus.getState().clearOutcome(event.data.sessionID)
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'busy' })
break
}
case 'session.execution.succeeded':
case 'session.execution.failed':
case 'session.execution.succeeded': {
useSessionStatus.getState().setOutcome(event.data.sessionID, 'succeeded')
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
}
case 'session.execution.failed': {
useSessionStatus.getState().setOutcome(event.data.sessionID, 'failed')
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
}
case 'session.execution.interrupted': {
useSessionStatus.getState().setOutcome(event.data.sessionID, 'interrupted')
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
@@ -529,6 +542,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
initialFetchDoneRef.current = false
fetchInitialPendingData()
fetchInitialSessionStatuses()
invalidateChildSessionCaches(queryClient)
startStatusPoll()
} else {
statusSyncVersionRef.current += 1
@@ -538,6 +552,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const handleResync = () => {
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
void fetchInitialSessionStatuses()
invalidateChildSessionCaches(queryClient)
}
const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))]
+93 -1
View File
@@ -3,14 +3,16 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import { useCreateSession, useDeleteSession, useSession, useSessionsAcrossDirectories } from './useOpenCode'
import { useChildSessionReconciliation, useCreateSession, useDeleteSession, useSession, useSessionsAcrossDirectories } from './useOpenCode'
import { FetchError } from '../api/fetchWrapper'
import { showToast } from '../lib/toast'
import { useSessionStatus } from '../stores/sessionStatusStore'
const mocks = vi.hoisted(() => ({
listSessionPage: vi.fn(),
deleteSession: vi.fn(),
createSession: vi.fn(),
getSession: vi.fn(),
}))
vi.mock('../lib/toast', () => ({
@@ -22,11 +24,13 @@ vi.mock('../lib/toast', () => ({
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
mocks.getSession.mockImplementation(actual.getSession)
return {
...actual,
listSessionPage: mocks.listSessionPage,
deleteSession: mocks.deleteSession,
createSession: mocks.createSession,
getSession: mocks.getSession,
}
})
@@ -218,3 +222,91 @@ describe('useCreateSession', () => {
expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/w/a', agent: undefined })
})
})
describe('useChildSessionReconciliation', () => {
beforeEach(() => {
mocks.getSession.mockReset()
useSessionStatus.setState({
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
revision: 0,
})
})
const idleSession = (): SessionInfo => ({
...sessionInfo('child-1', '/repo'),
time: { created: 1000, updated: 2000, idle: 2000 },
})
it('applies one guarded snapshot for multiple observers sharing one fetch', async () => {
let resolveSession: ((value: SessionInfo) => void) | undefined
mocks.getSession.mockImplementation(
() => new Promise<SessionInfo>((resolve) => { resolveSession = resolve }),
)
const queryClient = createQueryClient()
const wrapper = createWrapper(queryClient)
const first = renderHook(() => useChildSessionReconciliation('child-1'), { wrapper })
const second = renderHook(() => useChildSessionReconciliation('child-1'), { wrapper })
await waitFor(() => expect(mocks.getSession).toHaveBeenCalledTimes(1))
await act(async () => {
resolveSession?.(idleSession())
})
expect(mocks.getSession).toHaveBeenCalledTimes(1)
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(true)
first.unmount()
second.unmount()
})
it('releases the snapshot when unmounted while the request is pending', async () => {
let resolveSession: ((value: SessionInfo) => void) | undefined
mocks.getSession.mockImplementation(
() => new Promise<SessionInfo>((resolve) => { resolveSession = resolve }),
)
const queryClient = createQueryClient()
const wrapper = createWrapper(queryClient)
const { unmount } = renderHook(() => useChildSessionReconciliation('child-1'), { wrapper })
await waitFor(() => expect(mocks.getSession).toHaveBeenCalledTimes(1))
act(() => {
useSessionStatus.getState().setStatus('child-1', { type: 'busy' })
})
expect(useSessionStatus.getState().statusRevisions.size).toBeGreaterThan(0)
unmount()
await act(async () => {
resolveSession?.(idleSession())
})
await waitFor(() => expect(useSessionStatus.getState().statusRevisions.size).toBe(0))
})
it('clears a stale child outcome when the fresh snapshot is busy', async () => {
mocks.getSession.mockResolvedValue({
...sessionInfo('child-1', '/repo'),
outcome: 'failed',
})
useSessionStatus.getState().setOutcome('child-1', 'failed')
const queryClient = createQueryClient()
renderHook(() => useChildSessionReconciliation('child-1'), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => {
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'busy' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBeUndefined()
})
})
+22 -1
View File
@@ -24,7 +24,7 @@ import { parseNetworkError, isGatewayTimeout } from "../lib/opencode-errors";
import { showToast } from "../lib/toast";
import { useSendErrorStore } from "../stores/sendErrorStore";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation";
import { childSessionReconciliationQueryKey, invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation";
import { buildPinnedSessionKeys, buildSessionKey } from "../lib/sessionKey";
import { toggleSessionPin } from "../api/sessionPins";
import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
@@ -147,6 +147,27 @@ export const useSession = (sessionID: string | undefined, directory?: string) =>
return useQuery(sessionQueryOptions(sessionID, directory));
};
export const useChildSessionReconciliation = (sessionID: string | undefined) => {
useQuery({
queryKey: childSessionReconciliationQueryKey(sessionID),
queryFn: async () => {
const token = useSessionStatus.getState().beginStatusSnapshot();
try {
const session = await getSession(sessionID!);
useSessionStatus.getState().applySessionSnapshot(sessionID!, session, token);
return session;
} finally {
useSessionStatus.getState().endStatusSnapshot(token);
}
},
enabled: !!sessionID,
staleTime: 0,
refetchOnMount: 'always',
refetchOnReconnect: true,
refetchOnWindowFocus: true,
});
};
export const useCreateSession = (
directory?: string,
onSuccess?: (session: { id: string }) => void,
+134 -7
View File
@@ -53,14 +53,14 @@ describe('useSSE', () => {
beforeEach(() => {
vi.clearAllMocks()
MockEventSource.instances = []
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
})
afterEach(() => {
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = originalEventSource
globalThis.fetch = originalFetch
@@ -119,6 +119,8 @@ describe('useSSE', () => {
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: ['opencode', 'pending-actions', 'session-1', '/repo'],
})
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'shells'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'] })
})
unmount()
@@ -357,11 +359,12 @@ describe('useSSE', () => {
queryKey: ['opencode', 'pending-actions', 'session-1', '/repo'],
})
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'shells'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'] })
unmount()
})
it('tracks background shells from shell lifecycle events', async () => {
it('tracks background shells from shell lifecycle events without dropping completed shells', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -401,18 +404,142 @@ describe('useSSE', () => {
})
})
expect(queryClient.getQueryData<Array<{ id: string }>>(['opencode', 'shells', '/repo'])?.map((shell) => shell.id))
.toEqual(['shell-2'])
const shells = queryClient.getQueryData<Array<{ id: string; status: string; time: { completed?: number } }>>(
['opencode', 'shells', '/repo'],
)
expect(shells?.map((shell) => shell.id)).toEqual(['shell-1', 'shell-2'])
expect(shells?.[0]?.status).toBe('exited')
expect(shells?.[0]?.time.completed).toBeDefined()
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'shell.deleted',
directory: '/repo',
data: { id: 'shell-2' },
data: { id: 'shell-1' },
})
})
expect(queryClient.getQueryData(['opencode', 'shells', '/repo'])).toEqual([])
const afterDelete = queryClient.getQueryData<Array<{ id: string; status: string }>>(['opencode', 'shells', '/repo'])
expect(afterDelete?.map((shell) => shell.id)).toEqual(['shell-1', 'shell-2'])
expect(afterDelete?.[0]?.status).toBe('exited')
unmount()
})
it('keeps a deleted running shell visible as unavailable', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{
id: 'shell-1',
status: 'running',
command: 'sleep 1',
cwd: '/repo',
shell: 'zsh',
file: '/tmp/shell-1.log',
metadata: { sessionID: 'session-1' },
time: { started: 1 },
},
])
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'shell.deleted',
directory: '/repo',
data: { id: 'shell-1' },
})
})
expect(
queryClient.getQueryData<Array<{ id: string; status: string }>>(['opencode', 'shells', '/repo'])?.[0],
).toMatchObject({ id: 'shell-1', status: 'unavailable' })
unmount()
})
it('does not discard a shell exit that arrives before the cache is seeded', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
invalidateQueries.mockClear()
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'shell.exited',
directory: '/repo',
data: { id: 'shell-1', exit: 0, status: 'exited' },
})
})
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'shells', '/repo'] })
unmount()
})
it('does not resurrect a completed shell from a stale created event', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const shell = (status: string) => ({
id: 'shell-1',
status,
command: 'sleep 1',
cwd: '/repo',
shell: 'zsh',
file: '/tmp/shell-1.log',
metadata: { sessionID: 'session-1' },
time: { started: 1 },
})
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
{ ...shell('exited'), exit: 0, time: { started: 1, completed: 2 } },
])
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'shell.created',
directory: '/repo',
data: { info: shell('running') },
})
})
expect(
queryClient.getQueryData<Array<{ id: string; status: string }>>(['opencode', 'shells', '/repo'])?.[0]?.status,
).toBe('exited')
unmount()
})
+36 -10
View File
@@ -1,12 +1,19 @@
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { SessionInfo, V2Event } from '@opencode-manager/shared/opencode'
import { invalidateSessionListCaches, shellsQueryKey } from '@/lib/queryInvalidation'
import { invalidateChildSessionCaches, invalidateSessionListCaches, shellsQueryKey } from '@/lib/queryInvalidation'
import {
applyShellExit,
markShellDeleted,
recordShellDeleted,
recordShellExit,
upsertShell,
type ShellRecord,
} from '@/lib/backgroundWork'
import { showToast } from '@/lib/toast'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { openCodeEventStream } from '@/lib/opencode-event-stream'
import type { EventStreamSubscription } from '@/lib/opencode-event-stream'
import type { ShellInfo } from '@/api/opencode'
type V2StreamEvent = V2Event & { directory?: string }
@@ -109,18 +116,34 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
case 'shell.created': {
const info = event.data.info
queryClient.setQueryData<ShellInfo[]>(shellsQueryKey(cacheDirectory), (current) =>
current ? [...current.filter((shell) => shell.id !== info.id), info] : current,
)
const key = shellsQueryKey(cacheDirectory)
const current = queryClient.getQueryData<ShellRecord[]>(key)
if (!current) {
queryClient.invalidateQueries({ queryKey: key })
break
}
queryClient.setQueryData<ShellRecord[]>(key, (shells) => upsertShell(shells ?? [], info, cacheDirectory ?? ''))
break
}
case 'shell.exited': {
recordShellExit(cacheDirectory ?? '', event.data)
const key = shellsQueryKey(cacheDirectory)
const current = queryClient.getQueryData<ShellRecord[]>(key)
if (!current || !current.some((shell) => shell.id === event.data.id)) {
queryClient.invalidateQueries({ queryKey: key })
break
}
queryClient.setQueryData<ShellRecord[]>(key, (shells) => applyShellExit(shells ?? [], event.data))
break
}
case 'shell.exited':
case 'shell.deleted': {
const id = event.data.id
queryClient.setQueryData<ShellInfo[]>(shellsQueryKey(cacheDirectory), (current) =>
current?.filter((shell) => shell.id !== id),
)
recordShellDeleted(cacheDirectory ?? '', event.data.id)
const key = shellsQueryKey(cacheDirectory)
const current = queryClient.getQueryData<ShellRecord[]>(key)
if (!current || !current.some((shell) => shell.id === event.data.id)) break
queryClient.setQueryData<ShellRecord[]>(key, (shells) => markShellDeleted(shells ?? [], event.data.id))
break
}
@@ -178,6 +201,8 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
if (connected) {
setError(null)
syncCurrentSession()
queryClient.invalidateQueries({ queryKey: ['opencode', 'shells'] })
invalidateChildSessionCaches(queryClient)
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
} else {
setError('Connection lost. Reconnecting...')
@@ -188,6 +213,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
if (!mountedRef.current) return
invalidateSessionListCaches(queryClient)
queryClient.invalidateQueries({ queryKey: ['opencode', 'shells'] })
invalidateChildSessionCaches(queryClient)
refreshCurrentSession()
}
+40 -12
View File
@@ -1,26 +1,50 @@
import { useMemo } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { listShells, removeShell, type ShellInfo } from '@/api/opencode'
import { listShells, removeShell } from '@/api/opencode'
import { reconcileShellList, type ShellRecord } from '@/lib/backgroundWork'
import { shellsQueryKey } from '@/lib/queryInvalidation'
import { showToast } from '@/lib/toast'
export function useSessionShells(sessionID: string | undefined, directory: string | undefined) {
const query = useQuery({
function useShellListQuery(directory: string | undefined, enabled: boolean) {
const queryClient = useQueryClient()
return useQuery({
queryKey: shellsQueryKey(directory),
queryFn: () => listShells(directory ?? ''),
enabled: Boolean(directory),
queryFn: async () => {
const fetchStartedAt = Date.now()
const fetched = await listShells(directory ?? '')
const existing = queryClient.getQueryData<ShellRecord[]>(shellsQueryKey(directory)) ?? []
return reconcileShellList(existing, fetched, fetchStartedAt, directory ?? '')
},
enabled,
staleTime: Infinity,
})
}
export function useSessionShells(sessionID: string | undefined, directory: string | undefined) {
const query = useShellListQuery(directory, Boolean(directory))
const shells = useMemo(
() =>
(query.data ?? []).filter(
(shell) => shell.status === 'running' && shell.metadata.sessionID === sessionID,
),
() => (query.data ?? []).filter((shell) => shell.metadata.sessionID === sessionID),
[query.data, sessionID],
)
return shells
const listLoaded = query.isSuccess
return { shells, listLoaded }
}
export function useShell(shellID: string | undefined, directory: string | undefined) {
const query = useShellListQuery(directory, Boolean(directory && shellID))
const shell = useMemo(
() => (query.data ?? []).find((candidate) => candidate.id === shellID),
[query.data, shellID],
)
const listLoaded = query.isSuccess
return { shell, listLoaded }
}
export function useKillShell(directory: string | undefined) {
@@ -29,8 +53,12 @@ export function useKillShell(directory: string | undefined) {
return useMutation({
mutationFn: (id: string) => removeShell(id, directory ?? ''),
onSuccess: (_result, id) => {
queryClient.setQueryData<ShellInfo[]>(shellsQueryKey(directory), (current) =>
current?.filter((shell) => shell.id !== id),
queryClient.setQueryData<ShellRecord[]>(shellsQueryKey(directory), (current) =>
current?.map((shell) =>
shell.id === id
? { ...shell, status: 'killed', time: { ...shell.time, completed: shell.time.completed ?? Date.now() } }
: shell,
),
)
},
onError: (error) => {
+248
View File
@@ -0,0 +1,248 @@
import { describe, expect, it } from 'vitest'
import {
applyShellExit,
childLifecycle,
clearShellExitRecord,
isRunningLifecycle,
markShellDeleted,
reconcileShellList,
recordShellDeleted,
recordShellExit,
shellLifecycle,
shellToolLifecycle,
subagentLifecycle,
upsertShell,
type ShellRecord,
} from './backgroundWork'
const shell = (id: string, status: ShellRecord['status'], exit?: number, started = 1): ShellRecord => ({
id,
status,
command: `npm run ${id}`,
cwd: '/repo',
shell: 'zsh',
file: `/tmp/${id}.log`,
metadata: { sessionID: 'session-1' },
time: { started, ...(exit === undefined ? {} : { completed: started + 1 }) },
...(exit === undefined ? {} : { exit }),
})
describe('shellLifecycle', () => {
it('maps every shell status to a lifecycle state', () => {
expect(shellLifecycle(shell('a', 'running'))).toBe('running')
expect(shellLifecycle(shell('b', 'exited', 0))).toBe('completed')
expect(shellLifecycle(shell('c', 'exited', 1))).toBe('failed')
expect(shellLifecycle(shell('d', 'timeout'))).toBe('failed')
expect(shellLifecycle(shell('e', 'killed'))).toBe('killed')
expect(shellLifecycle(shell('f', 'unavailable'))).toBe('unavailable')
})
it('treats an exited shell without an exit code as completed', () => {
expect(shellLifecycle(shell('a', 'exited'))).toBe('completed')
})
it('never treats a missing shell as completed', () => {
expect(shellLifecycle(undefined)).toBe('unknown')
expect(isRunningLifecycle(shellLifecycle(undefined))).toBe(true)
})
})
describe('childLifecycle', () => {
it('never treats an unknown child as finished', () => {
expect(childLifecycle({ type: 'idle' }, false, undefined)).toBe('unknown')
})
it('maps a known child status to a lifecycle state', () => {
expect(childLifecycle({ type: 'idle' }, true, undefined)).toBe('completed')
expect(childLifecycle({ type: 'idle' }, true, 'succeeded')).toBe('completed')
expect(childLifecycle({ type: 'idle' }, true, 'failed')).toBe('failed')
expect(childLifecycle({ type: 'idle' }, true, 'interrupted')).toBe('interrupted')
expect(childLifecycle({ type: 'busy' }, true, undefined)).toBe('running')
expect(childLifecycle({ type: 'compact' }, true, undefined)).toBe('running')
expect(childLifecycle({ type: 'retry', attempt: 1, message: 'retry', next: 2 }, true, undefined)).toBe('running')
})
})
describe('subagentLifecycle', () => {
it('fails on a tool error', () => {
expect(subagentLifecycle('error', false, 'completed')).toBe('failed')
})
it('keeps an unknown backgrounded child running', () => {
expect(subagentLifecycle('completed', true, 'unknown')).toBe('unknown')
})
it('completes a backgrounded child once its status is known idle', () => {
expect(subagentLifecycle('completed', true, 'completed')).toBe('completed')
})
it('reports a failed backgrounded child as failed', () => {
expect(subagentLifecycle('completed', true, 'failed')).toBe('failed')
})
it('reports an interrupted backgrounded child as interrupted', () => {
expect(subagentLifecycle('completed', true, 'interrupted')).toBe('interrupted')
})
it('completes a foreground subagent whose child is known idle', () => {
expect(subagentLifecycle('running', false, 'completed')).toBe('completed')
})
it('keeps a foreground subagent running while its child status is unknown', () => {
expect(subagentLifecycle('running', false, 'unknown')).toBe('running')
})
})
describe('shellToolLifecycle', () => {
it('reports a non-background shell call as completed', () => {
expect(shellToolLifecycle(undefined, undefined, true)).toBe('completed')
})
it('reports a background shell from its live status', () => {
expect(shellToolLifecycle('sh_1', shell('sh_1', 'killed'), true)).toBe('killed')
})
it('keeps a shell unknown until the list loads, then unavailable when absent', () => {
expect(shellToolLifecycle('sh_1', undefined, false)).toBe('unknown')
expect(shellToolLifecycle('sh_1', undefined, true)).toBe('unavailable')
})
})
describe('reconcileShellList', () => {
it('preserves a terminal shell when a stale list reports it running', () => {
const cached = shell('a', 'exited', 0)
const fetched = shell('a', 'running')
expect(reconcileShellList([cached], [fetched], 100, '/repo')).toEqual([cached])
})
it('accepts a terminal status from the list', () => {
const fetched = shell('a', 'exited', 0)
expect(reconcileShellList([shell('a', 'running')], [fetched], 100, '/repo')).toEqual([fetched])
})
it('preserves a running shell created after a stale fetch started', () => {
const cached = shell('a', 'running', undefined, 200)
expect(reconcileShellList([cached], [], 100, '/repo')).toEqual([cached])
})
it('preserves terminal history omitted from a fresh fetch', () => {
const cached = shell('a', 'exited', 0, 50)
expect(reconcileShellList([cached], [], 100, '/repo')).toEqual([cached])
})
it('marks a running shell omitted from a fresh fetch as unavailable', () => {
const cached = shell('a', 'running', undefined, 50)
const [result] = reconcileShellList([cached], [], 100, '/repo')
expect(result?.status).toBe('unavailable')
expect(result?.time.completed).toBeDefined()
})
it('applies a shell exit recorded before the list was seeded', () => {
recordShellExit('/repo', { id: 'a', status: 'exited', exit: 0 })
const [result] = reconcileShellList([], [shell('a', 'running')], 100, '/repo')
expect(result?.status).toBe('exited')
expect(result?.exit).toBe(0)
clearShellExitRecord('/repo', 'a')
})
it('applies a shell deletion recorded before the list was seeded', () => {
recordShellDeleted('/repo', 'a')
const [result] = reconcileShellList([], [shell('a', 'running')], 100, '/repo')
expect(result?.status).toBe('unavailable')
clearShellExitRecord('/repo', 'a')
})
it('does not apply a shell exit recorded for another directory', () => {
recordShellExit('/other', { id: 'a', status: 'exited', exit: 0 })
const [result] = reconcileShellList([], [shell('a', 'running')], 100, '/repo')
expect(result?.status).toBe('running')
clearShellExitRecord('/other', 'a')
})
})
describe('upsertShell', () => {
it('does not downgrade a terminal shell to running', () => {
const cached = shell('a', 'exited', 0)
expect(upsertShell([cached], shell('a', 'running'), '/repo')).toEqual([cached])
})
it('does not downgrade an unavailable shell to running', () => {
const cached = shell('a', 'unavailable')
expect(upsertShell([cached], shell('a', 'running'), '/repo')).toEqual([cached])
})
it('does not resurrect a shell deleted before the cache was seeded', () => {
recordShellDeleted('/repo', 'a')
const [result] = upsertShell([], shell('a', 'running'), '/repo')
expect(result?.status).toBe('unavailable')
clearShellExitRecord('/repo', 'a')
})
it('replaces a running shell with the latest info', () => {
const next = shell('a', 'exited', 0)
expect(upsertShell([shell('a', 'running')], next, '/repo')).toEqual([next])
})
it('appends a newly created shell', () => {
expect(upsertShell([shell('a', 'running')], shell('b', 'running'), '/repo').map((item) => item.id)).toEqual(['a', 'b'])
})
})
describe('applyShellExit', () => {
it('marks a matching shell terminal and records its completion', () => {
const [result] = applyShellExit([shell('a', 'running')], { id: 'a', status: 'exited', exit: 0 })
expect(result?.status).toBe('exited')
expect(result?.exit).toBe(0)
expect(result?.time.completed).toBeDefined()
})
it('does not turn an unavailable shell back into running', () => {
const [result] = applyShellExit([shell('a', 'unavailable')], { id: 'a', status: 'running' })
expect(result?.status).toBe('unavailable')
})
it('leaves unrelated shells untouched', () => {
const other = shell('b', 'running')
const [result] = applyShellExit([other], { id: 'a', status: 'killed' })
expect(result).toBe(other)
})
})
describe('markShellDeleted', () => {
it('keeps the shell visible as unavailable instead of erasing it', () => {
const [result] = markShellDeleted([shell('a', 'running')], 'a')
expect(result?.id).toBe('a')
expect(result?.status).toBe('unavailable')
})
it('does not reset a terminal shell to running', () => {
const [result] = markShellDeleted([shell('a', 'exited', 0)], 'a')
expect(result?.status).toBe('exited')
})
})
+308
View File
@@ -0,0 +1,308 @@
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import type { SessionMessageAssistantTool, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { ShellInfo } from '@/api/opencode'
import type { SessionStatusType } from '@/stores/sessionStatusStore'
export const BACKGROUNDABLE_TOOLS = new Set(['shell', 'subagent'])
export type ChildOutcome = 'succeeded' | 'failed' | 'interrupted'
export type ShellLifecycleStatus = ShellInfo['status'] | 'unavailable'
export type ShellRecord = Omit<ShellInfo, 'status'> & { status: ShellLifecycleStatus }
export type BackgroundTaskKind = 'shell' | 'subagent'
export type BackgroundTaskStatus =
| 'running'
| 'completed'
| 'failed'
| 'killed'
| 'interrupted'
| 'unavailable'
export type BackgroundTaskLifecycle = BackgroundTaskStatus | 'unknown'
export interface BackgroundTask {
id: string
kind: BackgroundTaskKind
label: string
status: BackgroundTaskLifecycle
shell?: ShellRecord
childSessionID?: string
}
interface ShellExitRecord {
status: ShellLifecycleStatus
exit?: number
completedAt: number
}
const shellExitRecords = new Map<string, ShellExitRecord>()
const shellExitKey = (directory: string, id: string): string => `${directory}\u0000${id}`
export function recordShellExit(
directory: string,
exit: { id: string; status: ShellInfo['status']; exit?: number },
): void {
if (exit.status === 'running') return
shellExitRecords.set(shellExitKey(directory, exit.id), {
status: exit.status,
exit: exit.exit,
completedAt: Date.now(),
})
}
export function recordShellDeleted(directory: string, id: string): void {
shellExitRecords.set(shellExitKey(directory, id), {
status: 'unavailable',
completedAt: Date.now(),
})
}
export function clearShellExitRecord(directory: string, id: string): void {
shellExitRecords.delete(shellExitKey(directory, id))
}
function shellExitRecord(directory: string, id: string): ShellExitRecord | undefined {
return shellExitRecords.get(shellExitKey(directory, id))
}
export function toolMetadata(part: SessionMessageAssistantTool): Record<string, unknown> {
if (part.state.status === 'streaming') return {}
return part.state.metadata ?? {}
}
function metadataString(part: SessionMessageAssistantTool, key: string): string | undefined {
const value = toolMetadata(part)[key]
return typeof value === 'string' ? value : undefined
}
function isBackgroundPart(part: SessionMessageAssistantTool): boolean {
if (part.state.status !== 'completed') return false
const metadata = toolMetadata(part)
return metadata.background === true || metadata.status === 'running'
}
export function backgroundShellID(part: SessionMessageAssistantTool): string | undefined {
if (part.name !== 'shell' || !isBackgroundPart(part)) return undefined
return metadataString(part, 'shellID')
}
export function backgroundChildSessionID(part: SessionMessageAssistantTool): string | undefined {
if (part.name !== 'subagent' || !isBackgroundPart(part)) return undefined
return metadataString(part, 'sessionID')
}
export function isTerminalShell(shell: { status: ShellLifecycleStatus }): boolean {
return shell.status !== 'running'
}
export function shellLifecycle(shell: ShellRecord | undefined): BackgroundTaskLifecycle {
if (!shell) return 'unknown'
if (shell.status === 'running') return 'running'
if (shell.status === 'killed') return 'killed'
if (shell.status === 'timeout') return 'failed'
if (shell.status === 'unavailable') return 'unavailable'
return shell.exit !== undefined && shell.exit !== 0 ? 'failed' : 'completed'
}
export function childLifecycle(
status: SessionStatusType,
known: boolean,
outcome: ChildOutcome | undefined,
): BackgroundTaskLifecycle {
if (!known) return 'unknown'
if (status.type !== 'idle') return 'running'
if (outcome === 'failed') return 'failed'
if (outcome === 'interrupted') return 'interrupted'
return 'completed'
}
export function subagentLifecycle(
toolStatus: SessionMessageAssistantTool['state']['status'],
background: boolean,
childLifecycle: BackgroundTaskLifecycle,
): BackgroundTaskLifecycle {
if (toolStatus === 'error') return 'failed'
if (background) return childLifecycle
if (toolStatus === 'completed') return 'completed'
if (childLifecycle !== 'unknown' && childLifecycle !== 'running') return childLifecycle
return 'running'
}
export function shellToolLifecycle(
shellID: string | undefined,
shell: ShellRecord | undefined,
listLoaded: boolean,
): BackgroundTaskLifecycle {
if (!shellID) return 'completed'
if (shell) return shellLifecycle(shell)
return listLoaded ? 'unavailable' : 'unknown'
}
export function isRunningLifecycle(status: BackgroundTaskLifecycle): boolean {
return status === 'running' || status === 'unknown'
}
export function lifecycleLabel(status: BackgroundTaskLifecycle): string {
return status === 'unknown' ? 'running' : status
}
function applyShellExitRecord(shell: ShellRecord, record: ShellExitRecord): ShellRecord {
return {
...shell,
status: record.status,
exit: record.exit ?? shell.exit,
time: { ...shell.time, completed: shell.time.completed ?? record.completedAt },
}
}
function markShellUnavailable(shell: ShellRecord): ShellRecord {
return {
...shell,
status: 'unavailable',
time: { ...shell.time, completed: shell.time.completed ?? Date.now() },
}
}
export function reconcileShellList(
existing: ShellRecord[],
fetched: ShellInfo[],
fetchStartedAt: number,
directory: string,
): ShellRecord[] {
const existingByID = new Map(existing.map((shell) => [shell.id, shell]))
const fetchedByID = new Set(fetched.map((shell) => shell.id))
const merged: ShellRecord[] = fetched.map((shell) => {
const cached = existingByID.get(shell.id)
if (cached && isTerminalShell(cached) && !isTerminalShell(shell)) return cached
const record = shellExitRecord(directory, shell.id)
return record ? applyShellExitRecord(shell, record) : shell
})
for (const shell of existing) {
if (fetchedByID.has(shell.id)) continue
if (shell.time.started > fetchStartedAt) {
merged.push(shell)
continue
}
if (isTerminalShell(shell)) {
merged.push(shell)
continue
}
const record = shellExitRecord(directory, shell.id)
merged.push(record ? applyShellExitRecord(shell, record) : markShellUnavailable(shell))
}
return merged.sort((left, right) => left.time.started - right.time.started)
}
export function upsertShell(current: ShellRecord[], info: ShellInfo, directory: string): ShellRecord[] {
const cached = current.find((shell) => shell.id === info.id)
if (cached && isTerminalShell(cached) && !isTerminalShell(info)) return current
const record = shellExitRecord(directory, info.id)
const next = record && !isTerminalShell(info) ? applyShellExitRecord(info, record) : info
return [...current.filter((shell) => shell.id !== info.id), next]
}
export function applyShellExit(
current: ShellRecord[],
exit: { id: string; status: ShellInfo['status']; exit?: number },
): ShellRecord[] {
return current.map((shell) => {
if (shell.id !== exit.id || shell.status === 'unavailable') return shell
const terminal = exit.status !== 'running'
return {
...shell,
status: exit.status,
exit: exit.exit ?? shell.exit,
time: terminal ? { ...shell.time, completed: shell.time.completed ?? Date.now() } : shell.time,
}
})
}
export function markShellDeleted(current: ShellRecord[], id: string): ShellRecord[] {
return current.map((shell) => {
if (shell.id !== id || isTerminalShell(shell)) return shell
return markShellUnavailable(shell)
})
}
function shellLabel(part: SessionMessageAssistantTool): string {
if (part.state.status === 'streaming') return 'Shell command'
const command = part.state.input.command
if (typeof command !== 'string' || !command) return 'Shell command'
return unwrapSandboxExecCommand(command)
}
export function shellBackgroundTasks(
shells: ShellRecord[],
messages: SessionMessageInfo[],
listLoaded: boolean,
): BackgroundTask[] {
const tasks = new Map<string, BackgroundTask>()
for (const shell of shells) {
tasks.set(shell.id, {
id: shell.id,
kind: 'shell',
label: shell.command,
status: shellLifecycle(shell),
shell,
})
}
for (const message of messages) {
if (message.type !== 'assistant') continue
for (const part of message.content) {
if (part.type !== 'tool' || part.name !== 'shell') continue
const shellID = backgroundShellID(part)
if (!shellID || tasks.has(shellID)) continue
tasks.set(shellID, {
id: shellID,
kind: 'shell',
label: shellLabel(part),
status: listLoaded ? 'unavailable' : 'unknown',
})
}
}
return [...tasks.values()]
}
function subagentLabel(part: SessionMessageAssistantTool): string {
if (part.state.status !== 'streaming') {
const description = part.state.input.description
if (typeof description === 'string' && description) return description
}
return 'Sub-agent task'
}
export function subagentBackgroundTasks(
messages: SessionMessageInfo[],
statuses: Map<string, SessionStatusType>,
knownSessions: Set<string>,
outcomes: Map<string, ChildOutcome>,
): BackgroundTask[] {
const tasks = new Map<string, BackgroundTask>()
for (const message of messages) {
if (message.type !== 'assistant') continue
for (const part of message.content) {
if (part.type !== 'tool' || part.name !== 'subagent') continue
const childSessionID = backgroundChildSessionID(part)
if (!childSessionID) continue
tasks.set(childSessionID, {
id: childSessionID,
kind: 'subagent',
label: subagentLabel(part),
status: subagentLifecycle(
part.state.status,
true,
childLifecycle(
statuses.get(childSessionID) ?? { type: 'idle' },
knownSessions.has(childSessionID),
outcomes.get(childSessionID),
),
),
childSessionID,
})
}
}
return [...tasks.values()]
}
+8
View File
@@ -9,6 +9,14 @@ export function shellsQueryKey(directory: string | null | undefined) {
return ['opencode', 'shells', directory]
}
export function childSessionReconciliationQueryKey(sessionID: string | null | undefined) {
return ['opencode', 'session-reconcile', sessionID]
}
export function invalidateChildSessionCaches(queryClient: QueryClient) {
queryClient.invalidateQueries({ queryKey: ['opencode', 'session-reconcile'] })
}
export function invalidateProviderCaches(queryClient: QueryClient) {
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
queryClient.invalidateQueries({ queryKey: ['provider-auth-methods'] })
+1
View File
@@ -638,6 +638,7 @@ export function SessionDetail() {
directory={sessionDirectory}
messages={messages}
isSessionActive={isSessionActive}
onChildSessionClick={handleChildSessionClick}
/>
<PromptInput
ref={promptInputRef}
+164 -2
View File
@@ -6,6 +6,8 @@ const resetStore = () => {
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
revision: 0,
})
}
@@ -60,12 +62,172 @@ describe('sessionStatusStore', () => {
})
})
it('leaves the store state untouched for an idle event on an untracked session with no snapshot in flight', () => {
it('records knowledge for an idle event on an untracked session without adding a status', () => {
const before = useSessionStatus.getState()
before.setStatus('untracked', { type: 'idle' })
expect(useSessionStatus.getState()).toBe(before)
const after = useSessionStatus.getState()
expect(after.statuses).toBe(before.statuses)
expect(after.getStatus('untracked')).toEqual({ type: 'idle' })
expect(after.isSessionKnown('untracked')).toBe(true)
})
it('keeps knowledge of a session after it goes idle', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
expect(store.isSessionKnown('session-a')).toBe(true)
store.setStatus('session-a', { type: 'idle' })
expect(useSessionStatus.getState().isSessionKnown('session-a')).toBe(true)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
it('marks sessions from a global snapshot as known', () => {
const store = useSessionStatus.getState()
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({ 'session-a': { type: 'busy' } }, token)
expect(useSessionStatus.getState().isSessionKnown('session-a')).toBe(true)
expect(useSessionStatus.getState().isSessionKnown('session-unknown')).toBe(false)
})
it('does not treat a session omitted from a later snapshot as finished', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('session-a')).toBe(false)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
it('records a child outcome and preserves it when the status goes idle', () => {
const store = useSessionStatus.getState()
store.setStatus('child-a', { type: 'busy' })
store.setOutcome('child-a', 'failed')
store.setStatus('child-a', { type: 'idle' })
expect(useSessionStatus.getState().getOutcome('child-a')).toBe('failed')
expect(useSessionStatus.getState().isSessionKnown('child-a')).toBe(true)
})
it('clears a child outcome when a new execution starts', () => {
const store = useSessionStatus.getState()
store.setOutcome('child-a', 'interrupted')
store.clearOutcome('child-a')
expect(useSessionStatus.getState().getOutcome('child-a')).toBeUndefined()
})
it('applies an authoritative idle session snapshot from the child session query', () => {
const store = useSessionStatus.getState()
const token = store.beginStatusSnapshot()
store.applySessionSnapshot('child-a', {
id: 'child-a',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
outcome: 'failed',
time: { created: 1, updated: 2, idle: 2 },
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().isSessionKnown('child-a')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'idle' })
expect(useSessionStatus.getState().getOutcome('child-a')).toBe('failed')
})
it('applies a running child session snapshot as busy', () => {
const store = useSessionStatus.getState()
const token = store.beginStatusSnapshot()
store.applySessionSnapshot('child-a', {
id: 'child-a',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().isSessionKnown('child-a')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'busy' })
})
it('does not overwrite a newer live terminal event with a stale session snapshot', () => {
const store = useSessionStatus.getState()
const token = store.beginStatusSnapshot()
store.setStatus('child-a', { type: 'idle' })
store.applySessionSnapshot('child-a', {
id: 'child-a',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'idle' })
})
it('clears a stale child outcome when a fresh authoritative busy snapshot arrives', () => {
const store = useSessionStatus.getState()
store.setOutcome('child-a', 'failed')
const token = store.beginStatusSnapshot()
store.applySessionSnapshot('child-a', {
id: 'child-a',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().getOutcome('child-a')).toBeUndefined()
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'busy' })
})
it('preserves confirmed idle knowledge across a global snapshot', () => {
const store = useSessionStatus.getState()
store.setStatus('child-idle', { type: 'idle' })
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('child-idle')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-idle')).toEqual({ type: 'idle' })
})
it('turns a formerly active session omitted from a global snapshot unknown', () => {
const store = useSessionStatus.getState()
store.setStatus('child-active', { type: 'busy' })
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('child-active')).toBe(false)
})
it('does not let a snapshot erase an idle event received in flight', () => {
const store = useSessionStatus.getState()
store.setStatus('child-active', { type: 'busy' })
const token = store.beginStatusSnapshot()
store.setStatus('child-active', { type: 'idle' })
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('child-active')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-active')).toEqual({ type: 'idle' })
})
it('leaves the statuses map identity unchanged for a repeated identical busy status outside a snapshot', () => {
+133 -16
View File
@@ -1,4 +1,6 @@
import { create } from 'zustand'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import { childLifecycle, type BackgroundTaskLifecycle, type ChildOutcome } from '@/lib/backgroundWork'
export type SessionStatusType =
| { type: 'idle' }
@@ -6,7 +8,7 @@ export type SessionStatusType =
| { type: 'compact' }
| { type: 'retry'; attempt: number; message: string; next: number }
interface StatusSnapshotToken {
export interface StatusSnapshotToken {
revision: number
order: number
}
@@ -15,13 +17,20 @@ interface SessionStatusStore {
statuses: Map<string, SessionStatusType>
statusCache: Map<string, string>
statusRevisions: Map<string, number>
knownSessions: Set<string>
outcomes: Map<string, ChildOutcome>
revision: number
setStatus: (sessionID: string, status: SessionStatusType) => void
setOutcome: (sessionID: string, outcome: ChildOutcome) => void
clearOutcome: (sessionID: string) => void
setOptimisticActive: (sessionID: string, timeoutMs?: number) => void
replaceStatuses: (statuses: Record<string, SessionStatusType>, token: StatusSnapshotToken) => void
applySessionSnapshot: (sessionID: string, session: SessionInfo, token: StatusSnapshotToken) => void
beginStatusSnapshot: () => StatusSnapshotToken
endStatusSnapshot: (token: StatusSnapshotToken) => void
getStatus: (sessionID: string) => SessionStatusType
getOutcome: (sessionID: string) => ChildOutcome | undefined
isSessionKnown: (sessionID: string) => boolean
clearStatus: (sessionID: string) => void
}
@@ -54,6 +63,21 @@ const sameEntries = <V>(left: Map<string, V>, right: Map<string, V>): boolean =>
return true
}
const sameSets = (left: Set<string>, right: Set<string>): boolean => {
if (left.size !== right.size) return false
for (const value of right) {
if (!left.has(value)) 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)
next.add(sessionID)
return next
}
const registerSnapshot = (token: StatusSnapshotToken): void => {
inFlightSnapshots.set(token.order, token.revision)
}
@@ -107,13 +131,27 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
const statusCache = new Map(state.statusCache)
statuses.set(sessionID, status)
statusCache.set(sessionID, getStatusHash(status))
return { statuses, statusCache, ...(recordRevisionPatch(state, sessionID) ?? {}) }
const knownSessions = markSessionKnown(state.knownSessions, sessionID)
return {
statuses,
statusCache,
...(knownSessions ? { knownSessions } : {}),
...(recordRevisionPatch(state, sessionID) ?? {}),
}
}
const isLiveAfterCapture = (sessionID: string, captureRevision: number): boolean => {
if (optimisticActiveTimers.has(sessionID)) return true
const touched = get().statusRevisions.get(sessionID)
return touched !== undefined && touched > captureRevision
}
return {
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
revision: 0,
setStatus: (sessionID: string, status: SessionStatusType) => {
@@ -124,14 +162,55 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
clearOptimisticActiveTimer(sessionID)
if (get().statusCache.get(sessionID) === getStatusHash(status)) {
const patch = recordRevisionPatch(get(), sessionID)
if (patch) set(patch)
const revisionPatch = recordRevisionPatch(get(), sessionID)
const knownSessions = markSessionKnown(get().knownSessions, sessionID)
if (revisionPatch || knownSessions) {
set({
...(revisionPatch ?? {}),
...(knownSessions ? { knownSessions } : {}),
})
}
return
}
set((state) => applyStatusPatch(state, sessionID, status))
},
setOutcome: (sessionID: string, outcome: ChildOutcome) => {
if (get().outcomes.get(sessionID) === outcome) {
const knownSessions = markSessionKnown(get().knownSessions, sessionID)
if (knownSessions) set({ knownSessions })
return
}
set((state) => {
const outcomes = new Map(state.outcomes)
outcomes.set(sessionID, outcome)
const knownSessions = markSessionKnown(state.knownSessions, sessionID)
return { outcomes, ...(knownSessions ? { knownSessions } : {}) }
})
},
clearOutcome: (sessionID: string) => {
if (!get().outcomes.has(sessionID)) return
set((state) => {
const outcomes = new Map(state.outcomes)
outcomes.delete(sessionID)
return { outcomes }
})
},
applySessionSnapshot: (sessionID: string, session: SessionInfo, token: StatusSnapshotToken) => {
releaseSnapshot(token)
if (isLiveAfterCapture(sessionID, token.revision)) return
if (session.time.idle !== undefined) {
get().setStatus(sessionID, { type: 'idle' })
if (session.outcome) get().setOutcome(sessionID, session.outcome)
return
}
get().clearOutcome(sessionID)
get().setStatus(sessionID, { type: 'busy' })
},
setOptimisticActive: (sessionID: string, timeoutMs = OPTIMISTIC_ACTIVE_TIMEOUT_MS) => {
clearOptimisticActiveTimer(sessionID)
@@ -173,25 +252,20 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
const currentStatuses = get().statuses
const currentRevisions = get().statusRevisions
const currentKnownSessions = get().knownSessions
const captureRevision = token.revision
const isLiveAfterCapture = (sessionID: string): boolean => {
if (optimisticActiveTimers.has(sessionID)) return true
const touched = currentRevisions.get(sessionID)
return touched !== undefined && touched > captureRevision
}
const newMap = new Map<string, SessionStatusType>()
const newCache = new Map<string, string>()
for (const [sessionID, status] of currentStatuses.entries()) {
if (!isLiveAfterCapture(sessionID)) continue
if (!isLiveAfterCapture(sessionID, captureRevision)) continue
newMap.set(sessionID, status)
newCache.set(sessionID, getStatusHash(status))
}
for (const [sessionID, status] of Object.entries(statuses)) {
if (isLiveAfterCapture(sessionID)) continue
if (isLiveAfterCapture(sessionID, captureRevision)) continue
if (status.type === 'idle') continue
const current = currentStatuses.get(sessionID)
const effective = status.type === 'busy' && current !== undefined && current.type !== 'idle' ? current : status
@@ -200,13 +274,28 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
}
const nextRevisions = prunedRevisions(currentRevisions)
const nextKnownSessions = new Set<string>(Object.keys(statuses))
for (const [sessionID, revision] of currentRevisions.entries()) {
if (revision > captureRevision) nextKnownSessions.add(sessionID)
}
for (const sessionID of optimisticActiveTimers.keys()) {
nextKnownSessions.add(sessionID)
}
for (const sessionID of currentKnownSessions) {
if (!currentStatuses.has(sessionID)) nextKnownSessions.add(sessionID)
}
if (sameEntries(get().statusCache, newCache) && sameEntries(currentRevisions, nextRevisions)) return
if (
sameEntries(get().statusCache, newCache) &&
sameEntries(currentRevisions, nextRevisions) &&
sameSets(currentKnownSessions, nextKnownSessions)
) return
set({
statuses: newMap,
statusCache: newCache,
statusRevisions: nextRevisions,
knownSessions: nextKnownSessions,
})
},
@@ -230,18 +319,34 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
return get().statuses.get(sessionID) || DEFAULT_STATUS
},
getOutcome: (sessionID: string) => {
return get().outcomes.get(sessionID)
},
isSessionKnown: (sessionID: string) => {
return get().knownSessions.has(sessionID)
},
clearStatus: (sessionID: string) => {
clearOptimisticActiveTimer(sessionID)
if (!get().statuses.has(sessionID) && inFlightSnapshots.size === 0) return
const knownPatch = markSessionKnown(get().knownSessions, sessionID)
if (!get().statuses.has(sessionID) && inFlightSnapshots.size === 0) {
if (knownPatch) set({ knownSessions: knownPatch })
return
}
set((state) => {
const revisionPatch = recordRevisionPatch(state, sessionID)
if (!state.statuses.has(sessionID)) return revisionPatch ?? state
const knownSessions = markSessionKnown(state.knownSessions, sessionID)
const knownFields = knownSessions ? { knownSessions } : {}
if (!state.statuses.has(sessionID)) {
return { ...(revisionPatch ?? {}), ...knownFields }
}
const statuses = new Map(state.statuses)
const statusCache = new Map(state.statusCache)
statuses.delete(sessionID)
statusCache.delete(sessionID)
return { statuses, statusCache, ...(revisionPatch ?? {}) }
return { statuses, statusCache, ...(revisionPatch ?? {}), ...knownFields }
})
},
}
@@ -252,3 +357,15 @@ export const useSessionStatusForSession = (sessionID: string | undefined): Sessi
sessionID ? (state.statuses.get(sessionID) ?? DEFAULT_STATUS) : DEFAULT_STATUS
)
}
export const useIsSessionKnown = (sessionID: string | undefined): boolean => {
return useSessionStatus((state) => (sessionID ? state.knownSessions.has(sessionID) : false))
}
export const useChildLifecycleForSession = (sessionID: string | undefined): BackgroundTaskLifecycle => {
return useSessionStatus((state) => {
if (!sessionID) return 'unknown'
const status = state.statuses.get(sessionID) ?? DEFAULT_STATUS
return childLifecycle(status, state.knownSessions.has(sessionID), state.outcomes.get(sessionID))
})
}