mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
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:
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 && (
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Ban, Check, Loader2, Square, XCircle } from 'lucide-react'
|
||||
import { backgroundTaskStatusColor, type BackgroundTaskLifecycle } from '@/lib/backgroundWork'
|
||||
|
||||
export function BackgroundTaskStatusIcon({ status, className }: { status: BackgroundTaskLifecycle; className: string }) {
|
||||
const iconClassName = `${className} ${backgroundTaskStatusColor(status)}`
|
||||
if (status === 'completed') return <Check className={iconClassName} />
|
||||
if (status === 'failed') return <XCircle className={iconClassName} />
|
||||
if (status === 'interrupted') return <Ban className={iconClassName} />
|
||||
if (status === 'killed') return <Square className={iconClassName} />
|
||||
if (status === 'unavailable') return <XCircle className={iconClassName} />
|
||||
return <Loader2 className={`${iconClassName} animate-spin`} />
|
||||
}
|
||||
@@ -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,80 @@ 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 shellNotice = (
|
||||
shellID: string,
|
||||
state: 'completed' | 'error',
|
||||
exit?: number,
|
||||
): SessionMessageInfo => ({
|
||||
id: `notice-${shellID}`,
|
||||
type: 'synthetic',
|
||||
text: '',
|
||||
metadata: { source: 'shell', shellID, state, ...(exit === undefined ? {} : { exit }) },
|
||||
time: { created: 3 },
|
||||
})
|
||||
|
||||
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 +134,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 +168,270 @@ 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('hides completed shells and removes a killed shell', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev'), shell('other', 'session-2'), shell('done', 'session-1', 'exited')])
|
||||
renderBar([], false)
|
||||
const { container } = renderBar([], false)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background shell$/ }))
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
|
||||
expect(screen.getByText('npm run dev')).toBeInTheDocument()
|
||||
expect(screen.queryByText('npm run other')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('npm run done')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('npm run other')).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())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
clearShellExitRecord('/repo', 'dev')
|
||||
})
|
||||
|
||||
it('removes a shell row once it completes', 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 } },
|
||||
])
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('npm run dev')).not.toBeInTheDocument())
|
||||
expect(screen.queryByRole('button', { name: /background task/ })).not.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('hides a running shell omitted from a fresh list once it becomes unavailable', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { queryClient, container } = 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'] })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
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.queryByText('npm run dev')).not.toBeInTheDocument())
|
||||
expect(screen.queryByText('running')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a backgrounded subagent and removes 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' })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Explore')).not.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' },
|
||||
})
|
||||
const { container } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
await waitFor(() => expect(api.getSession).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a failed child session outcome', async () => {
|
||||
act(() => {
|
||||
useSessionStatus.getState().setOutcome('child-1', 'failed')
|
||||
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
|
||||
})
|
||||
const { container } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides an interrupted child session outcome', async () => {
|
||||
act(() => {
|
||||
useSessionStatus.getState().setOutcome('child-1', 'interrupted')
|
||||
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
|
||||
})
|
||||
const { container } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a deleted shell once it becomes unavailable', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev')])
|
||||
const { queryClient, container } = 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 } },
|
||||
])
|
||||
})
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a historical shell absent from the fetched list', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { container } = renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a historical shell absent from the list once its notice reports completion', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { container } = renderBar(
|
||||
[backgroundShellTool('sh-notice', 'npm run notice'), shellNotice('sh-notice', 'completed', 0)],
|
||||
false,
|
||||
)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a historical shell absent from the list once its error notice reports failure', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { container } = renderBar(
|
||||
[backgroundShellTool('sh-notice', 'npm run notice'), shellNotice('sh-notice', 'error')],
|
||||
false,
|
||||
)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
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, container } = renderBar(messages, false)
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
unmount()
|
||||
|
||||
const remount = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BackgroundWorkBar sessionID="session-1" directory="/repo" messages={messages} isSessionActive={false} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
await waitFor(() => expect(remount.container).toBeEmptyDOMElement())
|
||||
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.queryByText('Explore')).not.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.queryByText('Explore')).not.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')])
|
||||
const { container } = renderBar([], false)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
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 +439,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 +461,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,30 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ChevronDown, ChevronUp, Loader2, MoveDownRight, Square, Terminal } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Bot, Check, ChevronDown, ChevronUp, ExternalLink, Loader2, MoveDownRight, Square, Terminal } from 'lucide-react'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
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 { BackgroundTaskStatusIcon } from './BackgroundTaskStatusIcon'
|
||||
import {
|
||||
BACKGROUNDABLE_TOOLS,
|
||||
childLifecycle,
|
||||
collectBackgroundParts,
|
||||
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 +104,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 +123,123 @@ function ShellOutputView({ shell, directory, running }: { shell: ShellInfo; dire
|
||||
)
|
||||
}
|
||||
|
||||
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} className="h-3 w-3" />
|
||||
{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 collected = useMemo(() => collectBackgroundParts(messages), [messages])
|
||||
const childLifecycles = useSessionStatus(
|
||||
useShallow((state) => {
|
||||
const lifecycles: Record<string, BackgroundTaskLifecycle> = {}
|
||||
for (const part of collected.subagents) {
|
||||
lifecycles[part.childSessionID] = childLifecycle(
|
||||
state.statuses.get(part.childSessionID) ?? { type: 'idle' },
|
||||
state.knownSessions.has(part.childSessionID),
|
||||
state.outcomes.get(part.childSessionID),
|
||||
)
|
||||
}
|
||||
return lifecycles
|
||||
}),
|
||||
)
|
||||
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, collected.shells, collected.shellNotices, listLoaded),
|
||||
...subagentBackgroundTasks(collected.subagents, childLifecycles),
|
||||
].filter((task) => isRunningLifecycle(task.status)),
|
||||
[shells, collected, listLoaded, childLifecycles],
|
||||
)
|
||||
|
||||
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 +253,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 +286,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>
|
||||
|
||||
@@ -383,6 +383,21 @@ describe("DialogContent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("DialogHeader", () => {
|
||||
it("can shrink so a long title truncates instead of widening the dialog", () => {
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent>
|
||||
<DialogHeader data-testid="dialog-header">
|
||||
<DialogTitle className="truncate">a very long command that would otherwise widen the dialog</DialogTitle>
|
||||
</DialogHeader>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
expect(screen.getByTestId("dialog-header")).toHaveClass("min-w-0");
|
||||
});
|
||||
});
|
||||
|
||||
function stubVisualViewport(height: number) {
|
||||
const listeners = new Set<() => void>()
|
||||
Object.defineProperty(window, 'visualViewport', {
|
||||
|
||||
@@ -146,7 +146,7 @@ const DialogHeader = ({
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left min-w-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
Reference in new issue
Block a user