feat(session): surface background shell and subagent work (#360)

* feat(session): surface background shell and subagent work

* fix(session): address review feedback on background work UI
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 15:49:49 -04:00
1 parent 8b806e865f
commit 1389e8e59c
20 files changed
+802 -13

No files matched your search

@@ -128,6 +128,81 @@ describe('MessageThread', () => {
useUIState.getState().setIsEditingMessage(false)
})
it('renders instruction updates as a single notice line without the instruction body', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages: SessionMessageInfo[] = [
{ id: 'sys-1', type: 'system', text: '# Code Mode\nfull instruction body', time: { created: Date.now() } },
{
id: 'sys-2',
type: 'system',
text: 'agents body',
description: 'Instructions updated: AGENTS.md',
time: { created: Date.now() },
},
]
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
expect(screen.getByText(/Instructions updated$/)).toBeInTheDocument()
expect(screen.getByText(/Instructions updated: AGENTS\.md/)).toBeInTheDocument()
expect(screen.queryByText(/full instruction body/)).not.toBeInTheDocument()
expect(screen.queryByText(/agents body/)).not.toBeInTheDocument()
})
it('renders background completion notices as status lines instead of raw payloads', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const onChildSessionClick = vi.fn()
const messages: SessionMessageInfo[] = [
{
id: 'syn-shell',
type: 'synthetic',
text: '<shell id="job-1" state="error" command="pnpm test">\nboom\n</shell>',
description: 'pnpm test',
metadata: { source: 'shell', state: 'error' },
time: { created: Date.now() },
},
{
id: 'syn-subagent',
type: 'synthetic',
text: '<subagent sessionID="child-1" state="completed" description="Explore">\ndone\n</subagent>',
description: 'Explore',
metadata: { source: 'subagent', state: 'completed', childID: 'child-1', agent: 'explore' },
time: { created: Date.now() },
},
]
render(
<MessageThread
sessionID="test-session"
messages={messages}
pending={[]}
onChildSessionClick={onChildSessionClick}
/>,
)
expect(screen.getByText('! Shell failed')).toBeInTheDocument()
expect(screen.getByText('· pnpm test')).toBeInTheDocument()
expect(screen.queryByText(/<shell/)).not.toBeInTheDocument()
expect(screen.queryByText(/<subagent/)).not.toBeInTheDocument()
fireEvent.click(screen.getByText('↳ Explore finished'))
expect(onChildSessionClick).toHaveBeenCalledWith('child-1')
})
it('renders a synthetic message that only carries text', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages: SessionMessageInfo[] = [
{ id: 'syn-text', type: 'synthetic', text: 'Background task finished', time: { created: Date.now() } },
]
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
expect(screen.getByText(/Background task finished/)).toBeInTheDocument()
})
it('renders assistant message with only a subagent part as standalone row without header', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
@@ -63,8 +63,10 @@ function hasRenderableContent(
return false
})
case 'synthetic':
case 'system':
return message.text.trim().length > 0
case 'system': {
const notice = sessionNoticeContent(message)
return notice.completion !== undefined || notice.text.trim().length > 0
}
case 'shell':
case 'skill':
case 'compaction':
@@ -194,6 +196,85 @@ function MessageDivider({ label }: { label: string }) {
)
}
type SessionNoticeMessage = Extract<SessionMessageInfo, { type: 'synthetic' | 'system' }>
interface SessionNoticeContent {
text: string
completion?: {
heading: string
state?: string
childID?: string
}
}
function noticeMetadataString(message: SessionNoticeMessage, key: string): string | undefined {
const value = message.metadata?.[key]
return typeof value === 'string' ? value : undefined
}
function sessionNoticeContent(message: SessionNoticeMessage): SessionNoticeContent {
const source = noticeMetadataString(message, 'source')
const text = message.type === 'system'
? message.description ?? 'Instructions updated'
: message.description ?? (source === 'shell' || source === 'subagent' ? '' : message.text)
if (source !== 'shell' && source !== 'subagent') return { text }
const state = noticeMetadataString(message, 'state')
const agent = noticeMetadataString(message, 'agent')
const actor = source === 'shell' ? 'Shell' : agent ? agent.charAt(0).toUpperCase() + agent.slice(1) : 'Subagent'
const status = state === 'error' ? 'failed' : state === 'completed' || state === undefined ? 'finished' : state
return {
text: source === 'shell' ? text.replace(/\s+/g, ' ').trim() : text,
completion: {
heading: `${state === 'completed' ? '↳' : '!'} ${actor} ${status}`,
state,
childID: source === 'subagent' ? noticeMetadataString(message, 'childID') : undefined,
},
}
}
function SessionNotice({
message,
onChildSessionClick,
}: {
message: SessionNoticeMessage
onChildSessionClick?: (sessionId: string) => void
}) {
const { text, completion } = sessionNoticeContent(message)
if (!completion) {
return <div className="my-1 px-3 py-1 text-xs text-muted-foreground truncate">◈ {text}</div>
}
const tone = completion.state === 'error'
? 'text-destructive'
: completion.state === 'cancelled'
? 'text-amber-600 dark:text-amber-400'
: 'text-blue-600 dark:text-blue-400'
const content = (
<>
<span className={tone}>{completion.heading}</span>
{text && <span className="text-muted-foreground"> · {text}</span>}
</>
)
const childID = completion.childID
if (childID && onChildSessionClick) {
return (
<button
type="button"
onClick={() => onChildSessionClick(childID)}
aria-live="polite"
className="my-1 block w-full px-3 py-1 text-left text-xs truncate hover:underline"
>
{content}
</button>
)
}
return <div aria-live="polite" className="my-1 px-3 py-1 text-xs truncate">{content}</div>
}
function ShellMessage({ message }: { message: SessionMessageShell }) {
const output = message.output?.output ?? ''
const statusLabel = message.status === 'running'
@@ -490,11 +571,7 @@ const MessageRow = memo(function MessageRow({
}
if (message.type === 'synthetic' || message.type === 'system') {
return (
<div className="my-1 px-3 py-1.5 text-xs italic text-muted-foreground whitespace-pre-wrap">
{message.text}
</div>
)
return <SessionNotice message={message} onChildSessionClick={onChildSessionClick} />
}
return null
@@ -4,6 +4,7 @@ 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'
const mocks = vi.hoisted(() => ({
useSettings: vi.fn(),
@@ -99,3 +100,51 @@ describe('ToolCallPart permission indicator', () => {
expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument()
})
})
describe('ToolCallPart background indicator', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
isLoading: false,
updateSettings: vi.fn(),
isUpdating: false,
})
mocks.useToolCallPermission.mockReturnValue(null)
useUserBash.setState({ userBashCommands: new Map() })
})
const completedShell = (metadata: Record<string, unknown>): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_2',
name: 'shell',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { command: 'npm run dev' },
content: [{ type: 'text', text: 'Command moved to the background (shell ID: sh_1).' }],
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" />)
expect(screen.getByText('background')).toBeInTheDocument()
})
it('does not mark a shell call that finished normally', () => {
renderWithProviders(<ToolCallPart part={completedShell({ status: 'completed', shellID: 'sh_1' })} messageID="msg_1" />)
expect(screen.queryByText('background')).not.toBeInTheDocument()
})
it('marks a backgrounded user-bash command with a background indicator', () => {
useUserBash.setState({ userBashCommands: new Map([['npm run dev', Date.now()]]) })
renderWithProviders(<ToolCallPart part={completedShell({ status: 'running', shellID: 'sh_1' })} messageID="msg_1" />)
expect(screen.getByText('background')).toBeInTheDocument()
expect(screen.queryByText('✓')).not.toBeInTheDocument()
})
})
@@ -193,6 +193,16 @@ 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 backgroundIndicator = isBackgrounded ? (
<Badge
variant="outline"
className="shrink-0 border-yellow-600/40 bg-yellow-500/10 text-yellow-700 dark:text-yellow-400"
title="Continues running in the background; the session is notified when it finishes"
>
background
</Badge>
) : null
const sandboxIndicator = isSandboxedCommand ? (
<Badge
variant="outline"
@@ -206,8 +216,8 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
if (isSubagent) {
const status = part.state.status
const isRunning = status === 'running' && subagentSessionStatus.type !== 'idle'
const isCompleted = status === 'completed' || (status === 'running' && !!subagentSessionId && subagentSessionStatus.type === 'idle')
const isRunning = (status === 'running' || isBackgrounded) && subagentSessionStatus.type !== 'idle'
const isCompleted = !isRunning && (status === 'completed' || (status === 'running' && !!subagentSessionId && subagentSessionStatus.type === 'idle'))
const isError = status === 'error'
const description = previewText || 'Sub-agent task'
@@ -231,6 +241,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
{isError && <span className="text-red-600 text-sm font-medium">✗</span>}
<span className="font-medium text-foreground truncate">{description}</span>
<span className="text-[11px] font-medium text-orange-600 dark:text-orange-400 shrink-0">sub-agent</span>
{backgroundIndicator}
{subagentSessionId && <ExternalLink className="w-3 h-3 shrink-0 text-blue-600 dark:text-blue-400" />}
</div>
)
@@ -267,10 +278,15 @@ 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">
<span className="text-green-600 dark:text-green-400">✓</span>
{isBackgrounded ? (
<Loader2 className="w-3.5 h-3.5 animate-spin text-yellow-600 dark:text-yellow-400" />
) : (
<span className="text-green-600 dark:text-green-400">✓</span>
)}
<span className="font-medium">$</span>
<span className="text-foreground">{command}</span>
{sandboxIndicator}
{backgroundIndicator}
{ran !== undefined && completed !== undefined && (
<span className="text-muted-foreground text-xs ml-auto">
{((completed - ran) / 1000).toFixed(2)}s
@@ -312,6 +328,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.name}</span>
{sandboxIndicator}
{backgroundIndicator}
{previewText && isFileTool ? (
<span
@@ -0,0 +1,150 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { 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 { BackgroundWorkBar } from './BackgroundWorkBar'
const api = vi.hoisted(() => ({
backgroundSession: vi.fn(),
listShells: vi.fn(),
readShellOutput: vi.fn(),
removeShell: vi.fn(),
}))
vi.mock('@/api/opencode', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/opencode')>()),
...api,
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), loading: vi.fn() },
}))
const shell = (id: string, sessionID = 'session-1', status: ShellInfo['status'] = 'running'): ShellInfo => ({
id,
status,
command: `npm run ${id}`,
cwd: '/repo',
shell: 'zsh',
file: `/tmp/${id}.log`,
metadata: { sessionID },
time: { started: 1 },
})
const runningShellTool = (): SessionMessageAssistant => ({
id: 'msg-1',
type: 'assistant',
agent: 'build',
model: { providerID: 'p', id: 'm' },
content: [
{
type: 'tool',
id: 'tool-1',
name: 'shell',
state: { status: 'running', input: { command: 'npm test' }, metadata: {} },
time: { created: 1 },
},
],
time: { created: 1 },
})
function renderBar(messages: SessionMessageInfo[], isSessionActive: boolean) {
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} />,
{ wrapper },
),
queryClient,
}
}
describe('BackgroundWorkBar', () => {
beforeEach(() => {
vi.clearAllMocks()
api.listShells.mockResolvedValue([])
api.backgroundSession.mockResolvedValue(undefined)
api.removeShell.mockResolvedValue(undefined)
api.readShellOutput.mockResolvedValue({ output: '', cursor: 0, size: 0, truncated: false })
})
it('renders nothing when there is no running or background work', async () => {
const { container } = renderBar([], false)
await waitFor(() => expect(api.listShells).toHaveBeenCalledWith('/repo'))
expect(container).toBeEmptyDOMElement()
})
it('moves running shell work to the background', async () => {
renderBar([runningShellTool()], true)
fireEvent.click(await screen.findByRole('button', { name: /Move to background/ }))
await waitFor(() => expect(api.backgroundSession).toHaveBeenCalledWith('session-1'))
})
it('hides the background action once the session is idle', async () => {
renderBar([runningShellTool()], false)
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
expect(screen.queryByRole('button', { name: /Move to background/ })).not.toBeInTheDocument()
})
it('lists only this session\'s running shells and kills one', async () => {
api.listShells.mockResolvedValue([shell('dev'), shell('other', 'session-2'), shell('done', 'session-1', 'exited')])
renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background shell$/ }))
expect(screen.getByText('npm run dev')).toBeInTheDocument()
expect(screen.queryByText('npm run other')).not.toBeInTheDocument()
expect(screen.queryByText('npm run done')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Kill npm run dev' }))
await waitFor(() => expect(api.removeShell).toHaveBeenCalledWith('dev', '/repo'))
await waitFor(() => expect(screen.queryByText(/background shell/)).not.toBeInTheDocument())
})
it('shows the tail of a background shell output', async () => {
api.listShells.mockResolvedValue([shell('dev')])
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(screen.getByRole('button', { name: 'Output' }))
expect(await screen.findByText('server listening on 3000')).toBeInTheDocument()
expect(api.readShellOutput).toHaveBeenCalledWith('dev', '/repo', 0, 50_000)
})
it('reads the final output when the shell exits during an in-flight poll', async () => {
let resolveFirst: ((value: { output: string; cursor: number; size: number; truncated: boolean }) => void) | undefined
let calls = 0
api.listShells.mockResolvedValue([shell('dev')])
api.readShellOutput.mockImplementation(() => {
calls += 1
if (calls === 1) {
return new Promise<{ output: string; cursor: number; size: number; truncated: boolean }>((resolve) => {
resolveFirst = resolve
})
}
return Promise.resolve({ output: 'final tail', cursor: 10, size: 10, truncated: false })
})
const { queryClient } = renderBar([], false)
fireEvent.click(await screen.findByRole('button', { name: /1 background shell$/ }))
fireEvent.click(screen.getByRole('button', { name: 'Output' }))
await waitFor(() => expect(calls).toBe(1))
api.listShells.mockResolvedValue([])
await queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
expect(await screen.findByText('final tail')).toBeInTheDocument()
resolveFirst?.({ output: '', cursor: 0, size: 0, truncated: false })
})
})
@@ -0,0 +1,196 @@
import { useEffect, useRef, useState } from 'react'
import { ChevronDown, ChevronUp, Loader2, MoveDownRight, Square, Terminal } from 'lucide-react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { readShellOutput, type ShellInfo } 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 { useKillShell, useSessionShells } from '@/hooks/useSessionShells'
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) {
const message = messages[index]
if (message?.type !== 'assistant' || message.time.completed !== undefined) continue
return message.content.some(
(part) => part.type === 'tool' && part.state.status === 'running' && BACKGROUNDABLE_TOOLS.has(part.name),
)
}
return false
}
interface ShellOutputState {
output: string
truncated: boolean
}
function appendShellOutput(previous: ShellOutputState, output: string, truncated: boolean): ShellOutputState {
const next = previous.output + output
if (next.length <= SHELL_OUTPUT_LIMIT) return { output: next, truncated: previous.truncated || truncated }
return { output: next.slice(-SHELL_OUTPUT_LIMIT), truncated: true }
}
function useShellOutput(shellID: string, directory: string, running: boolean): ShellOutputState {
const [state, setState] = useState<ShellOutputState>({ output: '', truncated: false })
const cursorRef = useRef(0)
useEffect(() => {
let cancelled = false
let loading = false
const load = async () => {
if (loading) return
loading = true
let cursor = cursorRef.current
let output = ''
let truncated = false
try {
for (;;) {
const chunk = await readShellOutput(shellID, directory, cursor, SHELL_OUTPUT_LIMIT)
output += chunk.output
if (chunk.truncated) truncated = true
if (chunk.cursor <= cursor) break
cursor = chunk.cursor
if (cursor >= chunk.size) break
const tail = chunk.size - SHELL_OUTPUT_LIMIT
if (tail > cursor) {
cursor = tail
output = ''
truncated = true
}
}
} catch {
return
} finally {
loading = false
if (!cancelled) {
cursorRef.current = cursor
if (output || truncated) setState((previous) => appendShellOutput(previous, output, truncated))
}
}
}
void load()
if (!running) {
return () => {
cancelled = true
}
}
const interval = setInterval(() => void load(), SHELL_OUTPUT_POLL_INTERVAL_MS)
return () => {
cancelled = true
clearInterval(interval)
}
}, [shellID, directory, running])
return state
}
function ShellOutputView({ shell, directory, running }: { shell: ShellInfo; directory: string; running: boolean }) {
const { output, truncated } = useShellOutput(shell.id, directory, running)
const bottomRef = useRef<HTMLDivElement>(null)
useEffect(() => {
bottomRef.current?.scrollIntoView({ block: 'end' })
}, [output])
return (
<div className="max-h-[60vh] overflow-auto rounded bg-accent p-2">
<pre className="whitespace-pre-wrap break-all text-xs">
{truncated && <span className="text-muted-foreground">[earlier output omitted]{'\n'}</span>}
{output || <span className="text-muted-foreground">{running ? 'Waiting for output…' : 'No output'}</span>}
</pre>
<div ref={bottomRef} />
</div>
)
}
interface BackgroundWorkBarProps {
sessionID: string
directory: string
messages: SessionMessageInfo[]
isSessionActive: boolean
}
export function BackgroundWorkBar({ sessionID, directory, messages, isSessionActive }: BackgroundWorkBarProps) {
const shells = useSessionShells(sessionID, directory)
const killShell = useKillShell(directory)
const backgroundSession = useBackgroundSession()
const [expanded, setExpanded] = useState(false)
const [viewing, setViewing] = useState<ShellInfo | null>(null)
const canBackground = isSessionActive && hasBackgroundableWork(messages)
const viewingRunning = viewing !== null && shells.some((shell) => shell.id === viewing.id)
if (!canBackground && shells.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">
{canBackground && (
<Button
variant="outline"
size="sm"
className="h-7 gap-1 text-xs"
disabled={backgroundSession.isPending}
onClick={() => backgroundSession.mutate(sessionID)}
title="Let running shell commands and subagents continue in the background"
>
{backgroundSession.isPending ? <Loader2 className="h-3 w-3 animate-spin" /> : <MoveDownRight className="h-3 w-3" />}
Move to background
</Button>
)}
{shells.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-yellow-600 dark:text-yellow-400" />
{shells.length} background shell{shells.length === 1 ? '' : 's'}
{expanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
)}
</div>
{expanded && shells.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-green-600 dark:text-green-400" />
<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>
))}
</ul>
)}
<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>
</DialogHeader>
{viewing && <ShellOutputView key={viewing.id} shell={viewing} directory={directory} running={viewingRunning} />}
</DialogContent>
</Dialog>
</div>
)
}