mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +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
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user