diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 88563aeb43492..81cf2af281452 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1777,7 +1777,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { string, Record >(); - const state: { roster: ReadonlyArray | undefined } = { roster: undefined }; + const state: { roster: OrchestrationV2ProviderThread["pendingBackgroundTasks"] } = { + roster: undefined, + }; let wake = yield* Deferred.make(); yield* runtime.events.pipe( Stream.tap((event) => @@ -1826,7 +1828,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* until(check); }); }); - return { calls, callsById, callsAtChildTurnStart, childTurns, state, until }; + // A reported subagent stays listed until the wake that reads its report, which these replays never start. + const rosterSettled = () => + state.roster !== undefined && + state.roster.every((task) => callsById.get(task.taskId)?.status !== "running"); + return { calls, callsById, callsAtChildTurnStart, childTurns, state, until, rosterSettled }; }); const launchedAndRunning = [ ...backgroundLaunch(CHILD), @@ -2006,7 +2012,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { () => watch.calls.get("Again")?.status === "completed" && watch.calls.get("Sleep")?.status === "completed" && - watch.state.roster?.length === 0, + watch.rosterSettled(), ); assert.deepEqual(Object.fromEntries(watch.calls), { Sleep: { status: "completed", result: "CHILD_OK" }, @@ -2015,6 +2021,105 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect.each(["dispatched", "failed", "cleared", "stopped", "cancelled"] as const)( + "lists a finished background subagent until its wake's continuation is %s", + (outcome) => + Effect.gen(function* () { + const offered = + yield* Deferred.make(); + const gate = makeProviderReplayGate(["cancel"]); + const { runtime, thread } = yield* resumed( + [ + ...launchedAndRunning, + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report", "CHILD_OK"), + ...(outcome === "cancelled" + ? [ + event( + "session.inbox.cancelled", + { sessionID: SESSION, inboxID: "msg_report" }, + "cancel", + ), + ] + : [event("session.execution.started", { sessionID: SESSION })]), + ...(outcome === "stopped" + ? [ + out("session.interrupt", { sessionID: SESSION }), + reply("session.interrupt", { interrupted: true }), + ] + : []), + ], + outcome === "cancelled" ? { replayGate: gate } : undefined, + ).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid), + take: Effect.never, + }), + ); + const rosters: Array> = []; + const watch = yield* watchCalls( + { + ...runtime, + events: runtime.events.pipe( + Stream.tap((event) => + Effect.sync(() => { + if ( + event.type === "provider_thread.updated" && + event.providerThread.id === thread.id + ) + rosters.push( + (event.providerThread.pendingBackgroundTasks ?? []).map( + (task) => task.taskId, + ), + ); + }), + ), + ), + }, + thread, + ); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => watch.calls.get("Sleep")?.status === "completed"); + assert.deepEqual(watch.callsById.get("call-background"), { + status: "completed", + result: "CHILD_OK", + }); + const listed = rosters.findIndex((roster) => roster.includes("call-background")); + // The held task matches the running call, so the roster published at launch stays current. + const held = () => { + assert.deepEqual(rosters.at(-1), ["call-background"]); + assert.isFalse(rosters.slice(listed).some((roster) => roster.length === 0)); + }; + held(); + if (outcome === "cancelled") { + gate.release("cancel"); + } else { + const offer = yield* Deferred.await(offered); + held(); + if (outcome === "dispatched" || outcome === "failed") { + const dispatched = yield* Effect.exit( + offer.dispatchIfCurrent!( + outcome === "dispatched" ? Effect.void : Effect.fail("dispatch failed"), + ), + ); + assert.strictEqual(Exit.isSuccess(dispatched), outcome === "dispatched"); + } else if (outcome === "cleared") { + yield* offer.clearIfCurrent!(); + } else { + yield* runtime.interruptTurn({ + providerThread: thread, + providerTurnId: yield* providerTurnId, + requestRuntimeRestart: true, + }); + yield* watch.until(() => rosters.at(-1)?.length === 0); + assert.isTrue(Option.isNone(yield* offer.dispatchIfCurrent!(Effect.void))); + } + } + yield* watch.until(() => watch.state.roster?.length === 0); + }), + ); + it.effect("keeps a call to a finished subagent for its own run's report", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ @@ -2145,7 +2250,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(withLineage(thread)); yield* watch.until( () => - watch.state.roster?.length === 0 && + watch.rosterSettled() && Object.keys(expected).every((id) => watch.callsById.get(id)?.status === "completed"), ); assert.deepEqual(Object.fromEntries(watch.callsById), expected); diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index 94788c7fbfc43..c066399f2cd45 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -1357,6 +1357,125 @@ it.effect.each([ }).pipe(Effect.provide(layerRecoveryTest)), ); +it.effect.each(["completed", "running"] as const)( + "cuts off and wakes for a listed native subagent only while its item is open (%s)", + (status) => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const threadId = yield* createThread(`listed-subagent-${status}`); + const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`); + const providerSessionId = ProviderSessionId.make(`session:${threadId}`); + const subagentId = NodeId.make(`node:${threadId}:subagent`); + yield* projections.apply({ + id: EventId.make(`event:${threadId}:session`), + type: "provider-session.attached", + threadId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: providerSessionId, + driver, + providerInstanceId, + status: "ready", + cwd: "/workspace", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + }); + const settledRun = yield* createRun(threadId, "completed", { providerThreadId }); + yield* projections.apply({ + id: EventId.make(`event:${threadId}:roster`), + type: "provider-thread.updated", + threadId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: providerThreadId, + appThreadId: threadId, + ownerNodeId: null, + driver, + providerInstanceId, + providerSessionId, + nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + pendingBackgroundTasks: [ + { taskId: "call-review", description: "Review", kind: "subagent" }, + ], + }, + }); + yield* projections.apply({ + id: EventId.make(`event:${threadId}:subagent-item`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`item:${threadId}:subagent`), + threadId, + runId: settledRun, + nodeId: subagentId, + providerThreadId, + providerTurnId: null, + nativeItemRef: { driver, nativeId: "call-review", strength: "strong" }, + parentItemId: null, + ordinal: 1, + type: "subagent", + title: "Review", + subagentId, + origin: "provider_native", + driver, + providerInstanceId, + childThreadId: null, + prompt: "review src", + status, + result: status === "completed" ? "LGTM" : null, + startedAt: now, + completedAt: status === "completed" ? now : null, + updatedAt: now, + }, + }); + + const recoveryState = yield* projections.getRuntimeRecoveryProjection(threadId); + assert.deepEqual( + (recoveryState.settledRosterSubagents ?? []).map((item) => item.nativeItemRef?.nativeId), + status === "completed" ? ["call-review"] : [], + ); + + yield* recovery.reconcile("startup"); + + const effects = yield* sql<{ readonly effect_id: string }>` + SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId} + `; + const projection = yield* projections.getThreadProjection(threadId); + if (status === "completed") { + assert.deepEqual(effects, []); + assert.equal(projection.runs[0]?.status, "completed"); + assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork ?? [], []); + } else { + assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]); + assert.deepEqual( + (projection.runs[0]?.restartCancelledBackgroundWork ?? []).map((work) => work.kind), + ["subagent"], + ); + } + assert.deepEqual(projection.providerThreads[0]?.pendingBackgroundTasks ?? [], []); + }).pipe(Effect.provide(layerRecoveryTest)), +); + it.effect("wakes a settled run whose native subagent ran on its own provider thread", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6c8308706b651..74c69d496e6f0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -350,7 +350,10 @@ export type ProjectionRuntimeRecoveryState = Pick< | "runtimeRequests" | "messages" | "turnItems" ->; +> & { + /** Ended subagent items whose task the provider thread still lists; `turnItems` holds only open ones. */ + readonly settledRosterSubagents?: OrchestrationV2ThreadProjection["turnItems"]; +}; export type ProjectionPendingUserInputs = Pick< OrchestrationV2ThreadProjection, @@ -5911,6 +5914,27 @@ export const layer: Layer.Layer = ) ORDER BY item.ordinal ASC, item.turn_item_id ASC `, + // Ended subagents still listed while their report waits for its wake. CROSS JOIN keeps + // the roster outermost, so items are read only when a subagent is listed. + settledRosterSubagents: sql` + SELECT item.payload_json + FROM orchestration_v2_projection_provider_threads AS roster + CROSS JOIN json_each( + CASE WHEN json_valid(roster.payload_json) THEN roster.payload_json ELSE '{}' END, + '$.pendingBackgroundTasks' + ) AS task + CROSS JOIN orchestration_v2_projection_turn_items AS item + WHERE roster.thread_id = ${threadId} + AND json_extract(task.value, '$.kind') = 'subagent' + AND item.thread_id = ${threadId} + AND item.type = 'subagent' + AND item.status IN ('completed', 'failed', 'cancelled', 'interrupted') + AND json_extract( + CASE WHEN json_valid(item.payload_json) THEN item.payload_json ELSE '{}' END, + '$.nativeItemRef.nativeId' + ) = json_extract(task.value, '$.taskId') + ORDER BY item.ordinal ASC, item.turn_item_id ASC + `, }; const sections = Object.entries(queries).map( ([section, query]) => sql` @@ -5935,6 +5959,7 @@ export const layer: Layer.Layer = runtimeRequests, messages, turnItems, + settledRosterSubagents, ] = yield* Effect.all([ decodeRows(decodeRunPayload, threadId)(readRows("runs")), decodeRows(decodeRunAttemptPayload, threadId)(readRows("attempts")), @@ -5946,6 +5971,7 @@ export const layer: Layer.Layer = decodeRows(decodeRuntimeRequestPayload, threadId)(readRows("runtimeRequests")), decodeRows(decodeMessagePayload, threadId)(readRows("messages")), decodeRows(decodeTurnItemPayload, threadId)(readRows("turnItems")), + decodeRows(decodeTurnItemPayload, threadId)(readRows("settledRosterSubagents")), ]); return { thread, @@ -5959,6 +5985,7 @@ export const layer: Layer.Layer = runtimeRequests, messages, turnItems, + settledRosterSubagents, } satisfies ProjectionRuntimeRecoveryState; }, (effect, threadId) => diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 7a7a1d8123918..83feaabe91b57 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -42,6 +42,7 @@ import { mergeRestartCancelledBackgroundWork, latestStartedRun, neverStarted, + rosterTaskEnded, } from "./RestartBackgroundNote.ts"; export class ProviderRuntimeRecoveryError extends Schema.TaggedError()( @@ -922,7 +923,8 @@ export const make = Effect.gen(function* () { if ( cancelledBackgroundNativeIds.has(task.taskId) || (task.parentTaskId !== undefined && - cancelledBackgroundNativeIds.has(task.parentTaskId)) + cancelledBackgroundNativeIds.has(task.parentTaskId)) || + rosterTaskEnded(task, providerThread.id, projection) ) continue; cancelledBackgroundNativeIds.add(task.taskId); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 58918bdef612d..8bc0712c8671c 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,5 +1,6 @@ import { isDeliveredProviderTurn, + isOrchestrationV2WorkActive, type NodeId, type OrchestrationV2ConversationMessage, type OrchestrationV2PendingBackgroundTask, @@ -132,6 +133,33 @@ export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTa }; } +type RosterItem = Pick< + OrchestrationV2TurnItem, + "type" | "providerThreadId" | "nativeItemRef" | "status" +>; + +/** A listed subagent whose own item already ended was waiting only for its report's wake, not cut off. */ +export function rosterTaskEnded( + task: OrchestrationV2PendingBackgroundTask, + providerThreadId: OrchestrationV2ProviderThread["id"], + projection: { + readonly turnItems: ReadonlyArray; + readonly settledRosterSubagents?: ReadonlyArray | undefined; + }, +): boolean { + if (task.kind !== "subagent" || task.parentTaskId !== undefined) return false; + const ownItem = (item: RosterItem) => + item.type === "subagent" && + item.providerThreadId === providerThreadId && + item.nativeItemRef?.nativeId === task.taskId; + return ( + (projection.settledRosterSubagents ?? []).some( + (item) => ownItem(item) && !isOrchestrationV2WorkActive(item.status), + ) && + !projection.turnItems.some((item) => ownItem(item) && isOrchestrationV2WorkActive(item.status)) + ); +} + const MAX_NOTE_ENTRIES = 10; /** Why background work stopped: a T3 server restart, or the provider process exiting under a live server. */ diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 77af7d2680e05..11a80fa8511fe 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -238,6 +238,45 @@ it("does not continue settled root runs with restart-cancelled background work", ); }); +it("does not wake a settled run for a listed subagent that had already finished", () => { + const projection = makeProjection(); + const item = (status: "completed" | "running") => ({ + id: `turn-item:review:${status}`, + runId, + providerThreadId, + nativeItemRef: { driver, nativeId: "call-review", strength: "strong" }, + type: "subagent", + origin: "provider_native", + title: "Review", + status, + }); + const listed = (open: ReadonlyArray, settled?: ReadonlyArray) => + ({ + ...projection, + runs: [{ ...projection.runs[0]!, status: "completed" as const }], + providerThreads: [ + { + ...projection.providerThreads[0]!, + status: "idle" as const, + pendingBackgroundTasks: [ + { taskId: "call-review", kind: "subagent", description: "Review" }, + ], + }, + ], + providerTurns: [{ ...projection.providerTurns[0]!, status: "completed" }], + turnItems: open, + ...(settled === undefined ? {} : { settledRosterSubagents: settled }), + }) as unknown as OrchestrationV2ThreadProjection; + assert.isUndefined(restartContinuationRun(listed([], [item("completed")]), now)); + assert.equal(restartContinuationRun(listed([item("running")]), now)?.id, runId); + assert.equal(restartContinuationRun(listed([]), now)?.id, runId, "no ended item was read"); + assert.equal( + restartContinuationRun(listed([item("running")], [item("completed")]), now)?.id, + runId, + "a later call to the same subagent still runs", + ); +}); + it.effect.each(["completed", "waiting", "cancelled"] as const)( "wakes a %s run whose awaited monitor the restart cancelled, with the note as its prompt", (status) => diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 21d70c62f920e..18c688a5cb046 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -34,6 +34,7 @@ import { neverStarted, restartCancelledBackgroundWorkNote, restartContinuationNote, + rosterTaskEnded, } from "./RestartBackgroundNote.ts"; const CONTINUE_PROMPT = @@ -138,7 +139,7 @@ export const restartStopRequested = Effect.fn("RestartContinuation.restartStopRe /** App-owned delegations continue in their own threads and report back. */ function hasOpenAwaitedWork( - projection: Pick, + projection: Pick, providerThread: ProjectionRuntimeRecoveryState["providerThreads"][number], ): boolean { const openItem = projection.turnItems.some((item) => { @@ -156,8 +157,10 @@ function hasOpenAwaitedWork( return ( openItem || (providerThread.ownerNodeId === null && - (providerThread.pendingBackgroundTasks ?? []).some((task) => - isAwaitedWork(cancelledRosterTaskWork(task)), + (providerThread.pendingBackgroundTasks ?? []).some( + (task) => + isAwaitedWork(cancelledRosterTaskWork(task)) && + !rosterTaskEnded(task, providerThread.id, projection), )) ); } @@ -173,6 +176,7 @@ export function restartContinuationRun( | "providerTurns" | "runtimeRequests" | "turnItems" + | "settledRosterSubagents" >, now: DateTime.Utc, ): OrchestrationV2Run | undefined { diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9e14f8c4ef36b..f28df312a0108 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -25,6 +25,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ProviderCapabilities, type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderRetry, @@ -309,6 +310,8 @@ interface Wake { readonly events: Array; running: boolean; readonly reports: Array; + /** The finished subagents this wake reports, listed as pending until its continuation is dispatched. */ + readonly tasks: Array; readonly detail: string | null; dropped: boolean; readonly after: string | undefined; @@ -382,6 +385,8 @@ interface ThreadState { readonly childId: string; readonly report: BackgroundWorkReport; readonly text: string; + /** The background calls this report settled, still listed until a wake delivers it. */ + readonly tasks: ReadonlyArray; } >; readonly stoppedChildren: Set; @@ -1775,18 +1780,34 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* syncRosterAncestors(call.state); }); + const subagentTask = (call: SubagentCall): OrchestrationV2PendingBackgroundTask => ({ + taskId: call.nativeId, + kind: "subagent", + ...(call.title?.trim() ? { description: call.title.trim() } : {}), + ...(call.child?.subagent === undefined + ? {} + : { childThreadId: call.child.subagent.appThread.id }), + }); + + // A finished subagent stays listed until the run that reads its report exists, so the + // thread never looks finished in between. + const awaitingWake = (state: ThreadState) => + state.subagent !== undefined + ? [] + : [ + ...[...state.reports.values()].flatMap((entry) => + state.stoppedChildren.has(entry.childId) ? [] : entry.tasks, + ), + ...state.wakes.flatMap((wake) => wake.tasks), + ]; + const syncRoster = Effect.fnUntraced(function* (state: ThreadState) { - const roster: Array = - runningCalls(state) + const roster = [ + ...runningCalls(state) .filter((call) => call.background) - .map((call) => ({ - taskId: call.nativeId, - kind: "subagent" as const, - ...(call.title?.trim() ? { description: call.title.trim() } : {}), - ...(call.child?.subagent === undefined - ? {} - : { childThreadId: call.child.subagent.appThread.id }), - })); + .map(subagentTask), + ...awaitingWake(state), + ]; for (const [taskId, shell] of shells) { if (shell.running && sessionsOf(state).includes(shell.state)) { roster.push({ @@ -2320,6 +2341,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const route = state.providerThread.appThreadId; if (route === null || wake.messageId === undefined) return; const notification = backgroundWorkNotification(wake.reports); + // The dispatched run holds the thread from here; a declined, failed or cleared one must not. + const release = lock.withPermit( + Effect.suspend(() => { + if (wake.tasks.length === 0) return Effect.void; + wake.tasks.length = 0; + return syncRosterAncestors(state); + }), + ); yield* continuationRequests.offer({ threadId: route, providerThreadId: state.providerThread.id, @@ -2328,7 +2357,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr messageId: wake.messageId, ...(notification === null ? {} : { notification }), dispatchIfCurrent: (dispatch) => - wake.dropped ? Effect.succeedNone : Effect.asSome(dispatch), + (wake.dropped ? Effect.succeedNone : Effect.asSome(dispatch)).pipe( + Effect.ensuring(release), + ), + clearIfCurrent: () => release, }); }); @@ -3028,6 +3060,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const takeReports = Effect.fnUntraced(function* (state: ThreadState) { const delivered = [...state.reports.values()]; + const tasks = delivered.flatMap((entry) => + state.stoppedChildren.has(entry.childId) ? [] : entry.tasks, + ); state.reports.clear(); const stopped = delivered.length > 0 && @@ -3039,11 +3074,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr .interrupt({ sessionID: Session.ID.make(state.sessionId) }) .pipe(Effect.timeout(INTERRUPT_TIMEOUT), Effect.ignore({ log: true })); } - return { delivered, stopped }; + return { delivered, stopped, tasks }; }); const onWake = Effect.fnUntraced(function* (state: ThreadState) { - const { delivered, stopped } = yield* takeReports(state); + const { delivered, stopped, tasks } = yield* takeReports(state); if (stopped) return; const route = state.providerThread.appThreadId; // History begins at whichever OpenCode queued first: a report or another client's prompt. @@ -3058,6 +3093,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr events: [], running: true, reports: delivered.map((entry) => entry.report), + tasks: route === null ? [] : [...tasks], detail: delivered.length === 0 ? null : delivered.map((entry) => entry.text).join("\n\n"), dropped: false, after: delivered.at(-1)?.inboxId, @@ -3174,6 +3210,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr label: shell?.command ?? payload.description, outcome: reportOutcome(stringField(payload.metadata, "state")), }, + tasks: [], }); if (id !== undefined && shell === undefined) { const outcome = reportOutcome(stringField(payload.metadata, "state")); @@ -3255,6 +3292,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr childThreadId: call?.child?.subagent?.appThread.id, outcome, }, + tasks: [...lost, ...calls].filter((each) => each.background).map(subagentTask), }); const status = state.stoppedChildren.has(childId) ? "interrupted" @@ -3516,6 +3554,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (event.type === "session.inbox.cancelled" || event.type === "session.inbox.delivered") { const report = state.reports.get(event.data.inboxID); state.reports.delete(event.data.inboxID); + if (report !== undefined && report.tasks.length > 0) yield* syncRosterAncestors(state); const external = state.externalPrompts.get(event.data.inboxID); state.externalPrompts.delete(event.data.inboxID); const turn = state.active;