diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 68d8cc02b49f1..ecd6ec1ca50a7 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -91,7 +91,9 @@ import * as Stream from "effect/Stream"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; import { + SUBAGENT_RESULT_TURN_ITEM_TYPES, subagentResultForRun, + subagentStopNotice, delegatedTaskProgress, delegatedTaskReportRuns, } from "@t3tools/provider-core/server/subagentProjection"; @@ -732,15 +734,26 @@ function pageIncludesTerminalTaskResult(input: { const result = subagentResultForRun(input.target, run); if (result.messageId === null && result.turnItemId === null) return false; - return input.items.some((item) => { - if (item.sourceThreadId !== input.target.thread.id) return false; - const matchesResult = - (result.turnItemId !== null && item.itemId === result.turnItemId) || - (result.messageId !== null && - item.type === "assistant_message" && - item.messageId === result.messageId); - return matchesResult && item.text !== null && !item.textTruncated; - }); + const onPage = (matches: (item: OrchestratorMcpThreadTimelineItem) => boolean) => + input.items.some( + (item) => + item.sourceThreadId === input.target.thread.id && + matches(item) && + item.text !== null && + !item.textTruncated, + ); + // The result ends with the stop reason, so the page shows it only when it has both. + const notice = subagentStopNotice(input.target, run); + return ( + onPage( + (item) => + (result.turnItemId !== null && item.itemId === result.turnItemId) || + (result.messageId !== null && + item.type === "assistant_message" && + item.messageId === result.messageId), + ) && + (notice === undefined || onPage((item) => item.itemId === notice.id)) + ); } function latestTerminalResultRun( @@ -1874,7 +1887,7 @@ const make = Effect.gen(function* () { messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: ["assistant_message", "error", "system_notice"], + turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, }) .pipe(Effect.mapError(threadManagementFailure)); const childProjection = { @@ -3597,7 +3610,7 @@ const make = Effect.gen(function* () { messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: ["assistant_message", "error"], + turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, }) .pipe(Effect.mapError(threadManagementFailure)); if ( diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 060f23864c0b3..441c9992e73cc 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -1414,7 +1414,7 @@ const seedRestartCancelledChild = (input: { readonly name: string; readonly completionWake: "always" | "settled_only"; readonly continuationPending: boolean; - readonly runStatus?: "cancelled" | "completed"; + readonly runStatus?: "cancelled" | "completed" | "interrupted"; readonly lostWork?: OrchestrationV2Run["restartCancelledBackgroundWork"]; readonly now: DateTime.Utc; }) => @@ -5150,6 +5150,72 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { `Child task completed without an assistant result.\n\n${stopReason}`, ); assert.isUndefined(task?.cancelledRunId); + + // Codex 0.169 reports a hook-stopped turn as interrupted; its reason is the interrupt result. + const interrupted = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name: "cancel-finished-interrupted-child", + completionWake: "always", + continuationPending: false, + runStatus: "interrupted", + now, + }); + yield* eventSink.write({ + commandId: CommandId.make("command:cancel-finished-interrupted-child:result"), + events: [ + { + id: EventId.make("event:cancel-finished-interrupted-child:result"), + type: "turn-item.updated", + threadId: interrupted.childThreadId, + runId: interrupted.childRunId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + id: IdAllocator.derive.runSignalTurnItem({ + runId: interrupted.childRunId, + signal: "interrupt-result", + }), + type: "run_interrupt_result", + threadId: interrupted.childThreadId, + runId: interrupted.childRunId, + nodeId: rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 98, + status: "interrupted", + title: "Interrupted", + startedAt: now, + completedAt: now, + updatedAt: now, + message: stopReason, + }, + }, + ], + }); + yield* orchestrator.cancelDelegatedTask({ + parentThreadId: threadId, + taskId: interrupted.taskId, + command: { + type: "thread.stop", + commandId: CommandId.make("cancel-finished-interrupted-child"), + threadId: interrupted.childThreadId, + stopDelegatedTasks: false, + }, + stopDescendants: () => Effect.void, + }); + const interruptedTask = (yield* orchestrator.getThreadProjection(threadId)).subagents.find( + (row) => row.id === interrupted.taskId, + ); + assert.equal( + interruptedTask?.result, + `Child task ended with status interrupted.\n\n${stopReason}`, + ); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7179e297b1c9c..2d36fac0aec5b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -200,6 +200,7 @@ import { endOrphanedNativeSubagent, endRunlessRootTurns, makeSubagentChildThread, + SUBAGENT_RESULT_TURN_ITEM_TYPES, subagentResultForRun, delegatedTaskProgress, delegatedTaskReportRuns, @@ -14998,7 +14999,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: ["assistant_message", "error", "system_notice"], + turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( (run) => run.activeAttemptId ?? [], ), diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index 99e40acd547f4..0f083c49c5d8a 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -492,7 +492,7 @@ it("exposes the provider failure rather than a progress message from the failed assert.isNull(result.messageId); }); -it("reports a provider's stop reason for a completed run without an assistant result", () => { +it("reports a provider's stop reason with and without assistant progress", () => { const { projection, run } = taskFixture(); const notice = { id: IdAllocator.derive.runSignalTurnItem({ @@ -520,6 +520,48 @@ it("reports a provider's stop reason for a completed run without an assistant re subagentResultForRun({ ...projection, turnItems: [notice] }, run).text, `Child task completed without an assistant result.\n\n${notice.message}`, ); + const progress = makeSubagentConversationArtifacts({ + messageId: MessageId.make("before-hook-stop"), + turnItemId: TurnItemId.make("before-hook-stop"), + threadId: parentThreadId, + rootNodeId: NodeId.make("root"), + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + role: "assistant", + text: "I am checking the remaining files.", + ordinal: 1, + now: childCreatedAt, + }); + assert.equal( + subagentResultForRun( + { + ...projection, + messages: [{ ...progress.message, runId: run.id }], + turnItems: [{ ...progress.turnItem, runId: run.id }, notice], + }, + run, + ).text, + `${progress.message.text}\n\n${notice.message}`, + ); + const interruptResult = { + ...notice, + id: IdAllocator.derive.runSignalTurnItem({ runId: run.id, signal: "interrupt-result" }), + status: "interrupted", + title: "Interrupted", + type: "run_interrupt_result", + } satisfies OrchestrationV2TurnItem; + assert.equal( + subagentResultForRun( + { + ...projection, + messages: [{ ...progress.message, runId: run.id }], + turnItems: [{ ...progress.turnItem, runId: run.id }, interruptResult], + }, + { ...run, status: "interrupted" }, + ).text, + `${progress.message.text}\n\n${notice.message}`, + ); }); it("keeps the final report of a run that failed after its turn ended", () => { diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index e0ac009f5731a..d1638b8022029 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -194,13 +194,43 @@ export function withExecutedModelNote( /** Run signal of the notice that carries a provider's stop reason on a completed run. */ export const PROVIDER_STOP_REASON_SIGNAL = "provider-stop-reason"; -function stopNotice( +/** Turn item types `subagentResultForRun` reads; load at least these for its projection. */ +export const SUBAGENT_RESULT_TURN_ITEM_TYPES = [ + "assistant_message", + "error", + "system_notice", + "run_interrupt_result", +] as const satisfies ReadonlyArray; + +/** The item carrying a provider's stop reason for a run, which its delegated result ends with. */ +export function subagentStopNotice( projection: Pick, run: OrchestrationV2Run, -): string | undefined { - const id = derive.runSignalTurnItem({ runId: run.id, signal: PROVIDER_STOP_REASON_SIGNAL }); - const notice = projection.turnItems.find((item) => item.id === id); - return notice?.type === "system_notice" ? notice.message : undefined; +) { + // Codex ends a hook-stopped turn as completed or interrupted, depending on its version. + const ids = [ + derive.runSignalTurnItem({ runId: run.id, signal: PROVIDER_STOP_REASON_SIGNAL }), + derive.runSignalTurnItem({ runId: run.id, signal: "interrupt-result" }), + ]; + return projection.turnItems.find( + ( + item, + ): item is Extract< + OrchestrationV2TurnItem, + { readonly type: "system_notice" | "run_interrupt_result" } + > => + ids.includes(item.id) && + (item.type === "system_notice" || item.type === "run_interrupt_result"), + ); +} + +function withStopNotice( + projection: Pick, + run: OrchestrationV2Run, + text: string, +): string { + const notice = subagentStopNotice(projection, run); + return notice === undefined ? text : `${text}\n\n${notice.message}`; } type MonitorNotice = Pick; @@ -263,7 +293,7 @@ export function subagentResultForRun( run.status !== "completed" || result.messageId !== null || result.turnItemId !== null || - stopNotice(projection, run) !== undefined + subagentStopNotice(projection, run) !== undefined ) return result; for (const earlier of delegatedTaskReportRuns( @@ -320,19 +350,21 @@ function resultOfRun( failure !== undefined && turnItem !== null && turnItem.ordinal < failure.ordinal ? (message?.text ?? turnItem.text) : undefined; + const report = message?.text ?? turnItem?.text; const text = (failure?.type === "error" ? reportBeforeFailure === undefined ? failure.failure.message : `${failure.failure.message}\n\nLast assistant message before the run failed:\n\n${reportBeforeFailure}` : undefined) ?? - message?.text ?? - turnItem?.text ?? - (run.status === "completed" - ? ["Child task completed without an assistant result.", stopNotice(projection, run)] - .filter((part) => part !== undefined) - .join("\n\n") - : `Child task ended with status ${run.status}.`); + withStopNotice( + projection, + run, + report ?? + (run.status === "completed" + ? "Child task completed without an assistant result." + : `Child task ended with status ${run.status}.`), + ); const executedModel = latestProviderTurnForAttempt( projection.providerTurns, run.activeAttemptId,