fix: stabilize scheduled runs and background task tracking (#365)

* fix: stabilize scheduled runs and background task tracking

* fix: complete scheduled runs and harden background task status

- Route directory-less OpenCode session events (session.execution.*,
  session.usage.updated) to backend listeners by remembering each
  session's directory in the SSE aggregator, so scheduled runs finish
  and failure push notifications fire; browser delivery is unchanged.
- Resolve background shell status from the transcript completion notice
  when OpenCode no longer lists the shell, keep the first terminal
  status so a kill is not reported as completed, and share one status
  icon and colour mapping between the transcript and background bar.
- Reconcile child sessions only while unknown or running, trigger it
  from the EventProvider alone, refresh children that drop to unknown
  after a poll, and forget deleted sessions.
- Fetch the model list and default concurrently while waiting for the
  schedule model, share configured-model selection, and consolidate
  schedule startup cancellation cleanup.
- Reduce background work re-renders, prune shell exit records, remove
  dead exports, and document background work in the chat guide.

* fix: hide finished background tasks and clip long dialog titles
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-28 23:55:01 -04:00
1 parent e80016cc22
commit 304f636516
35 files changed
+4272 -254

No files matched your search

@@ -3,17 +3,20 @@ import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import { TextPart } from './TextPart'
import { ToolCallPart } from './ToolCallPart'
import { useSettings } from '@/hooks/useSettings'
import type { ShellNoticeOutcome } from '@/lib/backgroundWork'
type AssistantContentPart = SessionMessageAssistant['content'][number]
interface MessagePartProps {
part: AssistantContentPart
messageID?: string
directory?: string
shellOutcome?: ShellNoticeOutcome
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, shellOutcome, onFileClick, onChildSessionClick }: MessagePartProps) {
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
@@ -40,6 +43,8 @@ export const MessagePart = memo(function MessagePart({ part, messageID, onFileCl
<ToolCallPart
part={part}
messageID={messageID}
directory={directory}
shellOutcome={shellOutcome}
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
@@ -191,6 +204,43 @@ describe('MessageThread', () => {
expect(onChildSessionClick).toHaveBeenCalledWith('child-1')
})
it('resolves a background shell tool from its completion notice', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages: SessionMessageInfo[] = [
userMessage('1', 'Hello'),
assistantMessage('2', [
{
type: 'tool',
id: 'tool_shell',
name: 'shell',
state: {
status: 'completed',
input: { command: 'npm run dev' },
content: [{ type: 'text', text: 'started in the background' }],
metadata: { status: 'running', shellID: 'sh_notice' },
},
time: { created: Date.now(), completed: Date.now() + 100 },
},
]),
{
id: 'syn-shell',
type: 'synthetic',
text: '',
metadata: { source: 'shell', shellID: 'sh_notice', state: 'completed', exit: 0 },
time: { created: Date.now() },
},
]
const { container } = render(
<MessageThread sessionID="test-session" messages={messages} pending={[]} />,
)
expect(screen.getByText('completed')).toBeInTheDocument()
expect(screen.queryByText('unavailable')).not.toBeInTheDocument()
expect(container.querySelector('.animate-spin')).toBeNull()
})
it('renders a synthetic message that only carries text', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
@@ -22,6 +22,7 @@ import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage
import { useSettings } from '@/hooks/useSettings'
import { useTTS } from '@/hooks/useTTS'
import { CopyButton } from '@/components/ui/copy-button'
import { backgroundShellID, collectBackgroundParts, type ShellNoticeOutcome } from '@/lib/backgroundWork'
function getMessageText(message: SessionMessageInfo): string {
switch (message.type) {
@@ -364,6 +365,7 @@ interface MessageRowProps {
model?: string
simpleChatMode: boolean
showReasoning: boolean
shellOutcomes: ReadonlyMap<string, ShellNoticeOutcome>
}
const MessageRow = memo(function MessageRow({
@@ -382,8 +384,11 @@ const MessageRow = memo(function MessageRow({
model,
simpleChatMode,
showReasoning,
shellOutcomes,
}: MessageRowProps) {
const messageTextContent = getMessageText(message)
const shellOutcomeFor = (part: SessionMessageAssistant['content'][number]) =>
part.type === 'tool' ? shellOutcomes.get(backgroundShellID(part) ?? '') : undefined
const streaming = message.type === 'assistant' && message.time.completed === undefined
const isEditingThisMessage = editingUserMessageId === message.id
const canEditUserMessage = isLastUserMessage && !isSessionBusy
@@ -479,6 +484,8 @@ const MessageRow = memo(function MessageRow({
<MessagePart
part={part}
messageID={message.id}
directory={directory}
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -516,6 +523,8 @@ const MessageRow = memo(function MessageRow({
<MessagePart
part={part}
messageID={message.id}
directory={directory}
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -607,6 +616,15 @@ export const MessageThread = memo(function MessageThread({
const lastUserMessageId = useMemo(() => findLastUserMessageId(messages), [messages])
const shellOutcomesKey = useMemo(
() => [...collectBackgroundParts(messages).shellNotices].map(([id, outcome]) => `${id}=${outcome}`).join(','),
[messages],
)
const shellOutcomes = useMemo(
() => new Map(shellOutcomesKey ? shellOutcomesKey.split(',').map((entry) => entry.split('=') as [string, ShellNoticeOutcome]) : []),
[shellOutcomesKey],
)
const nextAssistantIdByMessageId = useMemo(() => {
const map = new Map<string, string | undefined>()
let nextAssistantId: string | undefined
@@ -656,6 +674,7 @@ export const MessageThread = memo(function MessageThread({
model={model}
simpleChatMode={simpleChatMode}
showReasoning={showReasoning}
shellOutcomes={shellOutcomes}
/>
))}
{pending.map((item) => (
@@ -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,94 @@ 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 a non-spinning unavailable icon', async () => {
const { container } = 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()
expect(container.querySelector('.animate-spin')).toBeNull()
})
it('completes a background shell missing from the list from its notice', async () => {
const { container } = renderWithProviders(
<ToolCallPart
part={completedShell({ status: 'running', shellID: 'sh_notice' })}
messageID="msg_1"
directory="/repo"
shellOutcome="completed"
/>,
)
await waitFor(() => expect(screen.getByText('completed')).toBeInTheDocument())
expect(screen.queryByText('background')).not.toBeInTheDocument()
expect(container.querySelector('.animate-spin')).toBeNull()
})
it('fails a background shell missing from the list from its notice', async () => {
renderWithProviders(
<ToolCallPart
part={completedShell({ status: 'running', shellID: 'sh_notice' })}
messageID="msg_1"
directory="/repo"
shellOutcome="failed"
/>,
)
await waitFor(() => expect(screen.getByText('failed')).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,28 @@ 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 { Badge } from '@/components/ui/badge'
import { CopyButton } from '@/components/ui/copy-button'
import { BackgroundTaskStatusIcon } from '@/components/session/BackgroundTaskStatusIcon'
import {
backgroundChildSessionID,
backgroundShellID,
backgroundTaskStatusColor,
isRunningLifecycle,
lifecycleLabel,
shellToolLifecycle,
subagentLifecycle,
subagentSessionID,
toolMetadata,
type BackgroundTaskLifecycle,
type ShellNoticeOutcome,
} from '@/lib/backgroundWork'
import { getToolInputPath, getToolSpecificRender } from './FileToolRender'
const DISPLAY_LIMIT = 30_000
@@ -41,6 +57,8 @@ function BoundedPre({ content, className }: { content: string; className: string
interface ToolCallPartProps {
part: SessionMessageAssistantTool
messageID?: string
directory?: string
shellOutcome?: ShellNoticeOutcome
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
}
@@ -50,21 +68,11 @@ 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)
}
function getSubagentSessionId(part: SessionMessageAssistantTool): string | undefined {
const sessionID = toolMetadata(part).sessionID
return typeof sessionID === 'string' ? sessionID : undefined
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
const jsonString = useMemo(() => JSON.stringify(json, null, 2), [json])
const references = useMemo(() => detectFileReferences(jsonString), [jsonString])
@@ -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, shellOutcome, 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 subagentSessionId = isSubagent ? subagentSessionID(part) : undefined
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, shellOutcome)
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,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
}, [expanded, part.name])
const getStatusColor = () => {
if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus)
switch (part.state.status) {
case 'completed':
return 'text-success'
@@ -151,7 +176,12 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
}
}
const renderShellLifecycleIcon = (status: BackgroundTaskLifecycle) => (
<BackgroundTaskStatusIcon status={status} className="w-3.5 h-3.5" />
)
const getStatusIcon = () => {
if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus)
switch (part.state.status) {
case 'completed':
return <span>✓</span>
@@ -193,7 +223,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 +248,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 +310,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 +375,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 && (