From 409f2c49999611fc323c72d98608196413d4d8cc Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:47:13 +0000 Subject: [PATCH] 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. --- backend/src/services/opencode-models.ts | 67 ++---- backend/src/services/schedules.ts | 48 ++-- backend/src/services/sse-aggregator.ts | 44 +++- backend/test/services/opencode-models.test.ts | 18 ++ backend/test/services/schedules.test.ts | 46 ++++ backend/test/services/sse-aggregator.test.ts | 89 ++++++++ docs/features/chat.md | 12 + frontend/src/api/providers.ts | 15 +- .../src/components/message/MessagePart.tsx | 5 +- .../components/message/MessageThread.test.tsx | 37 ++++ .../src/components/message/MessageThread.tsx | 17 ++ .../components/message/ToolCallPart.test.tsx | 34 ++- .../src/components/message/ToolCallPart.tsx | 34 ++- .../session/BackgroundTaskStatusIcon.tsx | 12 + .../session/BackgroundWorkBar.test.tsx | 39 ++++ .../components/session/BackgroundWorkBar.tsx | 40 ++-- frontend/src/contexts/EventContext.test.tsx | 98 ++++++++- frontend/src/contexts/EventContext.tsx | 19 +- frontend/src/hooks/useOpenCode.test.tsx | 28 ++- frontend/src/hooks/useOpenCode.ts | 13 +- frontend/src/hooks/useSSE.test.tsx | 67 +++++- frontend/src/hooks/useSSE.ts | 8 +- frontend/src/hooks/useSessionShells.test.tsx | 161 ++++++++++++++ frontend/src/hooks/useSessionShells.ts | 31 +-- frontend/src/lib/backgroundWork.test.ts | 138 ++++++++++++ frontend/src/lib/backgroundWork.ts | 208 ++++++++++++------ frontend/src/lib/queryInvalidation.ts | 12 +- .../src/stores/sessionStatusStore.test.ts | 68 ++++-- frontend/src/stores/sessionStatusStore.ts | 46 ++-- shared/src/opencode/index.ts | 2 +- shared/src/opencode/modelRef.ts | 20 +- 31 files changed, 1197 insertions(+), 279 deletions(-) create mode 100644 frontend/src/components/session/BackgroundTaskStatusIcon.tsx create mode 100644 frontend/src/hooks/useSessionShells.test.tsx diff --git a/backend/src/services/opencode-models.ts b/backend/src/services/opencode-models.ts index a6fd022d..e9908354 100644 --- a/backend/src/services/opencode-models.ts +++ b/backend/src/services/opencode-models.ts @@ -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['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 { return new Promise((resolve) => { if (signal.aborted) { @@ -154,11 +136,7 @@ async function readConfiguredRef( signal: AbortSignal, ): Promise { const entries = await client.api.config.get(location, { signal }) - const model = entries.reduce( - (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() diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index b0ef82b7..2499fecd 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -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 { + 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 { const key = `${repoId}:${jobId}:${runId}` if (ScheduleService.activeTeardowns.has(key)) return diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index 7bd8539f..2636192c 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -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 = new Map() private directoryClients: Map> = new Map() private activeSessions: Map> = new Map() + private sessionDirectories: Map = new Map() private eventListeners: Set = new Set() private subagentSessions: Map> = 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 { 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, 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() diff --git a/backend/test/services/opencode-models.test.ts b/backend/test/services/opencode-models.test.ts index a0a7313d..0d9514ff 100644 --- a/backend/test/services/opencode-models.test.ts +++ b/backend/test/services/opencode-models.test.ts @@ -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')], diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index 574a4bf4..a5861f9b 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -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', diff --git a/backend/test/services/sse-aggregator.test.ts b/backend/test/services/sse-aggregator.test.ts index edb400d5..b8c621c9 100644 --- a/backend/test/services/sse-aggregator.test.ts +++ b/backend/test/services/sse-aggregator.test.ts @@ -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' } }, + }) + }) +}) diff --git a/docs/features/chat.md b/docs/features/chat.md index a044f1a7..120b6ac4 100644 --- a/docs/features/chat.md +++ b/docs/features/chat.md @@ -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. diff --git a/frontend/src/api/providers.ts b/frontend/src/api/providers.ts index 584e5d73..6c7a87d2 100644 --- a/frontend/src/api/providers.ts +++ b/frontend/src/api/providers.ts @@ -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 } } -type ConfigDocumentModel = Extract["info"]["model"]; - -function formatConfigModel(model: NonNullable): string { - return typeof model === "string" ? model : `${model.providerID}/${model.model}`; -} - export async function getOpenCodeConfigModel(directory?: string): Promise { try { const entries = await callOpenCode((api) => api.config.get(openCodeLocation(directory))); - const model = entries.reduce( - (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; } diff --git a/frontend/src/components/message/MessagePart.tsx b/frontend/src/components/message/MessagePart.tsx index 9b6975f2..8f8ac455 100644 --- a/frontend/src/components/message/MessagePart.tsx +++ b/frontend/src/components/message/MessagePart.tsx @@ -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} /> diff --git a/frontend/src/components/message/MessageThread.test.tsx b/frontend/src/components/message/MessageThread.test.tsx index 10c149e0..d0865b26 100644 --- a/frontend/src/components/message/MessageThread.test.tsx +++ b/frontend/src/components/message/MessageThread.test.tsx @@ -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( + , + ) + + 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 }) diff --git a/frontend/src/components/message/MessageThread.tsx b/frontend/src/components/message/MessageThread.tsx index 7a37cf39..f5332115 100644 --- a/frontend/src/components/message/MessageThread.tsx +++ b/frontend/src/components/message/MessageThread.tsx @@ -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 } 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() 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) => ( diff --git a/frontend/src/components/message/ToolCallPart.test.tsx b/frontend/src/components/message/ToolCallPart.test.tsx index 8ce719f5..b98a330f 100644 --- a/frontend/src/components/message/ToolCallPart.test.tsx +++ b/frontend/src/components/message/ToolCallPart.test.tsx @@ -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( { 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( + , + ) + + 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( + , + ) + + await waitFor(() => expect(screen.getByText('failed')).toBeInTheDocument()) + expect(screen.queryByText('background')).not.toBeInTheDocument() }) it('treats an unknown child session as running, not finished', () => { diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index c20b753e..f4a8cd3c 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -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
{parts}
} -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 ✓ - if (status === 'failed') return ✗ - if (status === 'killed') return - return - } + const renderShellLifecycleIcon = (status: BackgroundTaskLifecycle) => ( + + ) const getStatusIcon = () => { if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus) diff --git a/frontend/src/components/session/BackgroundTaskStatusIcon.tsx b/frontend/src/components/session/BackgroundTaskStatusIcon.tsx new file mode 100644 index 00000000..31e1ca44 --- /dev/null +++ b/frontend/src/components/session/BackgroundTaskStatusIcon.tsx @@ -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 + if (status === 'failed') return + if (status === 'interrupted') return + if (status === 'killed') return + if (status === 'unavailable') return + return +} diff --git a/frontend/src/components/session/BackgroundWorkBar.test.tsx b/frontend/src/components/session/BackgroundWorkBar.test.tsx index 88e2b626..2de3e50b 100644 --- a/frontend/src/components/session/BackgroundWorkBar.test.tsx +++ b/frontend/src/components/session/BackgroundWorkBar.test.tsx @@ -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) diff --git a/frontend/src/components/session/BackgroundWorkBar.tsx b/frontend/src/components/session/BackgroundWorkBar.tsx index 0375e5d8..38e8af7b 100644 --- a/frontend/src/components/session/BackgroundWorkBar.tsx +++ b/frontend/src/components/session/BackgroundWorkBar.tsx @@ -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 - if (status === 'failed') return - if (status === 'interrupted') return - if (status === 'killed') return - if (status === 'unavailable') return - return -} - function BackgroundTaskKindIcon({ task }: { task: BackgroundTask }) { return task.kind === 'shell' ? @@ -155,7 +150,7 @@ function BackgroundTaskRow({ {task.label} - + {lifecycleLabel(task.status)} {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 = {} + 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)) diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index 2a00d705..f98efa96 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -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(, { 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(, { 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 () => { diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index c6f8ce6a..4b71656f 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -393,17 +393,28 @@ export function EventProvider({ children }: { children: React.ReactNode }) { useSessionStatus.getState().endStatusSnapshot(snapshotToken) return } + const busyBeforeSnapshot = new Set() + 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) diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx index 9fb1c95c..e5019ca6 100644 --- a/frontend/src/hooks/useOpenCode.test.tsx +++ b/frontend/src/hooks/useOpenCode.test.tsx @@ -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') }) }) diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 812c8411..a4f189b6 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -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, }); }; diff --git a/frontend/src/hooks/useSSE.test.tsx b/frontend/src/hooks/useSSE.test.tsx index 5d282d7d..d014d512 100644 --- a/frontend/src/hooks/useSSE.test.tsx +++ b/frontend/src/hooks/useSSE.test.tsx @@ -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()), + ...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>(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>(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: { diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index f537155d..5d9f18d8 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -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() } diff --git a/frontend/src/hooks/useSessionShells.test.tsx b/frontend/src/hooks/useSessionShells.test.tsx new file mode 100644 index 00000000..ec384b3d --- /dev/null +++ b/frontend/src/hooks/useSessionShells.test.tsx @@ -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()), + ...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 }) => ( + {children} + ) +} + +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(['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(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(key, (current) => + current ? applyShellExit(current, { id: 'dev', status: 'exited', exit: 0 }) : current, + ) + }) + + const [after] = queryClient.getQueryData(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) + }) +}) diff --git a/frontend/src/hooks/useSessionShells.ts b/frontend/src/hooks/useSessionShells.ts index 6a33d4e0..a5da4979 100644 --- a/frontend/src/hooks/useSessionShells.ts +++ b/frontend/src/hooks/useSessionShells.ts @@ -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( + directory: string | undefined, + enabled: boolean, + select?: (shells: ShellRecord[]) => TData, +) { const queryClient = useQueryClient() - return useQuery({ + return useQuery({ queryKey: shellsQueryKey(directory), - queryFn: async () => { + queryFn: async (): Promise => { const fetchStartedAt = Date.now() const fetched = await listShells(directory ?? '') const existing = queryClient.getQueryData(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( + 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(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) => { diff --git a/frontend/src/lib/backgroundWork.test.ts b/frontend/src/lib/backgroundWork.test.ts index 734227e8..5b7bdf2e 100644 --- a/frontend/src/lib/backgroundWork.test.ts +++ b/frontend/src/lib/backgroundWork.test.ts @@ -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' }) diff --git a/frontend/src/lib/backgroundWork.ts b/frontend/src/lib/backgroundWork.ts index b93436c8..d07aedd8 100644 --- a/frontend/src/lib/backgroundWork.ts +++ b/frontend/src/lib/backgroundWork.ts @@ -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 & { 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 +} + +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() - 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, - knownSessions: Set, - outcomes: Map, -): BackgroundTask[] { - const tasks = new Map() +export function collectBackgroundParts(messages: SessionMessageInfo[]): CollectedBackgroundParts { + const shells = new Map() + const subagents = new Map() + const shellNotices = new Map() 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, + listLoaded: boolean, +): BackgroundTask[] { + const tasks = new Map() + 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, +): 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, + })) +} diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index 4360ea06..8ebb8eef 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -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'] }) } diff --git a/frontend/src/stores/sessionStatusStore.test.ts b/frontend/src/stores/sessionStatusStore.test.ts index 050b546c..36590561 100644 --- a/frontend/src/stores/sessionStatusStore.test.ts +++ b/frontend/src/stores/sessionStatusStore.test.ts @@ -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) + }) }) diff --git a/frontend/src/stores/sessionStatusStore.ts b/frontend/src/stores/sessionStatusStore.ts index 32a5ea04..6cb52022 100644 --- a/frontend/src/stores/sessionStatusStore.ts +++ b/frontend/src/stores/sessionStatusStore.ts @@ -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((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((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' diff --git a/shared/src/opencode/index.ts b/shared/src/opencode/index.ts index 2bdea9c0..2baf7d94 100644 --- a/shared/src/opencode/index.ts +++ b/shared/src/opencode/index.ts @@ -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, diff --git a/shared/src/opencode/modelRef.ts b/shared/src/opencode/modelRef.ts index 397c10c1..2d7f8995 100644 --- a/shared/src/opencode/modelRef.ts +++ b/shared/src/opencode/modelRef.ts @@ -1,4 +1,6 @@ -import type { ModelRef } from '@opencode/client' +import type { ConfigEntry, ModelRef } from '@opencode/client' + +type ConfigDocumentModel = Extract['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( + (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 } : {}), + } +}