@devries-cameron20 / t3code Mirror · read-only / commits / 0df1967cfa
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 08:30 UTC

fix(server): a delegated task keeps its report when a later run ends without text (#37942)

Julius Marminge committed Nov 16, 2026 at 22:43 UTC 0df1967cfa6fcdf48dfc1a5c025e206d67aaedb9
6 files changed +343 -19
apps/server/src/mcp/OrchestratorMcpService.test.ts
+106
@@ -503,6 +503,112 @@ describe("OrchestratorMcpService", () => {
503 }),
504 );
505
506 + it.effect("takes a silent run's report only from the same task's earlier runs", () =>
507 + Effect.gen(function* () {
508 + const parentThreadId = ThreadId.make("thread:mcp-report-parent");
509 + const childThreadId = ThreadId.make("thread:mcp-report-child");
510 + const taskA = NodeId.make("node:mcp-report-task-a");
511 + const taskB = NodeId.make("node:mcp-report-task-b");
512 + const silent = "Child task completed without an assistant result.";
513 + const parentProjection = {
514 + thread: { id: parentThreadId },
515 + runs: [],
516 + contextTransfers: [],
517 + subagents: [taskA, taskB].map((id) => ({
518 + id,
519 + threadId: parentThreadId,
520 + origin: "app_owned",
521 + childThreadId,
522 + driver: "codex",
523 + model: "gpt-5.6-terra",
524 + status: "running",
525 + result: null,
526 + completionDelivery: null,
527 + })),
528 + } as unknown as OrchestrationV2ThreadProjection;
529 + const run = (ordinal: number, delegatedTaskId: NodeId) => ({
530 + id: RunId.make(`run:mcp-report-${ordinal}`),
531 + ordinal,
532 + status: "completed",
533 + delegatedTaskId,
534 + startedAt: DateTime.makeUnsafe(`2026-10-24T10:0${ordinal}:00Z`),
535 + completedAt: DateTime.makeUnsafe(`2026-10-24T10:0${ordinal}:30Z`),
536 + });
537 + const runs = [run(1, taskA), run(2, taskA), run(3, taskB)];
538 + let reports: ReadonlyArray<readonly [number, string]> = [];
539 + // The mock ignores run filters, so every report is loaded whichever runs are asked for.
540 + const childProjection = () =>
541 + ({
542 + thread: { id: childThreadId, title: "Child task" },
543 + runs,
544 + contextTransfers: [],
545 + messages: reports.map(([ordinal, text]) => ({
546 + id: MessageId.make(`message:mcp-report-${ordinal}`),
547 + runId: runs[ordinal - 1]!.id,
548 + role: "assistant",
549 + text,
550 + createdAt: runs[ordinal - 1]!.completedAt,
551 + updatedAt: runs[ordinal - 1]!.completedAt,
552 + })),
553 + subagents: [],
554 + providerThreads: [],
555 + providerTurns: [],
556 + runtimeRequests: [],
557 + turnItems: [],
558 + }) as unknown as OrchestrationV2ThreadProjection;
559 + const layerDependencies = Layer.mergeAll(
560 + NodeServices.layer,
561 + NodeCrypto.layer,
562 + Layer.mock(ThreadManagementService.ThreadManagementService)({
563 + getThreadRecords: (threadId) =>
564 + Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection()),
565 + delegatedTaskResultPending: () => Effect.succeed(false),
566 + dispatch: () => Effect.succeed({} as never),
567 + }),
568 + ServerSettings.layerTest(),
569 + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
570 + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
571 + list: () => Effect.succeed([]),
572 + }),
573 + Layer.mock(ProjectService.ProjectService)({}),
574 + Layer.mock(SecretRequests.SecretRequests)({}),
575 + Layer.mock(RemoteDelegation.RemoteDelegation)({}),
576 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
577 + );
578 + const scope: McpInvocationScope = {
579 + environmentId: EnvironmentId.make("environment:mcp-report"),
580 + requestNamespace: "provider-session:mcp-report",
581 + thread: {
582 + threadId: parentThreadId,
583 + providerSessionId: "provider-session:mcp-report",
584 + providerInstanceId: ProviderInstanceId.make("codex"),
585 + },
586 + client: undefined,
587 + capabilities: new Set(["orchestration"]),
588 + issuedAt: 1,
589 + };
590 +
591 + yield* Effect.gen(function* () {
592 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
593 + // Task A reported, then a run queued behind the report ended without text.
594 + reports = [[1, "REPORT-A"]];
595 + const reported = yield* service.taskStatus(scope, taskA);
596 + assert.equal(reported.status, "completed");
597 + assert.equal(reported.summary, "REPORT-A");
598 + assert.equal(reported.latestTerminalRunId, runs[2]!.id);
599 + assert.equal(reported.latestTerminalSummary, silent);
600 + assert.equal((yield* service.taskStatus(scope, taskB)).summary, silent);
601 +
602 + // A later task's report is not the result of a task that said nothing.
603 + reports = [[3, "REPORT-B"]];
604 + const quiet = yield* service.taskStatus(scope, taskA);
605 + assert.equal(quiet.summary, silent);
606 + assert.equal(quiet.latestTerminalSummary, "REPORT-B");
607 + assert.equal((yield* service.taskStatus(scope, taskB)).summary, "REPORT-B");
608 + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
609 + }),
610 + );
611 +
612 it.effect("tells the parent to end its turn only while its task still runs", () =>
613 Effect.gen(function* () {
614 const parentThreadId = ThreadId.make("thread:mcp-next-parent");
apps/server/src/mcp/OrchestratorMcpService.ts
+16 -3
@@ -93,6 +93,7 @@ import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterReg
93 import {
94 subagentResultForRun,
95 delegatedTaskProgress,
96 + delegatedTaskReportRuns,
97 } from "@t3tools/provider-core/server/subagentProjection";
98 import {
99 DispatchModeLimit,
@@ -1756,9 +1757,16 @@ const make = Effect.gen(function* () {
1757 childRun,
1758 heldForRestart ? taskResultRun : undefined,
1759 );
1760 + // Only the task's own result looks back for its report, and only among its own runs.
1761 + const reportRuns =
1762 + task.result === null && taskResultRun !== undefined
1763 + ? delegatedTaskReportRuns(childControls, taskResultRun)
1764 + : [];
1765 const resultRunIds = [
1766 ...new Set(
1761 - [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
1767 + [taskResultRun?.id, terminalRun?.id, ...reportRuns.map((run) => run.id)].filter(
1768 + (id): id is RunId => id !== undefined,
1769 + ),
1770 ),
1771 ];
1772 const resultRecords = yield* threadManagement
@@ -1774,6 +1782,11 @@ const make = Effect.gen(function* () {
1782 messages: [...childControls.messages, ...resultRecords.messages],
1783 turnItems: resultRecords.turnItems,
1784 };
1785 + const resultText = (run: OrchestrationV2Run) =>
1786 + subagentResultForRun(
1787 + { ...childProjection, runs: run.id === taskResultRun?.id ? reportRuns : [] },
1788 + run,
1789 + ).text;
1790 const workState =
1791 task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;
1792 const runStatus = taskStatusForRun(taskResultRun ?? childRun);
@@ -1799,7 +1812,7 @@ const make = Effect.gen(function* () {
1812 task.result !== null
1813 ? task.result
1814 : taskResultRun !== undefined && isTerminalTaskStatus(status)
1802 - ? subagentResultForRun(childProjection, taskResultRun).text
1815 + ? resultText(taskResultRun)
1816 : null;
1817 const resultTransfers = childControls.contextTransfers.filter(
1818 (transfer) =>
@@ -1820,7 +1833,7 @@ const make = Effect.gen(function* () {
1833 const latestTerminalSummary = canExposeTaskRunResult(terminalRun)
1834 ? terminalRun.id === childRun?.id
1835 ? derivedResult
1823 - : subagentResultForRun(childProjection, terminalRun).text
1836 + : resultText(terminalRun)
1837 : null;
1838 const resultContextTransferId = resultTransfer?.id ?? null;
1839 const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+71
@@ -5064,6 +5064,77 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
5064 }),
5065 );
5066
5067 + it.effect("delivers the child's report when a run queued behind it ends without text", () =>
5068 + Effect.gen(function* () {
5069 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5070 + const eventSink = yield* EventSink.EventSinkV2;
5071 + const now = yield* DateTime.now;
5072 + const threadId = ThreadId.make("thread:silent-queued-parent");
5073 + const projectId = ProjectId.make("project:silent-queued-parent");
5074 + const runId = RunId.make("run:silent-queued-parent");
5075 + const rootNodeId = NodeId.make("node:silent-queued-parent-root");
5076 + yield* seedParentWithTerminalTask({
5077 + threadId,
5078 + projectId,
5079 + runId,
5080 + rootNodeId,
5081 + taskId: NodeId.make("node:silent-queued-parent-settled"),
5082 + deliveryState: "delivered",
5083 + now,
5084 + });
5085 + const child = yield* seedRestartCancelledChild({
5086 + parentThreadId: threadId,
5087 + projectId,
5088 + parentRunId: runId,
5089 + rootNodeId,
5090 + name: "silent-queued-child",
5091 + completionWake: "always",
5092 + continuationPending: false,
5093 + runStatus: "completed",
5094 + now,
5095 + });
5096 + yield* eventSink.write({
5097 + commandId: CommandId.make("command:silent-queued-child:queued"),
5098 + events: [
5099 + {
5100 + id: EventId.make("event:silent-queued-child:report"),
5101 + type: "message.updated",
5102 + threadId: child.childThreadId,
5103 + runId: child.childRunId,
5104 + occurredAt: now,
5105 + payload: {
5106 + id: MessageId.make("message:silent-queued-child:report"),
5107 + threadId: child.childThreadId,
5108 + runId: child.childRunId,
5109 + nodeId: null,
5110 + role: "assistant",
5111 + text: "REPORT-OK",
5112 + attachments: [],
5113 + streaming: false,
5114 + createdBy: "agent",
5115 + creationSource: "server",
5116 + createdAt: now,
5117 + updatedAt: now,
5118 + },
5119 + },
5120 + runEvent({
5121 + threadId: child.childThreadId,
5122 + runId: RunId.make("run:silent-queued-child:2"),
5123 + ordinal: 2,
5124 + status: "completed",
5125 + now,
5126 + }),
5127 + ],
5128 + });
5129 + yield* orchestrator.recoverDelegatedTask(child.childThreadId);
5130 + const task = (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
5131 + (row) => row.id === child.taskId,
5132 + );
5133 + assert.equal(task?.status, "completed");
5134 + assert.equal(task?.result, "REPORT-OK");
5135 + }),
5136 + );
5137 +
5138 // Running does not prove prompt consumption in Claude; re-offer cut deliveries even when resuming the turn.
5139 it.effect("re-offers a cut delivery even when a continuation resumes its turn", () =>
5140 Effect.gen(function* () {
apps/server/src/orchestration-v2/Orchestrator.ts
+7 -2
@@ -195,6 +195,7 @@ import {
195 makeSubagentChildThread,
196 subagentResultForRun,
197 delegatedTaskProgress,
198 + delegatedTaskReportRuns,
199 subagentThreadTitle,
200 } from "@t3tools/provider-core/server/subagentProjection";
201 import {
@@ -14411,18 +14412,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14412 return;
14413 }
14414
14415 + // A run queued behind the report can end the task without saying anything.
14416 + const reportRuns = delegatedTaskReportRuns(childControls, { ...childRun, status: outcome });
14417 + const resultRunIds = [childRun.id, ...reportRuns.map((run) => run.id)];
14418 const childResult = yield* projectionStore.getThreadRecords(
14419 childThreadId,
14420 ["messages", "turnItems"],
14421 {
14422 messageRoles: ["assistant"],
14419 - messageRunIds: [childRun.id],
14420 - turnItemRunId: childRun.id,
14423 + messageRunIds: resultRunIds,
14424 + turnItemRunIds: resultRunIds,
14425 turnItemTypes: ["assistant_message", "error", "system_notice"],
14426 },
14427 );
14428 const childProjection = {
14429 ...childControls,
14430 + runs: reportRuns,
14431 messages: childResult.messages,
14432 turnItems: childResult.turnItems,
14433 };
apps/server/src/orchestration-v2/SubagentProjection.test.ts
+63
@@ -393,6 +393,69 @@ it("waits for nested work and retains the report across monitor acknowledgements
393 assert.equal(afterMonitorEnded.resultRun?.id, ended.id);
394 });
395
396 +it("keeps the report when a run queued behind it ends without assistant text", () => {
397 + const { projection, run } = taskFixture();
398 + const report = makeSubagentConversationArtifacts({
399 + messageId: MessageId.make("report"),
400 + turnItemId: TurnItemId.make("report"),
401 + threadId: parentThreadId,
402 + rootNodeId: NodeId.make("root"),
403 + providerThreadId: null,
404 + providerTurnId: null,
405 + nativeItemRef: null,
406 + role: "assistant",
407 + text: "REPORT-OK",
408 + ordinal: 1,
409 + now: childCreatedAt,
410 + });
411 + const queued: OrchestrationV2Run = {
412 + ...run,
413 + id: RunId.make("queued-after-report"),
414 + ordinal: 2,
415 + userMessageId: MessageId.make("queued-message"),
416 + startedAt: DateTime.makeUnsafe("2026-07-24T10:00:00.000Z"),
417 + completedAt: DateTime.makeUnsafe("2026-07-24T10:00:01.000Z"),
418 + };
419 + for (const notification of [
420 + undefined,
421 + {
422 + source: { kind: "command" as const },
423 + outcome: "completed" as const,
424 + summary: "1 command finished",
425 + },
426 + ]) {
427 + const child = {
428 + ...projection,
429 + runs: [run, queued],
430 + messages: [
431 + { ...report.message, runId: run.id },
432 + {
433 + ...report.message,
434 + id: MessageId.make("queued-message"),
435 + runId: queued.id,
436 + role: "user" as const,
437 + text: "ACK-SILENT",
438 + ...(notification ? { notification } : {}),
439 + },
440 + ],
441 + turnItems: [{ ...report.turnItem, runId: run.id }],
442 + };
443 + const progress = delegatedTaskProgress(child);
444 + assert.equal(progress.state, "result_available");
445 + assert.equal(subagentResultForRun(child, progress.resultRun!).text, "REPORT-OK");
446 + // Another task's run, or one that did not complete, keeps its own outcome.
447 + for (const other of [
448 + { ...queued, delegatedTaskId: NodeId.make("follow-up") },
449 + { ...queued, status: "interrupted" as const },
450 + ]) {
451 + assert.notInclude(
452 + subagentResultForRun({ ...child, runs: [run, other] }, other).text,
453 + "REPORT-OK",
454 + );
455 + }
456 + }
457 +});
458 +
459 it("exposes the provider failure rather than a progress message from the failed run", () => {
460 const { projection, run } = taskFixture();
461 const failedRun = { ...run, status: "failed" as const };
packages/provider-core/src/server/subagentProjection.ts
+80 -14
@@ -193,17 +193,89 @@ export function withExecutedModelNote(
193 /** Run signal of the notice that carries a provider's stop reason on a completed run. */
194 export const PROVIDER_STOP_REASON_SIGNAL = "provider-stop-reason";
195
196 -function withStopNotice(
196 +function stopNotice(
197 projection: Pick<OrchestrationV2ThreadProjection, "turnItems">,
198 run: OrchestrationV2Run,
199 - text: string,
200 -): string {
199 +): string | undefined {
200 const id = derive.runSignalTurnItem({ runId: run.id, signal: PROVIDER_STOP_REASON_SIGNAL });
201 const notice = projection.turnItems.find((item) => item.id === id);
203 - return notice?.type === "system_notice" ? `${text}\n\n${notice.message}` : text;
202 + return notice?.type === "system_notice" ? notice.message : undefined;
203 }
204
205 +type MonitorNotice = Pick<OrchestrationV2ConversationMessage, "runId" | "notification">;
206 +
207 +/** Runs that only acknowledge a monitor update are never a task's work. */
208 +function monitorUpdateRunIds(messages: ReadonlyArray<MonitorNotice>) {
209 + return new Set(
210 + messages
211 + .filter(
212 + (message) =>
213 + message.notification?.source.kind === "monitor" &&
214 + message.notification.outcome === "updated",
215 + )
216 + .map((message) => message.runId),
217 + );
218 +}
219 +
220 +/**
221 + * The same task's completed runs before `run`, latest first: where its report is when `run`
222 + * completed without saying anything. Ends at another task's run or at any other outcome.
223 + */
224 +export function delegatedTaskReportRuns(
225 + projection: {
226 + readonly runs: ReadonlyArray<OrchestrationV2Run>;
227 + readonly messages: ReadonlyArray<MonitorNotice>;
228 + },
229 + run: OrchestrationV2Run,
230 +): ReadonlyArray<OrchestrationV2Run> {
231 + if (run.status !== "completed") return [];
232 + const monitorRuns = monitorUpdateRunIds(projection.messages);
233 + const earlier = projection.runs
234 + .filter(
235 + (candidate) =>
236 + candidate.id !== run.id &&
237 + candidate.startedAt !== null &&
238 + candidate.status !== "rolled_back" &&
239 + !monitorRuns.has(candidate.id) &&
240 + runRanAfter(run, candidate),
241 + )
242 + .toSorted((a, b) => (runRanAfter(a, b) ? -1 : 1));
243 + const end = earlier.findIndex(
244 + (candidate) =>
245 + candidate.status !== "completed" || candidate.delegatedTaskId !== run.delegatedTaskId,
246 + );
247 + return end === -1 ? earlier : earlier.slice(0, end);
248 +}
249 +
250 +/**
251 + * `runs` scopes where a run that completed without saying anything finds its report, see
252 + * `delegatedTaskReportRuns`. The projection must hold the assistant records of every run given.
253 + */
254 export function subagentResultForRun(
255 + projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems" | "providerTurns"> & {
256 + readonly runs?: ReadonlyArray<OrchestrationV2Run>;
257 + },
258 + run: OrchestrationV2Run,
259 +) {
260 + const result = resultOfRun(projection, run);
261 + if (
262 + run.status !== "completed" ||
263 + result.messageId !== null ||
264 + result.turnItemId !== null ||
265 + stopNotice(projection, run) !== undefined
266 + )
267 + return result;
268 + for (const earlier of delegatedTaskReportRuns(
269 + { runs: projection.runs ?? [], messages: projection.messages },
270 + run,
271 + )) {
272 + const report = resultOfRun(projection, earlier);
273 + if (report.messageId !== null || report.turnItemId !== null) return report;
274 + }
275 + return result;
276 +}
277 +
278 +function resultOfRun(
279 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems" | "providerTurns">,
280 run: OrchestrationV2Run,
281 ): {
@@ -256,7 +328,9 @@ export function subagentResultForRun(
328 message?.text ??
329 turnItem?.text ??
330 (run.status === "completed"
259 - ? withStopNotice(projection, run, "Child task completed without an assistant result.")
331 + ? ["Child task completed without an assistant result.", stopNotice(projection, run)]
332 + .filter((part) => part !== undefined)
333 + .join("\n\n")
334 : `Child task ended with status ${run.status}.`);
335 const executedModel = latestProviderTurnForAttempt(
336 projection.providerTurns,
@@ -299,15 +373,7 @@ export function delegatedTaskProgress(projection: {
373 }) {
374 const terminal = (status: string) =>
375 ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(status);
302 - const monitorRuns = new Set(
303 - projection.messages
304 - .filter(
305 - (message) =>
306 - message.notification?.source.kind === "monitor" &&
307 - message.notification.outcome === "updated",
308 - )
309 - .map((message) => message.runId),
310 - );
376 + const monitorRuns = monitorUpdateRunIds(projection.messages);
377 const workRuns = projection.runs.filter(
378 (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back",
379 );