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.
This commit is contained in:
Chris Scott committed 2026-09-28 22:47:13 +00:00
1 parent a75d86c339
commit 409f2c4999
31 files changed
+1197 -279

No files matched your search

+22 -45
View File
@@ -1,5 +1,5 @@
import type { ConfigEntry, ModelInfo, ModelRef } from '@opencode-manager/shared/opencode'
import { formatOpenCodeModelRef, openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import type { ModelInfo, ModelRef } from '@opencode-manager/shared/opencode'
import { formatOpenCodeModelRef, openCodeLocation, parseOpenCodeModelRef, selectConfiguredModelRef } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from './opencode/client'
export interface ResolvedOpenCodeModel {
@@ -17,8 +17,6 @@ export interface ResolveOpenCodeModelOptions {
export const MODEL_LOAD_TIMEOUT_MS = 15_000
export const MODEL_LOAD_POLL_MS = 500
type ConfigDocumentModel = Extract<ConfigEntry, { type: 'document' }>['info']['model']
function normalizeModelCandidate(model: string | null | undefined): string | null {
if (!model) {
return null
@@ -70,22 +68,6 @@ function resolveFromLoadedModels(
return fallback ? toResolvedModel({ providerID: fallback.providerID, id: fallback.id }) : null
}
function toConfiguredRef(model: ConfigDocumentModel): ModelRef | undefined {
if (!model) {
return undefined
}
if (typeof model === 'string') {
return parseOpenCodeModelRef(model)
}
return {
providerID: model.providerID,
id: model.model,
...(model.variant ? { variant: model.variant } : {}),
}
}
function sleep(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (signal.aborted) {
@@ -154,11 +136,7 @@ async function readConfiguredRef(
signal: AbortSignal,
): Promise<ModelRef | undefined> {
const entries = await client.api.config.get(location, { signal })
const model = entries.reduce<ConfigDocumentModel>(
(current, entry) => (entry.type === 'document' && entry.info.model ? entry.info.model : current),
undefined,
)
return toConfiguredRef(model)
return selectConfiguredModelRef(entries)
}
export async function resolveOpenCodeModel(
@@ -193,31 +171,30 @@ export async function resolveOpenCodeModel(
break
}
const listResult = await runPollingRequest(
() => client.api.model.list(location, { signal }),
external,
timeoutController.signal,
)
if (!listResult.ok) {
break
}
models = listResult.value.data
const [listResult, defaultResult] = await Promise.all([
runPollingRequest(
() => client.api.model.list(location, { signal }),
external,
timeoutController.signal,
),
runPollingRequest(
() => client.api.model.default(location, { signal }),
external,
timeoutController.signal,
),
])
external?.throwIfAborted()
if (timeoutController.signal.aborted) {
break
if (listResult.ok) {
models = listResult.value.data
}
const defaultResult = await runPollingRequest(
() => client.api.model.default(location, { signal }),
external,
timeoutController.signal,
)
if (!defaultResult.ok) {
if (defaultResult.ok) {
defaultModel = defaultResult.value.data
}
if (!listResult.ok || !defaultResult.ok) {
break
}
defaultModel = defaultResult.value.data
external?.throwIfAborted()
+24 -24
View File
@@ -303,13 +303,8 @@ export class ScheduleService {
}
private static settleCancel(jobId: number, runId: number, status: ScheduleRun['status'] | undefined): void {
const pending = ScheduleService.pendingCancels.get(jobId)
if (pending?.runId !== runId || pending.resolved) {
return
}
pending.resolved = true
pending.resolve(status === 'cancelled' ? 'cancelled' : status === 'completed' || status === 'failed' ? 'settled' : 'resume')
const decision: CancelDecision = status === 'cancelled' ? 'cancelled' : status === 'completed' || status === 'failed' ? 'settled' : 'resume'
ScheduleService.resolveCancel(jobId, runId, decision)
}
private static resolveCancel(jobId: number, runId: number, decision: CancelDecision): void {
@@ -579,9 +574,7 @@ export class ScheduleService {
}
if (abort.signal.aborted) {
ScheduleService.clearCancel(jobId, run.id)
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
return this.loadRun(repoId, jobId, run.id, run)
return this.abandonCancelledStartup(repoId, jobId, run, job, repo)
}
const runJob = { ...job, agentSlug: await this.resolveRunAgent(runDirectory, job.agentSlug) }
@@ -591,9 +584,7 @@ export class ScheduleService {
})
if (abort.signal.aborted) {
ScheduleService.clearCancel(jobId, run.id)
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
return this.loadRun(repoId, jobId, run.id, run)
return this.abandonCancelledStartup(repoId, jobId, run, job, repo)
}
const sessionTitle = buildSessionTitle(job)
@@ -608,18 +599,13 @@ export class ScheduleService {
})
} catch (error) {
if (abort.signal.aborted) {
ScheduleService.clearCancel(jobId, run.id)
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
return this.loadRun(repoId, jobId, run.id, run)
return this.abandonCancelledStartup(repoId, jobId, run, job, repo)
}
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to create OpenCode session', 502)
}
if (abort.signal.aborted) {
await this.interruptCancelledSession(session.id)
ScheduleService.clearCancel(jobId, run.id)
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
return this.loadRun(repoId, jobId, run.id, run)
return this.abandonCancelledStartup(repoId, jobId, run, job, repo, session.id)
}
const runWithSession = updateScheduleRunMetadata(this.db, repoId, jobId, run.id, {
@@ -653,10 +639,7 @@ export class ScheduleService {
return runWithSession
} catch (error) {
if (abort.signal.aborted) {
ScheduleService.clearCancel(jobId, run.id)
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
ScheduleService.releaseActiveRun(jobId, run.id)
return this.loadRun(repoId, jobId, run.id, run)
return this.abandonCancelledStartup(repoId, jobId, run, job, repo)
}
const finishedAt = Date.now()
@@ -1124,6 +1107,23 @@ export class ScheduleService {
return getScheduleRunById(this.db, repoId, jobId, runId) ?? fallback
}
private async abandonCancelledStartup(
repoId: number,
jobId: number,
run: ScheduleRun,
job: ScheduleJob,
repo: Repo,
sessionId?: string,
): Promise<ScheduleRun> {
if (sessionId) {
await this.interruptCancelledSession(sessionId)
}
ScheduleService.clearCancel(jobId, run.id)
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
ScheduleService.releaseActiveRun(jobId, run.id)
return this.loadRun(repoId, jobId, run.id, run)
}
private async teardownWorktree(repoId: number, jobId: number, runId: number, job: ScheduleJob, repo: Repo): Promise<void> {
const key = `${repoId}:${jobId}:${runId}`
if (ScheduleService.activeTeardowns.has(key)) return
+36 -8
View File
@@ -1,7 +1,7 @@
import { EventSource } from 'eventsource'
import { logger } from '../utils/logger'
import { DEFAULTS } from '@opencode-manager/shared/config'
import { openCodeLocation, type OpenCodeApi, type V2Event } from '@opencode-manager/shared/opencode'
import { openCodeLocation, sessionIDFromEvent, type OpenCodeApi, type V2Event } from '@opencode-manager/shared/opencode'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './opencode/auth'
import { getOpenCodeUpstreamBaseUrl } from './opencode/upstream'
import { encodeSSEFrame } from '../utils/sse-frame'
@@ -44,6 +44,7 @@ class SSEAggregator {
private clients: Map<string, SSEClient> = new Map()
private directoryClients: Map<string, Set<string>> = new Map()
private activeSessions: Map<string, Set<string>> = new Map()
private sessionDirectories: Map<string, string> = new Map()
private eventListeners: Set<SSEEventListener> = new Set()
private subagentSessions: Map<string, Set<string>> = new Map()
private upstream: EventSource | null = null
@@ -284,12 +285,14 @@ class SSEAggregator {
for (const ref of this.getScheduledSessions()) {
tracked.set(ref.sessionID, ref.directory)
}
tracked.forEach((directory, sessionID) => this.sessionDirectories.set(sessionID, directory))
return tracked
}
private async resolveSessionDirectory(fetcher: PendingActionsFetcher, sessionID: string): Promise<string | null> {
try {
const session = await fetcher.api.session.get({ sessionID })
this.sessionDirectories.set(sessionID, session.location.directory)
return session.location.directory
} catch (error) {
logger.warn(`replay: failed to resolve directory for session ${sessionID}: ${String(error)}`)
@@ -403,24 +406,35 @@ class SSEAggregator {
const payloadJson = MULTILINE_PATTERN.test(data) ? JSON.stringify(event) : data
const directory = event.location?.directory
const sessionID = sessionIDFromEvent(event)
try {
const resolvedDirectory = directory ?? (sessionID ? this.sessionDirectories.get(sessionID) : undefined)
if (sessionID && event.type === 'session.deleted') {
this.sessionDirectories.delete(sessionID)
} else if (directory && sessionID) {
this.sessionDirectories.set(sessionID, directory)
}
if (directory) {
this.deliverEvent(directory, event, payloadJson)
} else {
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
return
}
if (resolvedDirectory) {
this.deliverResolvedEvent(resolvedDirectory, event, payloadJson)
return
}
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
} catch (error) {
logger.error(`SSE failed to handle ${event.type} event:`, error)
}
}
private deliverEvent(directory: string, event: SSEEvent, payloadJson?: string): void {
this.handleEvent(directory, event)
this.eventListeners.forEach(listener => {
try { listener(directory, event) } catch { /* ignore listener errors */ }
})
this.notifyEvent(directory, event)
const subscriberIds = this.directoryClients.get(directory)
if (!subscriberIds || subscriberIds.size === 0) return
@@ -428,6 +442,19 @@ class SSEAggregator {
this.writeEnvelopeToClients(subscriberIds, directory, payloadJson ?? JSON.stringify(event))
}
private deliverResolvedEvent(directory: string, event: SSEEvent, payloadJson: string): void {
this.notifyEvent(directory, event)
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
}
private notifyEvent(directory: string, event: SSEEvent): void {
this.handleEvent(directory, event)
this.eventListeners.forEach(listener => {
try { listener(directory, event) } catch { /* ignore listener errors */ }
})
}
private writeEnvelopeToClients(clientIds: Iterable<string>, directory: string | null, payloadJson: string): void {
let frame: Uint8Array | null = null
for (const clientId of clientIds) {
@@ -594,6 +621,7 @@ class SSEAggregator {
this.upstreamConnected = false
this.activeSessions.clear()
this.sessionDirectories.clear()
this.subagentSessions.clear()
this.directoryClients.clear()
this.clients.clear()
@@ -225,6 +225,24 @@ describe('resolveOpenCodeModel', () => {
expect(listCalls).toBe(3)
})
it('resolves an object configured model and preserves its variant', async () => {
const client = createClientStub({
models: [model('openai', 'gpt-5')],
configEntries: [
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-5', variant: 'high' } } } as ConfigEntry,
],
})
const result = await resolveOpenCodeModel(client, DIR)
expect(result).toEqual({
providerID: 'openai',
id: 'gpt-5',
variant: 'high',
model: 'openai/gpt-5#high',
})
})
it('does not resolve a same-provider fallback before the target model loads', async () => {
const client = createClientStub({
models: [model('openai', 'gpt-4')],
+46
View File
@@ -386,6 +386,52 @@ describe('ScheduleService', () => {
})
})
it('completes from a directory-less session.execution.succeeded resolved to the run directory', async () => {
const stub = createStubScheduleApi({
sessionID: 'ses-run-exec',
active: { 'ses-run-exec': { type: 'running' } },
})
const service = makeService(stub.api)
const runWithSession: ScheduleRun = {
...baseRun,
sessionId: 'ses-run-exec',
sessionTitle: 'Scheduled: Weekly engineering summary',
logText: 'Run started. Waiting for assistant response...',
}
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
mocks.getScheduleRunById.mockReturnValue(runWithSession)
await service.runJob(42, 7, 'manual')
await vi.waitFor(() => {
expect(stub.api.session.active).toHaveBeenCalled()
})
expect(mocks.updateScheduleRun).not.toHaveBeenCalled()
stub.state.active = {}
stub.state.messages = [assistantMessage('Execution summary.', { completed: true })]
captureEventListener()(repo.fullPath, {
id: 'evt_exec_succeeded',
created: Date.now(),
type: 'session.execution.succeeded',
data: { sessionID: 'ses-run-exec' },
})
await vi.waitFor(() => {
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
expect.anything(),
42,
7,
5,
expect.objectContaining({
status: 'completed',
responseText: 'Execution summary.',
}),
)
})
})
it('keeps waiting when an intermediate assistant step completes while the session is still busy', async () => {
const stub = createStubScheduleApi({
sessionID: 'ses-multi',
@@ -15,6 +15,7 @@ vi.mock('../../src/utils/logger', () => ({
}))
import type { OpenCodeApi } from '@opencode-manager/shared/opencode'
import { sessionIDFromEvent } from '@opencode-manager/shared/opencode'
import { sseAggregator, type PendingActionsFetcher } from '../../src/services/sse-aggregator'
interface CapturedEvent {
@@ -647,3 +648,91 @@ describe('SSEAggregator directory-indexed broadcast', () => {
expect(clientB.frames).toHaveLength(1)
})
})
describe('SSEAggregator directory-less session event routing', () => {
beforeEach(() => {
sseAggregator.shutdown()
sseAggregator.setPendingActionsFetcher(null)
sseAggregator.setScheduledSessionsResolver(() => [])
})
it('resolves a directory-less terminal event from the remembered directory for listeners, active sessions, and all clients', () => {
const subscribed = createCapturingClient()
const global = createCapturingClient()
sseAggregator.addClient('resolved-a', subscribed.callback, subscribed.writeFrame, ['/r'])
sseAggregator.addClient('resolved-b', global.callback, global.writeFrame, [])
const seen: Array<{ directory: string; type: string; sessionID: string }> = []
sseAggregator.onEvent((directory, event) => {
seen.push({ directory, type: event.type, sessionID: sessionIDFromEvent(event) ?? '' })
})
emitRawEvent({ type: 'session.execution.started', location: { directory: '/r' }, data: { sessionID: 'ses_1' } })
expect(sseAggregator.getActiveSessions()).toEqual({ '/r': ['ses_1'] })
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_1' } })
expect(seen).toEqual([
{ directory: '/r', type: 'session.execution.started', sessionID: 'ses_1' },
{ directory: '/r', type: 'session.execution.succeeded', sessionID: 'ses_1' },
])
expect(sseAggregator.getActiveSessions()).toEqual({})
expect(subscribed.frames.map(parseFrame)).toEqual([
{
directory: '/r',
payload: { id: 'evt_1', created: 1, type: 'session.execution.started', location: { directory: '/r' }, data: { sessionID: 'ses_1' } },
},
{
directory: null,
payload: { id: 'evt_1', created: 1, type: 'session.execution.succeeded', data: { sessionID: 'ses_1' } },
},
])
expect(global.frames.map(parseFrame)).toEqual([
{
directory: null,
payload: { id: 'evt_1', created: 1, type: 'session.execution.succeeded', data: { sessionID: 'ses_1' } },
},
])
})
it('broadcasts a directory-less event from an unknown session without notifying listeners', () => {
const client = createCapturingClient()
sseAggregator.addClient('unknown-a', client.callback, client.writeFrame, ['/r'])
const seen: string[] = []
sseAggregator.onEvent((_directory, event) => { seen.push(event.type) })
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_unknown' } })
expect(seen).toEqual([])
expect(sseAggregator.getActiveSessions()).toEqual({})
expect(client.frames.map(parseFrame)).toEqual([
{
directory: null,
payload: { id: 'evt_1', created: 1, type: 'session.execution.succeeded', data: { sessionID: 'ses_unknown' } },
},
])
})
it('forgets the remembered directory when session.deleted arrives', () => {
const client = createCapturingClient()
sseAggregator.addClient('deleted-a', client.callback, client.writeFrame, ['/r'])
const seen: string[] = []
sseAggregator.onEvent((_directory, event) => { seen.push(event.type) })
emitRawEvent({ type: 'session.created', location: { directory: '/r' }, data: { sessionID: 'ses_del' } })
emitRawEvent({ type: 'session.deleted', data: { sessionID: 'ses_del' } })
seen.length = 0
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_del' } })
expect(seen).toEqual([])
expect(sseAggregator.getActiveSessions()).toEqual({})
expect(client.frames.map(parseFrame).at(-1)).toEqual({
directory: null,
payload: { id: 'evt_1', created: 1, type: 'session.execution.succeeded', data: { sessionID: 'ses_del' } },
})
})
})
+12
View File
@@ -12,6 +12,18 @@ Messages stream in real-time using Server-Sent Events (SSE):
![Chat Conversation](../images/chat-conversation.png)
## Background Work
While a shell command or subagent is running, **Move to background** above the prompt lets it keep running while the session continues. The background tasks bar lists each background shell and subagent with its status:
- **running** - still working
- **completed** / **failed** - finished, using the shell exit code or the subagent outcome
- **killed** - you stopped the shell from the bar
- **interrupted** - the subagent was interrupted
- **unavailable** - OpenCode no longer knows the shell and the session has no completion notice for it
Shell rows can show live output and be killed; subagent rows open the child session. Statuses are reconciled when the connection returns, so work that finished while you were away is shown as finished. After a page reload, a shell you killed is shown as **failed**, which matches OpenCode's own notice for it.
## Model Selection
Click the **model name** in the chat prompt area to open the quick model switcher, where you can switch models, mark favorites, and pick variants without leaving the chat. Each agent keeps its own model selection. See [AI Configuration](ai-config.md#model-selection) for the full reference.
+3 -12
View File
@@ -2,7 +2,7 @@ import { API_BASE_URL } from "@/config";
import { settingsApi } from "./settings";
import { fetchWrapper } from "./fetchWrapper";
import { callOpenCode } from "./opencodeApi";
import { openCodeLocation, type ConfigEntry, type FormAnswer, type ModelInfo } from "@opencode-manager/shared/opencode";
import { openCodeLocation, selectConfiguredModelRef, type FormAnswer, type ModelInfo } from "@opencode-manager/shared/opencode";
import type { CredentialListResponse, CredentialStatusResponse } from "@opencode-manager/shared/schemas";
import type { OpenCodeConfigFile } from "./types/settings";
@@ -128,20 +128,11 @@ export async function getProviders(directory?: string): Promise<ProvidersResult>
}
}
type ConfigDocumentModel = Extract<ConfigEntry, { type: "document" }>["info"]["model"];
function formatConfigModel(model: NonNullable<ConfigDocumentModel>): string {
return typeof model === "string" ? model : `${model.providerID}/${model.model}`;
}
export async function getOpenCodeConfigModel(directory?: string): Promise<string | null> {
try {
const entries = await callOpenCode((api) => api.config.get(openCodeLocation(directory)));
const model = entries.reduce<ConfigDocumentModel>(
(current, entry) => (entry.type === "document" && entry.info.model ? entry.info.model : current),
undefined,
);
return model ? formatConfigModel(model) : null;
const ref = selectConfiguredModelRef(entries);
return ref ? `${ref.providerID}/${ref.id}` : null;
} catch {
return null;
}
@@ -3,6 +3,7 @@ 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]
@@ -10,11 +11,12 @@ 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, directory, 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
@@ -42,6 +44,7 @@ export const MessagePart = memo(function MessagePart({ part, messageID, director
part={part}
messageID={messageID}
directory={directory}
shellOutcome={shellOutcome}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -204,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
@@ -480,6 +485,7 @@ const MessageRow = memo(function MessageRow({
part={part}
messageID={message.id}
directory={directory}
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -518,6 +524,7 @@ const MessageRow = memo(function MessageRow({
part={part}
messageID={message.id}
directory={directory}
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
/>
@@ -609,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
@@ -658,6 +674,7 @@ export const MessageThread = memo(function MessageThread({
model={model}
simpleChatMode={simpleChatMode}
showReasoning={showReasoning}
shellOutcomes={shellOutcomes}
/>
))}
{pending.map((item) => (
@@ -200,8 +200,8 @@ describe('ToolCallPart background indicator', () => {
expect(screen.getByText('completed')).toBeInTheDocument()
})
it('shows a background shell missing from a loaded list as unavailable', async () => {
renderWithProviders(
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"
@@ -211,6 +211,36 @@ describe('ToolCallPart background indicator', () => {
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', () => {
@@ -8,18 +8,22 @@ import { useToolCallPermission } from '@/contexts/EventContext'
import { useChildSessionReconciliation } from '@/hooks/useOpenCode'
import { useShell } from '@/hooks/useSessionShells'
import { detectFileReferences } from '@/lib/fileReferences'
import { ExternalLink, Loader2, Shield, Square } from 'lucide-react'
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 { getToolSpecificRender } from './FileToolRender'
@@ -54,6 +58,7 @@ interface ToolCallPartProps {
part: SessionMessageAssistantTool
messageID?: string
directory?: string
shellOutcome?: ShellNoticeOutcome
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
}
@@ -68,11 +73,6 @@ function toolOutputText(part: SessionMessageAssistantTool): string {
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])
@@ -113,11 +113,11 @@ 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, directory, 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 subagentSessionId = isSubagent ? subagentSessionID(part) : undefined
const backgroundSubagent = isSubagent ? backgroundChildSessionID(part) : undefined
const subagentSessionLifecycle = useChildLifecycleForSession(subagentSessionId)
useChildSessionReconciliation(
@@ -132,7 +132,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
)
const backgroundShell = part.name === 'shell' ? backgroundShellID(part) : undefined
const { shell, listLoaded: shellListLoaded } = useShell(backgroundShell, directory)
const shellStatus = shellToolLifecycle(backgroundShell, shell, shellListLoaded)
const shellStatus = shellToolLifecycle(backgroundShell, shell, shellListLoaded, shellOutcome)
const isBackgroundShell = backgroundShell !== undefined
const isBackgroundShellRunning = isBackgroundShell && isRunningLifecycle(shellStatus)
const pendingPermission = useToolCallPermission(part.id, messageID)
@@ -162,12 +162,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
}, [expanded, part.name])
const getStatusColor = () => {
if (isBackgroundShell) {
if (shellStatus === 'completed') return 'text-success'
if (shellStatus === 'failed') return 'text-destructive'
if (shellStatus === 'killed') return 'text-warning'
return 'text-warning'
}
if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus)
switch (part.state.status) {
case 'completed':
return 'text-success'
@@ -181,12 +176,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
}
}
const renderShellLifecycleIcon = (status: BackgroundTaskLifecycle) => {
if (status === 'completed') return <span className="text-success">✓</span>
if (status === 'failed') return <span className="text-destructive">✗</span>
if (status === 'killed') return <Square className="w-3.5 h-3.5 text-warning" />
return <Loader2 className="w-3.5 h-3.5 animate-spin text-warning" />
}
const renderShellLifecycleIcon = (status: BackgroundTaskLifecycle) => (
<BackgroundTaskStatusIcon status={status} className="w-3.5 h-3.5" />
)
const getStatusIcon = () => {
if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus)
@@ -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`} />
}
@@ -75,6 +75,18 @@ const backgroundShellTool = (shellID: string, command = 'npm run dev'): SessionM
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',
@@ -171,6 +183,7 @@ describe('BackgroundWorkBar', () => {
await waitFor(() => expect(api.removeShell).toHaveBeenCalledWith('dev', '/repo'))
expect(await screen.findByText('killed')).toBeInTheDocument()
expect(screen.getByText('npm run dev')).toBeInTheDocument()
clearShellExitRecord('/repo', 'dev')
})
it('updates a shell row from running to completed without removing it', async () => {
@@ -345,6 +358,32 @@ describe('BackgroundWorkBar', () => {
expect(screen.queryByText('running')).not.toBeInTheDocument()
})
it('shows a historical shell absent from the list as completed from its notice', async () => {
api.listShells.mockResolvedValue([])
renderBar(
[backgroundShellTool('sh-notice', 'npm run notice'), shellNotice('sh-notice', 'completed', 0)],
false,
)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('completed')).toBeInTheDocument()
expect(screen.queryByText('unavailable')).not.toBeInTheDocument()
})
it('shows a historical shell absent from the list as failed from its error notice', async () => {
api.listShells.mockResolvedValue([])
renderBar(
[backgroundShellTool('sh-notice', 'npm run notice'), shellNotice('sh-notice', 'error')],
false,
)
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
expect(await screen.findByText('failed')).toBeInTheDocument()
expect(screen.queryByText('unavailable')).not.toBeInTheDocument()
})
it('keeps a historical shell unknown while its list is still loading', async () => {
api.listShells.mockImplementation(() => new Promise(() => {}))
renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { Ban, Bot, Check, ChevronDown, ChevronUp, ExternalLink, Loader2, MoveDownRight, Square, Terminal, XCircle } from 'lucide-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 } from '@/api/opencode'
import { Button } from '@/components/ui/button'
@@ -7,8 +8,11 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f
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,
@@ -119,15 +123,6 @@ function ShellOutputView({ shell, directory, running }: { shell: ShellRecord; di
)
}
function BackgroundTaskStatusIcon({ status }: { status: BackgroundTaskLifecycle }) {
if (status === 'completed') return <Check className="h-3 w-3 text-success" />
if (status === 'failed') return <XCircle className="h-3 w-3 text-destructive" />
if (status === 'interrupted') return <Ban className="h-3 w-3 text-warning" />
if (status === 'killed') return <Square className="h-3 w-3 text-warning" />
if (status === 'unavailable') return <XCircle className="h-3 w-3 text-muted-foreground" />
return <Loader2 className="h-3 w-3 animate-spin text-warning" />
}
function BackgroundTaskKindIcon({ task }: { task: BackgroundTask }) {
return task.kind === 'shell'
? <Terminal className="h-3 w-3 shrink-0 text-success" />
@@ -155,7 +150,7 @@ function BackgroundTaskRow({
<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} />
<BackgroundTaskStatusIcon status={task.status} className="h-3 w-3" />
{lifecycleLabel(task.status)}
</span>
{task.kind === 'shell' && task.shell && (
@@ -202,9 +197,20 @@ interface BackgroundWorkBarProps {
export function BackgroundWorkBar({ sessionID, directory, messages, isSessionActive, onChildSessionClick }: BackgroundWorkBarProps) {
const { shells, listLoaded } = useSessionShells(sessionID, directory)
const statuses = useSessionStatus((state) => state.statuses)
const knownSessions = useSessionStatus((state) => state.knownSessions)
const outcomes = useSessionStatus((state) => state.outcomes)
const 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)
@@ -212,10 +218,10 @@ export function BackgroundWorkBar({ sessionID, directory, messages, isSessionAct
const tasks = useMemo(
() => [
...shellBackgroundTasks(shells, messages, listLoaded),
...subagentBackgroundTasks(messages, statuses, knownSessions, outcomes),
...shellBackgroundTasks(shells, collected.shells, collected.shellNotices, listLoaded),
...subagentBackgroundTasks(collected.subagents, childLifecycles),
],
[shells, messages, listLoaded, statuses, knownSessions, outcomes],
[shells, collected, listLoaded, childLifecycles],
)
const hasRunningTask = tasks.some((task) => isRunningLifecycle(task.status))
+88 -10
View File
@@ -1026,8 +1026,8 @@ describe('EventProvider permissions and forms', () => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(true)
expect(useSessionStatus.getState().isSessionKnown('child-unknown')).toBe(false)
expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-unknown')).toBe(false)
})
it('does not treat a child omitted from a global snapshot as finished', async () => {
@@ -1052,7 +1052,7 @@ describe('EventProvider permissions and forms', () => {
})
await waitFor(() => {
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(false)
expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(false)
})
})
@@ -1069,14 +1069,14 @@ describe('EventProvider permissions and forms', () => {
onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed')
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
act(() => {
onEvent({ type: 'session.idle', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed')
})
it('records an interrupted child outcome', async () => {
@@ -1091,7 +1091,7 @@ describe('EventProvider permissions and forms', () => {
onEvent({ type: 'session.execution.interrupted', data: { sessionID: 'child-1', reason: 'user' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('interrupted')
expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('interrupted')
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
})
@@ -1110,16 +1110,16 @@ describe('EventProvider permissions and forms', () => {
act(() => {
onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed')
act(() => {
handleStatusChange(true)
})
await waitFor(() => {
expect(useSessionStatus.getState().getOutcome('child-1')).toBe('failed')
expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed')
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true)
})
})
@@ -1136,7 +1136,85 @@ describe('EventProvider permissions and forms', () => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBeUndefined()
expect(useSessionStatus.getState().outcomes.get('child-1')).toBeUndefined()
})
it('forgets a deleted session status, knowledge, and outcome while keeping the list invalidation', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'session.execution.failed', data: { sessionID: 'child-1', error: { message: 'boom' } }, directory: '/repo' })
})
expect(useSessionStatus.getState().outcomes.get('child-1')).toBe('failed')
expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true)
act(() => {
onEvent({ type: 'session.deleted', data: { sessionID: 'child-1' }, directory: '/repo' })
})
const after = useSessionStatus.getState()
expect(after.statuses.has('child-1')).toBe(false)
expect(after.knownSessions.has('child-1')).toBe(false)
expect(after.outcomes.has('child-1')).toBe(false)
await waitFor(() => {
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true)
})
})
it('invalidates only the reconciliation of children that moved from busy to unknown during a poll', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions
.mockResolvedValueOnce({ 'child-1': { type: 'running' }, 'child-2': { type: 'running' } })
.mockResolvedValue({ 'child-2': { type: 'running' } })
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
queryClient.setQueryData(['opencode', 'session-reconcile', 'child-1'], { id: 'child-1' })
queryClient.setQueryData(['opencode', 'session-reconcile', 'child-2'], { id: 'child-2' })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
vi.useFakeTimers()
try {
act(() => {
handleStatusChange(true)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(0)
})
expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true)
invalidateQueries.mockClear()
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: ['opencode', 'session-reconcile', 'child-1'],
})
expect(invalidateQueries).not.toHaveBeenCalledWith({
queryKey: ['opencode', 'session-reconcile', 'child-2'],
})
expect(invalidateQueries).not.toHaveBeenCalledWith({
queryKey: ['opencode', 'session-reconcile'],
})
} finally {
vi.useRealTimers()
}
})
it('reconciles the global active snapshot on reconnect and clears omitted sessions', async () => {
+17 -2
View File
@@ -393,17 +393,28 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
return
}
const busyBeforeSnapshot = new Set<string>()
for (const [sessionID, status] of useSessionStatus.getState().statuses.entries()) {
if (status.type !== 'idle') busyBeforeSnapshot.add(sessionID)
}
useSessionStatus.getState().replaceStatuses(
busyStatusesFromActiveSessions(active),
snapshotToken,
)
const knownAfterSnapshot = useSessionStatus.getState().knownSessions
const becameUnknown = [...busyBeforeSnapshot].filter(
(sessionID) => !knownAfterSnapshot.has(sessionID),
)
if (becameUnknown.length > 0) {
invalidateChildSessionCaches(queryClient, becameUnknown)
}
} catch (error) {
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
if (import.meta.env.DEV) {
console.warn('Failed to fetch active sessions:', error)
}
}
}, [])
}, [queryClient])
const stopStatusPoll = useCallback(() => {
if (statusPollIntervalRef.current === null) return
@@ -492,9 +503,13 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
}
case 'session.deleted': {
useSessionStatus.getState().forgetSession(event.data.sessionID)
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
}
case 'session.created':
case 'session.renamed':
case 'session.deleted':
case 'session.moved':
case 'session.metadata.updated':
invalidateSessionListCachesDebounced(queryClient, event.directory)
+21 -7
View File
@@ -260,7 +260,7 @@ describe('useChildSessionReconciliation', () => {
expect(mocks.getSession).toHaveBeenCalledTimes(1)
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'idle' })
expect(useSessionStatus.getState().isSessionKnown('child-1')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-1')).toBe(true)
first.unmount()
second.unmount()
@@ -293,10 +293,8 @@ describe('useChildSessionReconciliation', () => {
})
it('clears a stale child outcome when the fresh snapshot is busy', async () => {
mocks.getSession.mockResolvedValue({
...sessionInfo('child-1', '/repo'),
outcome: 'failed',
})
mocks.getSession.mockResolvedValue(sessionInfo('child-1', '/repo'))
useSessionStatus.getState().setStatus('child-1', { type: 'busy' })
useSessionStatus.getState().setOutcome('child-1', 'failed')
const queryClient = createQueryClient()
@@ -305,8 +303,24 @@ describe('useChildSessionReconciliation', () => {
})
await waitFor(() => {
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().statuses.get('child-1')).toEqual({ type: 'busy' })
})
expect(useSessionStatus.getState().getOutcome('child-1')).toBeUndefined()
expect(useSessionStatus.getState().outcomes.get('child-1')).toBeUndefined()
})
it('does not reconcile a child whose lifecycle is already terminal', async () => {
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
const queryClient = createQueryClient()
renderHook(() => useChildSessionReconciliation('child-1'), {
wrapper: createWrapper(queryClient),
})
await act(async () => {
await Promise.resolve()
})
expect(mocks.getSession).not.toHaveBeenCalled()
expect(queryClient.getQueryState(['opencode', 'session-reconcile', 'child-1'])?.fetchStatus).not.toBe('fetching')
})
})
+7 -6
View File
@@ -23,7 +23,8 @@ import type { ModelRef, SessionInfo } from "@opencode-manager/shared/opencode";
import { parseNetworkError, isGatewayTimeout } from "../lib/opencode-errors";
import { showToast } from "../lib/toast";
import { useSendErrorStore } from "../stores/sendErrorStore";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { useSessionStatus, useChildLifecycleForSession } from "../stores/sessionStatusStore";
import { isRunningLifecycle } from "../lib/backgroundWork";
import { childSessionReconciliationQueryKey, invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation";
import { buildPinnedSessionKeys, buildSessionKey } from "../lib/sessionKey";
import { toggleSessionPin } from "../api/sessionPins";
@@ -148,6 +149,7 @@ export const useSession = (sessionID: string | undefined, directory?: string) =>
};
export const useChildSessionReconciliation = (sessionID: string | undefined) => {
const lifecycle = useChildLifecycleForSession(sessionID)
useQuery({
queryKey: childSessionReconciliationQueryKey(sessionID),
queryFn: async () => {
@@ -160,11 +162,10 @@ export const useChildSessionReconciliation = (sessionID: string | undefined) =>
useSessionStatus.getState().endStatusSnapshot(token);
}
},
enabled: !!sessionID,
staleTime: 0,
refetchOnMount: 'always',
refetchOnReconnect: true,
refetchOnWindowFocus: true,
enabled: !!sessionID && isRunningLifecycle(lifecycle),
staleTime: 5_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
};
+65 -2
View File
@@ -3,6 +3,8 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useSSE } from './useSSE'
import { useKillShell } from './useSessionShells'
import { clearShellExitRecord } from '@/lib/backgroundWork'
import { useSessionStatus } from '../stores/sessionStatusStore'
import { useSendErrorStore } from '../stores/sendErrorStore'
import { showToast } from '@/lib/toast'
@@ -17,6 +19,16 @@ vi.mock('@/lib/toast', () => ({
},
}))
const shellApi = vi.hoisted(() => ({
listShells: vi.fn(),
removeShell: vi.fn(),
}))
vi.mock('@/api/opencode', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/opencode')>()),
...shellApi,
}))
class MockEventSource {
static instances: MockEventSource[] = []
@@ -53,6 +65,8 @@ describe('useSSE', () => {
beforeEach(() => {
vi.clearAllMocks()
MockEventSource.instances = []
shellApi.listShells.mockResolvedValue([])
shellApi.removeShell.mockResolvedValue(undefined)
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
@@ -120,7 +134,7 @@ describe('useSSE', () => {
queryKey: ['opencode', 'pending-actions', 'session-1', '/repo'],
})
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'shells'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'] })
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'] })
})
unmount()
@@ -359,7 +373,7 @@ describe('useSSE', () => {
queryKey: ['opencode', 'pending-actions', 'session-1', '/repo'],
})
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'shells'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'] })
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'session-reconcile'] })
unmount()
})
@@ -544,6 +558,55 @@ describe('useSSE', () => {
unmount()
})
it('keeps a killed shell killed after a later shell.exited event', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const key = ['opencode', 'shells', '/repo']
queryClient.setQueryData(key, [
{
id: 'shell-1',
status: 'running',
command: 'sleep 1',
cwd: '/repo',
shell: 'zsh',
file: '/tmp/shell-1.log',
metadata: { sessionID: 'session-1' },
time: { started: 1 },
},
])
const { result, unmount } = renderHook(
() => ({ sse: useSSE('/repo', 'session-1'), kill: useKillShell('/repo') }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.sse.isConnected).toBe(true))
await act(async () => {
await result.current.kill.mutateAsync('shell-1')
})
expect(queryClient.getQueryData<Array<{ status: string }>>(key)?.[0]?.status).toBe('killed')
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'shell.exited',
directory: '/repo',
data: { id: 'shell-1', status: 'exited' },
})
})
expect(queryClient.getQueryData<Array<{ status: string }>>(key)?.[0]?.status).toBe('killed')
unmount()
clearShellExitRecord('/repo', 'shell-1')
})
it('does not write session status from stream events', async () => {
const queryClient = new QueryClient({
defaultOptions: {
+3 -5
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { SessionInfo, V2Event } from '@opencode-manager/shared/opencode'
import { invalidateChildSessionCaches, invalidateSessionListCaches, shellsQueryKey } from '@/lib/queryInvalidation'
import { invalidateSessionListCaches, invalidateShellCaches, shellsQueryKey } from '@/lib/queryInvalidation'
import {
applyShellExit,
markShellDeleted,
@@ -201,8 +201,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
if (connected) {
setError(null)
syncCurrentSession()
queryClient.invalidateQueries({ queryKey: ['opencode', 'shells'] })
invalidateChildSessionCaches(queryClient)
invalidateShellCaches(queryClient)
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
} else {
setError('Connection lost. Reconnecting...')
@@ -212,8 +211,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
const handleResync = () => {
if (!mountedRef.current) return
invalidateSessionListCaches(queryClient)
queryClient.invalidateQueries({ queryKey: ['opencode', 'shells'] })
invalidateChildSessionCaches(queryClient)
invalidateShellCaches(queryClient)
refreshCurrentSession()
}
@@ -0,0 +1,161 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useKillShell, useShell } from './useSessionShells'
import { applyShellExit, clearShellExitRecord, recordShellExit, type ShellRecord } from '@/lib/backgroundWork'
const api = vi.hoisted(() => ({
listShells: 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'): ShellRecord => ({
id,
status: 'running',
command: `npm run ${id}`,
cwd: '/repo',
shell: 'zsh',
file: `/tmp/${id}.log`,
metadata: { sessionID },
time: { started: 1 },
})
const createWrapper = (queryClient: QueryClient) => {
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } })
describe('useKillShell', () => {
beforeEach(() => {
vi.clearAllMocks()
api.listShells.mockResolvedValue([])
api.removeShell.mockResolvedValue(undefined)
})
it('marks a killed shell terminal without erasing it', async () => {
const queryClient = createQueryClient()
queryClient.setQueryData(['opencode', 'shells', '/repo'], [shell('dev')])
const { result } = renderHook(() => useKillShell('/repo'), {
wrapper: createWrapper(queryClient),
})
await act(async () => {
await result.current.mutateAsync('dev')
})
const [updated] = queryClient.getQueryData<ShellRecord[]>(['opencode', 'shells', '/repo']) ?? []
expect(updated?.status).toBe('killed')
expect(updated?.time.completed).toBeDefined()
clearShellExitRecord('/repo', 'dev')
})
it('records a killed shell so a later refetch keeps it killed', async () => {
const queryClient = createQueryClient()
const key = ['opencode', 'shells', '/repo']
queryClient.setQueryData(key, [shell('dev')])
const { result } = renderHook(
() => ({ kill: useKillShell('/repo'), shell: useShell('dev', '/repo') }),
{ wrapper: createWrapper(queryClient) },
)
await act(async () => {
await result.current.kill.mutateAsync('dev')
})
queryClient.setQueryData(key, [])
api.listShells.mockResolvedValue([shell('dev')])
await act(async () => {
await queryClient.invalidateQueries({ queryKey: key })
})
const [refetched] = queryClient.getQueryData<ShellRecord[]>(key) ?? []
expect(refetched?.status).toBe('killed')
clearShellExitRecord('/repo', 'dev')
})
it('keeps a killed shell killed through a later exit event', async () => {
const queryClient = createQueryClient()
const key = ['opencode', 'shells', '/repo']
queryClient.setQueryData(key, [shell('dev')])
const { result } = renderHook(() => useKillShell('/repo'), {
wrapper: createWrapper(queryClient),
})
await act(async () => {
await result.current.mutateAsync('dev')
})
await act(async () => {
recordShellExit('/repo', { id: 'dev', status: 'exited', exit: 0 })
queryClient.setQueryData<ShellRecord[]>(key, (current) =>
current ? applyShellExit(current, { id: 'dev', status: 'exited', exit: 0 }) : current,
)
})
const [after] = queryClient.getQueryData<ShellRecord[]>(key) ?? []
expect(after?.status).toBe('killed')
clearShellExitRecord('/repo', 'dev')
})
})
describe('useShell', () => {
beforeEach(() => {
vi.clearAllMocks()
api.listShells.mockResolvedValue([])
api.removeShell.mockResolvedValue(undefined)
})
it('returns only the matching shell record once the list loads', async () => {
const queryClient = createQueryClient()
api.listShells.mockResolvedValue([shell('dev'), shell('other')])
const { result } = renderHook(() => useShell('dev', '/repo'), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(result.current.shell?.id).toBe('dev'))
expect(result.current.listLoaded).toBe(true)
})
it('does not re-render when an unrelated shell record changes', async () => {
const queryClient = createQueryClient()
const dev = shell('dev')
const other = shell('other')
api.listShells.mockResolvedValue([dev, other])
let renderCount = 0
const { result } = renderHook(
() => {
renderCount += 1
return useShell('dev', '/repo')
},
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(result.current.shell).toBe(dev))
const rendersAfterLoad = renderCount
await act(async () => {
queryClient.setQueryData(['opencode', 'shells', '/repo'], [dev, { ...other, command: 'changed' }])
})
expect(renderCount).toBe(rendersAfterLoad)
})
})
+16 -15
View File
@@ -1,16 +1,20 @@
import { useMemo } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { listShells, removeShell } from '@/api/opencode'
import { reconcileShellList, type ShellRecord } from '@/lib/backgroundWork'
import { applyShellExit, recordShellExit, reconcileShellList, type ShellRecord } from '@/lib/backgroundWork'
import { shellsQueryKey } from '@/lib/queryInvalidation'
import { showToast } from '@/lib/toast'
function useShellListQuery(directory: string | undefined, enabled: boolean) {
function useShellListQuery<TData = ShellRecord[]>(
directory: string | undefined,
enabled: boolean,
select?: (shells: ShellRecord[]) => TData,
) {
const queryClient = useQueryClient()
return useQuery({
return useQuery<ShellRecord[], Error, TData>({
queryKey: shellsQueryKey(directory),
queryFn: async () => {
queryFn: async (): Promise<ShellRecord[]> => {
const fetchStartedAt = Date.now()
const fetched = await listShells(directory ?? '')
const existing = queryClient.getQueryData<ShellRecord[]>(shellsQueryKey(directory)) ?? []
@@ -18,6 +22,7 @@ function useShellListQuery(directory: string | undefined, enabled: boolean) {
},
enabled,
staleTime: Infinity,
select,
})
}
@@ -35,16 +40,15 @@ export function useSessionShells(sessionID: string | undefined, directory: strin
}
export function useShell(shellID: string | undefined, directory: string | undefined) {
const query = useShellListQuery(directory, Boolean(directory && shellID))
const shell = useMemo(
() => (query.data ?? []).find((candidate) => candidate.id === shellID),
[query.data, shellID],
const query = useShellListQuery<ShellRecord | undefined>(
directory,
Boolean(directory && shellID),
(shells) => shells.find((candidate) => candidate.id === shellID),
)
const listLoaded = query.isSuccess
return { shell, listLoaded }
return { shell: query.data, listLoaded }
}
export function useKillShell(directory: string | undefined) {
@@ -53,12 +57,9 @@ export function useKillShell(directory: string | undefined) {
return useMutation({
mutationFn: (id: string) => removeShell(id, directory ?? ''),
onSuccess: (_result, id) => {
recordShellExit(directory ?? '', { id, status: 'killed' })
queryClient.setQueryData<ShellRecord[]>(shellsQueryKey(directory), (current) =>
current?.map((shell) =>
shell.id === id
? { ...shell, status: 'killed', time: { ...shell.time, completed: shell.time.completed ?? Date.now() } }
: shell,
),
current && applyShellExit(current, { id, status: 'killed' }),
)
},
onError: (error) => {
+138
View File
@@ -1,13 +1,16 @@
import { describe, expect, it } from 'vitest'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import {
applyShellExit,
childLifecycle,
clearShellExitRecord,
collectBackgroundParts,
isRunningLifecycle,
markShellDeleted,
reconcileShellList,
recordShellDeleted,
recordShellExit,
shellBackgroundTasks,
shellLifecycle,
shellToolLifecycle,
subagentLifecycle,
@@ -15,6 +18,19 @@ import {
type ShellRecord,
} from './backgroundWork'
const shellNotice = (
id: string,
shellID: string,
state: 'completed' | 'error',
exit?: number,
): SessionMessageInfo => ({
id,
type: 'synthetic',
text: '',
metadata: { source: 'shell', shellID, state, ...(exit === undefined ? {} : { exit }) },
time: { created: 1 },
})
const shell = (id: string, status: ShellRecord['status'], exit?: number, started = 1): ShellRecord => ({
id,
status,
@@ -106,6 +122,67 @@ describe('shellToolLifecycle', () => {
expect(shellToolLifecycle('sh_1', undefined, false)).toBe('unknown')
expect(shellToolLifecycle('sh_1', undefined, true)).toBe('unavailable')
})
it('falls back to the transcript notice outcome when the shell is absent', () => {
expect(shellToolLifecycle('sh_1', undefined, true, 'completed')).toBe('completed')
expect(shellToolLifecycle('sh_1', undefined, true, 'failed')).toBe('failed')
})
it('prefers the live shell record over the transcript notice outcome', () => {
expect(shellToolLifecycle('sh_1', shell('sh_1', 'running'), true, 'failed')).toBe('running')
})
})
describe('collectBackgroundParts', () => {
it('collects shell completion notices by shell ID', () => {
const collected = collectBackgroundParts([
shellNotice('syn-1', 'sh_1', 'completed', 0),
shellNotice('syn-2', 'sh_2', 'error'),
shellNotice('syn-3', 'sh_3', 'completed'),
])
expect(collected.shellNotices.get('sh_1')).toBe('completed')
expect(collected.shellNotices.get('sh_2')).toBe('failed')
expect(collected.shellNotices.get('sh_3')).toBe('completed')
})
it('ignores notices without a shell ID', () => {
const collected = collectBackgroundParts([
{
id: 'syn-1',
type: 'synthetic',
text: '',
metadata: { source: 'shell', state: 'completed' },
time: { created: 1 },
},
])
expect(collected.shellNotices.size).toBe(0)
})
})
describe('shellBackgroundTasks', () => {
it('uses a transcript notice when the shell has no live record', () => {
const tasks = shellBackgroundTasks(
[],
[{ id: 'sh_1', label: 'npm run dev' }],
new Map([['sh_1', 'completed']]),
true,
)
expect(tasks[0]?.status).toBe('completed')
})
it('uses a failed transcript notice when the shell has no live record', () => {
const tasks = shellBackgroundTasks(
[],
[{ id: 'sh_1', label: 'npm run dev' }],
new Map([['sh_1', 'failed']]),
true,
)
expect(tasks[0]?.status).toBe('failed')
})
})
describe('reconcileShellList', () => {
@@ -173,6 +250,55 @@ describe('reconcileShellList', () => {
clearShellExitRecord('/other', 'a')
})
it('prunes a shell exit record once a later fetch confirms the terminal status', () => {
recordShellExit('/repo', { id: 'a', status: 'exited', exit: 0 })
const [result] = reconcileShellList([], [shell('a', 'exited', 0)], Date.now() + 1000, '/repo')
expect(result?.status).toBe('exited')
const [afterPrune] = upsertShell([], shell('a', 'running'), '/repo')
expect(afterPrune?.status).toBe('running')
})
it('keeps a shell exit record when the fetch started before it was written', () => {
const fetchStartedAt = Date.now() - 1000
recordShellExit('/repo', { id: 'a', status: 'exited', exit: 0 })
const [result] = reconcileShellList([], [shell('a', 'exited', 0)], fetchStartedAt, '/repo')
expect(result?.status).toBe('exited')
const [afterStaleFetch] = upsertShell([], shell('a', 'running'), '/repo')
expect(afterStaleFetch?.status).toBe('exited')
clearShellExitRecord('/repo', 'a')
})
it('prunes a shell exit record once a later fetch omits a terminal shell', () => {
recordShellExit('/repo', { id: 'a', status: 'exited', exit: 0 })
const cached = shell('a', 'exited', 0, 50)
const [result] = reconcileShellList([cached], [], Date.now() + 1000, '/repo')
expect(result?.status).toBe('exited')
const [afterPrune] = upsertShell([], shell('a', 'running'), '/repo')
expect(afterPrune?.status).toBe('running')
})
it('prunes a shell exit record once a later fetch omits the shell it marked', () => {
recordShellExit('/repo', { id: 'a', status: 'exited', exit: 0 })
const [result] = reconcileShellList([shell('a', 'running', undefined, 50)], [], Date.now() + 1000, '/repo')
expect(result?.status).toBe('exited')
expect(result?.exit).toBe(0)
const [afterPrune] = upsertShell([], shell('a', 'running'), '/repo')
expect(afterPrune?.status).toBe('running')
})
})
describe('upsertShell', () => {
@@ -188,6 +314,12 @@ describe('upsertShell', () => {
expect(upsertShell([cached], shell('a', 'running'), '/repo')).toEqual([cached])
})
it('does not replace a terminal shell status with a different status', () => {
const cached = shell('a', 'killed')
expect(upsertShell([cached], shell('a', 'exited', 0), '/repo')).toEqual([cached])
})
it('does not resurrect a shell deleted before the cache was seeded', () => {
recordShellDeleted('/repo', 'a')
@@ -224,6 +356,12 @@ describe('applyShellExit', () => {
expect(result?.status).toBe('unavailable')
})
it('does not replace a killed shell with a later exit event', () => {
const [result] = applyShellExit([shell('a', 'killed')], { id: 'a', status: 'exited', exit: 0 })
expect(result?.status).toBe('killed')
})
it('leaves unrelated shells untouched', () => {
const other = shell('b', 'running')
const [result] = applyShellExit([other], { id: 'a', status: 'killed' })
+140 -68
View File
@@ -6,10 +6,11 @@ import type { SessionStatusType } from '@/stores/sessionStatusStore'
export const BACKGROUNDABLE_TOOLS = new Set(['shell', 'subagent'])
export type ChildOutcome = 'succeeded' | 'failed' | 'interrupted'
export type ShellLifecycleStatus = ShellInfo['status'] | 'unavailable'
export type ShellNoticeOutcome = 'completed' | 'failed'
type ShellLifecycleStatus = ShellInfo['status'] | 'unavailable'
export type ShellRecord = Omit<ShellInfo, 'status'> & { status: ShellLifecycleStatus }
export type BackgroundTaskKind = 'shell' | 'subagent'
export type BackgroundTaskStatus =
type BackgroundTaskKind = 'shell' | 'subagent'
type BackgroundTaskStatus =
| 'running'
| 'completed'
| 'failed'
@@ -74,6 +75,10 @@ function metadataString(part: SessionMessageAssistantTool, key: string): string
return typeof value === 'string' ? value : undefined
}
export function subagentSessionID(part: SessionMessageAssistantTool): string | undefined {
return metadataString(part, 'sessionID')
}
function isBackgroundPart(part: SessionMessageAssistantTool): boolean {
if (part.state.status !== 'completed') return false
const metadata = toolMetadata(part)
@@ -87,10 +92,10 @@ export function backgroundShellID(part: SessionMessageAssistantTool): string | u
export function backgroundChildSessionID(part: SessionMessageAssistantTool): string | undefined {
if (part.name !== 'subagent' || !isBackgroundPart(part)) return undefined
return metadataString(part, 'sessionID')
return subagentSessionID(part)
}
export function isTerminalShell(shell: { status: ShellLifecycleStatus }): boolean {
function isTerminalShell(shell: { status: ShellLifecycleStatus }): boolean {
return shell.status !== 'running'
}
@@ -131,9 +136,11 @@ export function shellToolLifecycle(
shellID: string | undefined,
shell: ShellRecord | undefined,
listLoaded: boolean,
notice?: ShellNoticeOutcome,
): BackgroundTaskLifecycle {
if (!shellID) return 'completed'
if (shell) return shellLifecycle(shell)
if (notice) return notice
return listLoaded ? 'unavailable' : 'unknown'
}
@@ -141,6 +148,13 @@ export function isRunningLifecycle(status: BackgroundTaskLifecycle): boolean {
return status === 'running' || status === 'unknown'
}
export function backgroundTaskStatusColor(status: BackgroundTaskLifecycle): string {
if (status === 'completed') return 'text-success'
if (status === 'failed') return 'text-destructive'
if (status === 'unavailable') return 'text-muted-foreground'
return 'text-warning'
}
export function lifecycleLabel(status: BackgroundTaskLifecycle): string {
return status === 'unknown' ? 'running' : status
}
@@ -162,6 +176,16 @@ function markShellUnavailable(shell: ShellRecord): ShellRecord {
}
}
function clearConfirmedShellExitRecord(
directory: string,
id: string,
record: ShellExitRecord | undefined,
fetchStartedAt: number,
): void {
if (!record || record.completedAt > fetchStartedAt) return
clearShellExitRecord(directory, id)
}
export function reconcileShellList(
existing: ShellRecord[],
fetched: ShellInfo[],
@@ -174,6 +198,10 @@ export function reconcileShellList(
const cached = existingByID.get(shell.id)
if (cached && isTerminalShell(cached) && !isTerminalShell(shell)) return cached
const record = shellExitRecord(directory, shell.id)
if (isTerminalShell(shell)) {
clearConfirmedShellExitRecord(directory, shell.id, record, fetchStartedAt)
return shell
}
return record ? applyShellExitRecord(shell, record) : shell
})
@@ -183,12 +211,18 @@ export function reconcileShellList(
merged.push(shell)
continue
}
const record = shellExitRecord(directory, shell.id)
if (isTerminalShell(shell)) {
clearConfirmedShellExitRecord(directory, shell.id, record, fetchStartedAt)
merged.push(shell)
continue
}
const record = shellExitRecord(directory, shell.id)
merged.push(record ? applyShellExitRecord(shell, record) : markShellUnavailable(shell))
if (record) {
merged.push(applyShellExitRecord(shell, record))
clearConfirmedShellExitRecord(directory, shell.id, record, fetchStartedAt)
continue
}
merged.push(markShellUnavailable(shell))
}
return merged.sort((left, right) => left.time.started - right.time.started)
@@ -196,7 +230,7 @@ export function reconcileShellList(
export function upsertShell(current: ShellRecord[], info: ShellInfo, directory: string): ShellRecord[] {
const cached = current.find((shell) => shell.id === info.id)
if (cached && isTerminalShell(cached) && !isTerminalShell(info)) return current
if (cached && isTerminalShell(cached) && cached.status !== info.status) return current
const record = shellExitRecord(directory, info.id)
const next = record && !isTerminalShell(info) ? applyShellExitRecord(info, record) : info
return [...current.filter((shell) => shell.id !== info.id), next]
@@ -207,7 +241,8 @@ export function applyShellExit(
exit: { id: string; status: ShellInfo['status']; exit?: number },
): ShellRecord[] {
return current.map((shell) => {
if (shell.id !== exit.id || shell.status === 'unavailable') return shell
if (shell.id !== exit.id) return shell
if (isTerminalShell(shell) && shell.status !== exit.status) return shell
const terminal = exit.status !== 'running'
return {
...shell,
@@ -225,6 +260,34 @@ export function markShellDeleted(current: ShellRecord[], id: string): ShellRecor
})
}
interface BackgroundShellPart {
id: string
label: string
}
interface BackgroundSubagentPart {
childSessionID: string
label: string
toolStatus: SessionMessageAssistantTool['state']['status']
}
interface CollectedBackgroundParts {
shells: BackgroundShellPart[]
subagents: BackgroundSubagentPart[]
shellNotices: Map<string, ShellNoticeOutcome>
}
function shellNoticeFromMessage(message: SessionMessageInfo): { shellID: string; outcome: ShellNoticeOutcome } | undefined {
if (message.type !== 'synthetic' && message.type !== 'system') return undefined
const metadata = message.metadata
if (!metadata || metadata.source !== 'shell') return undefined
const shellID = metadata.shellID
if (typeof shellID !== 'string' || !shellID) return undefined
const exit = metadata.exit
const completed = metadata.state === 'completed' && (exit === undefined || exit === 0)
return { shellID, outcome: completed ? 'completed' : 'failed' }
}
function shellLabel(part: SessionMessageAssistantTool): string {
if (part.state.status === 'streaming') return 'Shell command'
const command = part.state.input.command
@@ -232,40 +295,6 @@ function shellLabel(part: SessionMessageAssistantTool): string {
return unwrapSandboxExecCommand(command)
}
export function shellBackgroundTasks(
shells: ShellRecord[],
messages: SessionMessageInfo[],
listLoaded: boolean,
): BackgroundTask[] {
const tasks = new Map<string, BackgroundTask>()
for (const shell of shells) {
tasks.set(shell.id, {
id: shell.id,
kind: 'shell',
label: shell.command,
status: shellLifecycle(shell),
shell,
})
}
for (const message of messages) {
if (message.type !== 'assistant') continue
for (const part of message.content) {
if (part.type !== 'tool' || part.name !== 'shell') continue
const shellID = backgroundShellID(part)
if (!shellID || tasks.has(shellID)) continue
tasks.set(shellID, {
id: shellID,
kind: 'shell',
label: shellLabel(part),
status: listLoaded ? 'unavailable' : 'unknown',
})
}
}
return [...tasks.values()]
}
function subagentLabel(part: SessionMessageAssistantTool): string {
if (part.state.status !== 'streaming') {
const description = part.state.input.description
@@ -274,35 +303,78 @@ function subagentLabel(part: SessionMessageAssistantTool): string {
return 'Sub-agent task'
}
export function subagentBackgroundTasks(
messages: SessionMessageInfo[],
statuses: Map<string, SessionStatusType>,
knownSessions: Set<string>,
outcomes: Map<string, ChildOutcome>,
): BackgroundTask[] {
const tasks = new Map<string, BackgroundTask>()
export function collectBackgroundParts(messages: SessionMessageInfo[]): CollectedBackgroundParts {
const shells = new Map<string, BackgroundShellPart>()
const subagents = new Map<string, BackgroundSubagentPart>()
const shellNotices = new Map<string, ShellNoticeOutcome>()
for (const message of messages) {
const notice = shellNoticeFromMessage(message)
if (notice) {
if (!shellNotices.has(notice.shellID)) shellNotices.set(notice.shellID, notice.outcome)
continue
}
if (message.type !== 'assistant') continue
for (const part of message.content) {
if (part.type !== 'tool' || part.name !== 'subagent') continue
const childSessionID = backgroundChildSessionID(part)
if (!childSessionID) continue
tasks.set(childSessionID, {
id: childSessionID,
kind: 'subagent',
label: subagentLabel(part),
status: subagentLifecycle(
part.state.status,
true,
childLifecycle(
statuses.get(childSessionID) ?? { type: 'idle' },
knownSessions.has(childSessionID),
outcomes.get(childSessionID),
),
),
childSessionID,
})
if (part.type !== 'tool') continue
if (part.name === 'shell') {
const shellID = backgroundShellID(part)
if (!shellID || shells.has(shellID)) continue
shells.set(shellID, { id: shellID, label: shellLabel(part) })
continue
}
if (part.name === 'subagent') {
const childSessionID = backgroundChildSessionID(part)
if (!childSessionID) continue
subagents.set(childSessionID, {
childSessionID,
label: subagentLabel(part),
toolStatus: part.state.status,
})
}
}
}
return { shells: [...shells.values()], subagents: [...subagents.values()], shellNotices }
}
export function shellBackgroundTasks(
shells: ShellRecord[],
shellParts: BackgroundShellPart[],
notices: ReadonlyMap<string, ShellNoticeOutcome>,
listLoaded: boolean,
): BackgroundTask[] {
const tasks = new Map<string, BackgroundTask>()
for (const shell of shells) {
tasks.set(shell.id, {
id: shell.id,
kind: 'shell',
label: shell.command,
status: shellToolLifecycle(shell.id, shell, listLoaded, notices.get(shell.id)),
shell,
})
}
for (const part of shellParts) {
if (tasks.has(part.id)) continue
tasks.set(part.id, {
id: part.id,
kind: 'shell',
label: part.label,
status: shellToolLifecycle(part.id, undefined, listLoaded, notices.get(part.id)),
})
}
return [...tasks.values()]
}
export function subagentBackgroundTasks(
parts: BackgroundSubagentPart[],
lifecycles: Record<string, BackgroundTaskLifecycle>,
): BackgroundTask[] {
return parts.map((part) => ({
id: part.childSessionID,
kind: 'subagent',
label: part.label,
status: subagentLifecycle(part.toolStatus, true, lifecycles[part.childSessionID] ?? 'unknown'),
childSessionID: part.childSessionID,
}))
}
+11 -1
View File
@@ -9,11 +9,21 @@ export function shellsQueryKey(directory: string | null | undefined) {
return ['opencode', 'shells', directory]
}
export function invalidateShellCaches(queryClient: QueryClient) {
queryClient.invalidateQueries({ queryKey: ['opencode', 'shells'] })
}
export function childSessionReconciliationQueryKey(sessionID: string | null | undefined) {
return ['opencode', 'session-reconcile', sessionID]
}
export function invalidateChildSessionCaches(queryClient: QueryClient) {
export function invalidateChildSessionCaches(queryClient: QueryClient, sessionIDs?: string[]) {
if (sessionIDs) {
for (const sessionID of sessionIDs) {
queryClient.invalidateQueries({ queryKey: childSessionReconciliationQueryKey(sessionID) })
}
return
}
queryClient.invalidateQueries({ queryKey: ['opencode', 'session-reconcile'] })
}
+52 -16
View File
@@ -70,17 +70,17 @@ describe('sessionStatusStore', () => {
const after = useSessionStatus.getState()
expect(after.statuses).toBe(before.statuses)
expect(after.getStatus('untracked')).toEqual({ type: 'idle' })
expect(after.isSessionKnown('untracked')).toBe(true)
expect(after.knownSessions.has('untracked')).toBe(true)
})
it('keeps knowledge of a session after it goes idle', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
expect(store.isSessionKnown('session-a')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('session-a')).toBe(true)
store.setStatus('session-a', { type: 'idle' })
expect(useSessionStatus.getState().isSessionKnown('session-a')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('session-a')).toBe(true)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
@@ -90,8 +90,8 @@ describe('sessionStatusStore', () => {
useSessionStatus.getState().replaceStatuses({ 'session-a': { type: 'busy' } }, token)
expect(useSessionStatus.getState().isSessionKnown('session-a')).toBe(true)
expect(useSessionStatus.getState().isSessionKnown('session-unknown')).toBe(false)
expect(useSessionStatus.getState().knownSessions.has('session-a')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('session-unknown')).toBe(false)
})
it('does not treat a session omitted from a later snapshot as finished', () => {
@@ -101,7 +101,7 @@ describe('sessionStatusStore', () => {
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('session-a')).toBe(false)
expect(useSessionStatus.getState().knownSessions.has('session-a')).toBe(false)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
@@ -112,8 +112,8 @@ describe('sessionStatusStore', () => {
store.setStatus('child-a', { type: 'idle' })
expect(useSessionStatus.getState().getOutcome('child-a')).toBe('failed')
expect(useSessionStatus.getState().isSessionKnown('child-a')).toBe(true)
expect(useSessionStatus.getState().outcomes.get('child-a')).toBe('failed')
expect(useSessionStatus.getState().knownSessions.has('child-a')).toBe(true)
})
it('clears a child outcome when a new execution starts', () => {
@@ -122,7 +122,7 @@ describe('sessionStatusStore', () => {
store.clearOutcome('child-a')
expect(useSessionStatus.getState().getOutcome('child-a')).toBeUndefined()
expect(useSessionStatus.getState().outcomes.get('child-a')).toBeUndefined()
})
it('applies an authoritative idle session snapshot from the child session query', () => {
@@ -139,9 +139,9 @@ describe('sessionStatusStore', () => {
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().isSessionKnown('child-a')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-a')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'idle' })
expect(useSessionStatus.getState().getOutcome('child-a')).toBe('failed')
expect(useSessionStatus.getState().outcomes.get('child-a')).toBe('failed')
})
it('applies a running child session snapshot as busy', () => {
@@ -157,7 +157,7 @@ describe('sessionStatusStore', () => {
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().isSessionKnown('child-a')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-a')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'busy' })
})
@@ -192,7 +192,7 @@ describe('sessionStatusStore', () => {
location: { directory: '/repo' },
}, token)
expect(useSessionStatus.getState().getOutcome('child-a')).toBeUndefined()
expect(useSessionStatus.getState().outcomes.get('child-a')).toBeUndefined()
expect(useSessionStatus.getState().getStatus('child-a')).toEqual({ type: 'busy' })
})
@@ -203,7 +203,7 @@ describe('sessionStatusStore', () => {
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('child-idle')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-idle')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-idle')).toEqual({ type: 'idle' })
})
@@ -214,7 +214,7 @@ describe('sessionStatusStore', () => {
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('child-active')).toBe(false)
expect(useSessionStatus.getState().knownSessions.has('child-active')).toBe(false)
})
it('does not let a snapshot erase an idle event received in flight', () => {
@@ -226,7 +226,7 @@ describe('sessionStatusStore', () => {
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().isSessionKnown('child-active')).toBe(true)
expect(useSessionStatus.getState().knownSessions.has('child-active')).toBe(true)
expect(useSessionStatus.getState().getStatus('child-active')).toEqual({ type: 'idle' })
})
@@ -410,4 +410,40 @@ describe('sessionStatusStore', () => {
expect(useSessionStatus.getState().getStatus('active')).toEqual({ type: 'busy' })
})
it('forgets a session status, knowledge, and outcome', () => {
const store = useSessionStatus.getState()
store.setStatus('child-a', { type: 'busy' })
store.setOutcome('child-a', 'failed')
store.forgetSession('child-a')
const after = useSessionStatus.getState()
expect(after.statuses.has('child-a')).toBe(false)
expect(after.statusCache.has('child-a')).toBe(false)
expect(after.knownSessions.has('child-a')).toBe(false)
expect(after.outcomes.has('child-a')).toBe(false)
})
it('does not let an in-flight snapshot resurrect a forgotten session', () => {
const store = useSessionStatus.getState()
store.setStatus('child-a', { type: 'busy' })
const token = store.beginStatusSnapshot()
store.forgetSession('child-a')
useSessionStatus.getState().applySessionSnapshot('child-a', {
id: 'child-a',
projectID: 'project-1',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
location: { directory: '/repo' },
}, token)
const after = useSessionStatus.getState()
expect(after.statuses.has('child-a')).toBe(false)
expect(after.knownSessions.has('child-a')).toBe(false)
expect(after.outcomes.has('child-a')).toBe(false)
})
})
+31 -15
View File
@@ -8,7 +8,7 @@ export type SessionStatusType =
| { type: 'compact' }
| { type: 'retry'; attempt: number; message: string; next: number }
export interface StatusSnapshotToken {
interface StatusSnapshotToken {
revision: number
order: number
}
@@ -29,9 +29,8 @@ interface SessionStatusStore {
beginStatusSnapshot: () => StatusSnapshotToken
endStatusSnapshot: (token: StatusSnapshotToken) => void
getStatus: (sessionID: string) => SessionStatusType
getOutcome: (sessionID: string) => ChildOutcome | undefined
isSessionKnown: (sessionID: string) => boolean
clearStatus: (sessionID: string) => void
forgetSession: (sessionID: string) => void
}
const DEFAULT_STATUS: SessionStatusType = { type: 'idle' }
@@ -319,14 +318,6 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
return get().statuses.get(sessionID) || DEFAULT_STATUS
},
getOutcome: (sessionID: string) => {
return get().outcomes.get(sessionID)
},
isSessionKnown: (sessionID: string) => {
return get().knownSessions.has(sessionID)
},
clearStatus: (sessionID: string) => {
clearOptimisticActiveTimer(sessionID)
const knownPatch = markSessionKnown(get().knownSessions, sessionID)
@@ -349,6 +340,35 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
return { statuses, statusCache, ...(revisionPatch ?? {}), ...knownFields }
})
},
forgetSession: (sessionID: string) => {
clearOptimisticActiveTimer(sessionID)
const current = get()
const hasSession =
current.statuses.has(sessionID) ||
current.statusCache.has(sessionID) ||
current.knownSessions.has(sessionID) ||
current.outcomes.has(sessionID)
if (!hasSession && inFlightSnapshots.size === 0) return
set((state) => {
const statuses = new Map(state.statuses)
const statusCache = new Map(state.statusCache)
const knownSessions = new Set(state.knownSessions)
const outcomes = new Map(state.outcomes)
statuses.delete(sessionID)
statusCache.delete(sessionID)
knownSessions.delete(sessionID)
outcomes.delete(sessionID)
return {
statuses,
statusCache,
knownSessions,
outcomes,
...(recordRevisionPatch(state, sessionID) ?? {}),
}
})
},
}
})
@@ -358,10 +378,6 @@ export const useSessionStatusForSession = (sessionID: string | undefined): Sessi
)
}
export const useIsSessionKnown = (sessionID: string | undefined): boolean => {
return useSessionStatus((state) => (sessionID ? state.knownSessions.has(sessionID) : false))
}
export const useChildLifecycleForSession = (sessionID: string | undefined): BackgroundTaskLifecycle => {
return useSessionStatus((state) => {
if (!sessionID) return 'unknown'
+1 -1
View File
@@ -48,7 +48,7 @@ export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSe
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
export { formatOpenCodeModelRef, parseOpenCodeModelRef } from './modelRef'
export { formatOpenCodeModelRef, parseOpenCodeModelRef, selectConfiguredModelRef } from './modelRef'
export {
MCP_OAUTH_CALLBACK_PATH,
+19 -1
View File
@@ -1,4 +1,6 @@
import type { ModelRef } from '@opencode/client'
import type { ConfigEntry, ModelRef } from '@opencode/client'
type ConfigDocumentModel = Extract<ConfigEntry, { type: 'document' }>['info']['model']
export function parseOpenCodeModelRef(model: string): ModelRef | undefined {
const providerEnd = model.indexOf('/')
@@ -19,3 +21,19 @@ export function parseOpenCodeModelRef(model: string): ModelRef | undefined {
export function formatOpenCodeModelRef(ref: ModelRef): string {
return ref.variant ? `${ref.providerID}/${ref.id}#${ref.variant}` : `${ref.providerID}/${ref.id}`
}
export function selectConfiguredModelRef(entries: ConfigEntry[]): ModelRef | undefined {
const model = entries.reduce<ConfigDocumentModel>(
(current, entry) => (entry.type === 'document' && entry.info.model ? entry.info.model : current),
undefined,
)
if (!model) return undefined
if (typeof model === 'string') return parseOpenCodeModelRef(model)
return {
providerID: model.providerID,
id: model.model,
...(model.variant ? { variant: model.variant } : {}),
}
}