@devries-cameron20 / t3code Mirror · read-only / commits / 4f5ff17172
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 22, 22:00 UTC

fix(server): deliver subagent results without history handoffs (#22117)

Julius Marminge committed Oct 20, 2026 at 00:03 UTC 4f5ff17172c5f2bde61a09aafb23011ae4d38538
5 files changed +228 -72
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+179
@@ -671,6 +671,93 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => {
671 assert.include(message?.text ?? "", String(firstTaskId));
672 assert.include(message?.text ?? "", String(secondTaskId));
673 assert.include(message?.text ?? "", "task_status");
674 + assert.include(message?.text ?? "", "child finished");
675 + }),
676 + );
677 +
678 + it.effect.each([
679 + {
680 + name: "oversized UTF-8 result",
681 + first: "界".repeat(6_000),
682 + second: "small result",
683 + inlineFirst: false,
684 + inlineSecond: true,
685 + },
686 + {
687 + name: "combined results",
688 + first: "a".repeat(10_000),
689 + second: "b".repeat(10_000),
690 + inlineFirst: true,
691 + inlineSecond: false,
692 + },
693 + ])("uses task_status for $name beyond the inline budget", (testCase) =>
694 + Effect.gen(function* () {
695 + const orchestrator = yield* Orchestrator.OrchestratorV2;
696 + const sink = yield* EventSink.EventSinkV2;
697 + const now = yield* DateTime.now;
698 + const threadId = ThreadId.make(`thread:inline-budget:${testCase.name}`);
699 + const runId = RunId.make(`run:inline-budget:${testCase.name}`);
700 + const firstTaskId = NodeId.make(`node:inline-first:${testCase.name}`);
701 + const secondTaskId = NodeId.make(`node:inline-second:${testCase.name}`);
702 + const messageId = MessageId.make(`message:delegated-delivery:${threadId}`);
703 + yield* seedParentWithTerminalTask({
704 + threadId,
705 + projectId: ProjectId.make(`project:inline-budget:${testCase.name}`),
706 + runId,
707 + rootNodeId: NodeId.make(`node:inline-budget:${testCase.name}`),
708 + taskId: firstTaskId,
709 + deliveryState: "claimed",
710 + completionWake: "always",
711 + deliveryTaskIds: [firstTaskId, secondTaskId],
712 + now,
713 + });
714 + const parent = yield* orchestrator.getThreadProjection(threadId);
715 + const task = parent.subagents[0]!;
716 + yield* sink.write({
717 + events: [
718 + { id: firstTaskId, result: testCase.first, status: "failed" as const },
719 + { id: secondTaskId, result: testCase.second, status: "cancelled" as const },
720 + ].map(({ id, result, status }) => ({
721 + id: EventId.make(`event:inline-budget:${id}`),
722 + type: "subagent.updated" as const,
723 + threadId,
724 + runId,
725 + nodeId: id,
726 + occurredAt: now,
727 + payload: { ...task, id, result, status, title: "Inspect regression" },
728 + })),
729 + });
730 + yield* orchestrator.dispatch({
731 + type: "message.dispatch",
732 + commandId: CommandId.make(`command:inline-budget:${testCase.name}`),
733 + threadId,
734 + messageId,
735 + text: "Delegated tasks completed.",
736 + attachments: [],
737 + dispatchMode: { type: "queue_after_active" },
738 + createdBy: "agent",
739 + creationSource: "server",
740 + delegatedCompletion: {
741 + parentRunId: runId,
742 + generation: 1,
743 + taskIds: [firstTaskId, secondTaskId],
744 + },
745 + });
746 + const projection = yield* orchestrator.getThreadProjection(threadId);
747 + const message = projection.messages.find((candidate) => candidate.id === messageId)!;
748 + assert.equal(message.text.includes(testCase.first), testCase.inlineFirst);
749 + assert.equal(message.text.includes(testCase.second), testCase.inlineSecond);
750 + const deferredTaskId = testCase.inlineFirst ? secondTaskId : firstTaskId;
751 + assert.include(
752 + message.text,
753 + `Delegated task ${deferredTaskId} (Inspect regression) [${testCase.inlineFirst ? "cancelled" : "failed"}]`,
754 + );
755 + assert.include(message.text, `Use task_status with taskId ${deferredTaskId}`);
756 + assert.deepEqual(message.delegatedCompletion?.taskIds, [firstTaskId, secondTaskId]);
757 + assert.equal(
758 + projection.subagents.find((candidate) => candidate.id === deferredTaskId)?.result,
759 + testCase.inlineFirst ? testCase.second : testCase.first,
760 + );
761 }),
762 );
763
@@ -1644,6 +1731,98 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
1731 );
1732
1733 it.layer(layerTest)("delegated tasks across a server restart", (it) => {
1734 + it.effect("queues a child result without creating a provider history handoff", () =>
1735 + Effect.gen(function* () {
1736 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1737 + const eventSink = yield* EventSink.EventSinkV2;
1738 + const now = yield* DateTime.now;
1739 + const threadId = ThreadId.make("thread:result-message-parent");
1740 + const projectId = ProjectId.make("project:result-message");
1741 + const runId = RunId.make("run:result-message-parent");
1742 + const rootNodeId = NodeId.make("node:result-message-parent");
1743 + yield* seedParentWithTerminalTask({
1744 + threadId,
1745 + projectId,
1746 + runId,
1747 + rootNodeId,
1748 + taskId: NodeId.make("node:result-message-seed"),
1749 + deliveryState: "acknowledged",
1750 + now,
1751 + });
1752 + const child = yield* seedRestartCancelledChild({
1753 + parentThreadId: threadId,
1754 + projectId,
1755 + parentRunId: runId,
1756 + rootNodeId,
1757 + name: "result-message-child",
1758 + completionWake: "always",
1759 + continuationPending: false,
1760 + runStatus: "completed",
1761 + now,
1762 + });
1763 + const parent = yield* orchestrator.getThreadProjection(threadId);
1764 + const childProjection = yield* orchestrator.getThreadProjection(child.childThreadId);
1765 + const providerThreadId = ProviderThreadId.make("provider-thread:result-message-child");
1766 + yield* eventSink.write({
1767 + commandId: CommandId.make("command:result-message-child-provider"),
1768 + events: [
1769 + {
1770 + id: EventId.make("event:result-message-child-provider"),
1771 + type: "provider-thread.updated",
1772 + threadId: child.childThreadId,
1773 + occurredAt: now,
1774 + payload: {
1775 + ...parent.providerThreads[0]!,
1776 + id: providerThreadId,
1777 + appThreadId: child.childThreadId,
1778 + },
1779 + },
1780 + {
1781 + id: EventId.make("event:result-message-child-run"),
1782 + type: "run.updated",
1783 + threadId: child.childThreadId,
1784 + runId: child.childRunId,
1785 + occurredAt: now,
1786 + payload: { ...childProjection.runs[0]!, providerThreadId },
1787 + },
1788 + ],
1789 + });
1790 +
1791 + yield* orchestrator.recoverDelegatedTasks;
1792 + const recovered = yield* orchestrator.getThreadProjection(threadId);
1793 + const task = recovered.subagents.find((candidate) => candidate.id === child.taskId)!;
1794 + assert.equal(task.status, "completed");
1795 + assert.isNotNull(task.result);
1796 + assert.isEmpty(recovered.contextHandoffs);
1797 + assert.equal(recovered.contextTransfers.length, 1);
1798 +
1799 + const delivery = recovered.runs.find((candidate) => candidate.id === runId)!
1800 + .delegatedCompletion!.delivery!;
1801 + const messageId = delivery.messageId;
1802 + yield* orchestrator.dispatch({
1803 + type: "message.dispatch",
1804 + commandId: CommandId.make("command:result-message-delivery"),
1805 + threadId,
1806 + messageId,
1807 + text: "Delegated task finished.",
1808 + attachments: [],
1809 + dispatchMode: { type: "queue_after_active" },
1810 + createdBy: "agent",
1811 + creationSource: "server",
1812 + delegatedCompletion: {
1813 + parentRunId: runId,
1814 + generation: delivery.generation,
1815 + taskIds: [child.taskId],
1816 + },
1817 + });
1818 + const queued = yield* orchestrator.getThreadProjection(threadId);
1819 + assert.include(
1820 + queued.messages.find((message) => message.id === messageId)?.text ?? "",
1821 + task.result!,
1822 + );
1823 + }),
1824 + );
1825 +
1826 it.effect("holds a restart-cancelled child for its continuation's result", () =>
1827 Effect.gen(function* () {
1828 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/orchestration-v2/Orchestrator.ts
+31 -67
@@ -596,11 +596,28 @@ function legacyPullRequestLink(
596 );
597 }
598
599 -function delegatedCompletionWakeDetail(taskIds: ReadonlyArray<string>): string {
600 - const taskList = taskIds.join(", ");
601 - return taskIds.length === 1
602 - ? `Delegated task ${taskList} reached a terminal state. Use task_status with taskId ${taskList} to read the result.`
603 - : `Delegated tasks ${taskList} reached terminal states. Use task_status with each taskId to read the results.`;
599 +const DELEGATED_RESULT_INLINE_BYTES = 16_000;
600 +
601 +function delegatedCompletionWakeDetail(
602 + taskIds: ReadonlyArray<string>,
603 + tasks: ReadonlyArray<OrchestrationV2Subagent>,
604 +): string {
605 + let remainingBytes = DELEGATED_RESULT_INLINE_BYTES;
606 + return taskIds
607 + .map((taskId) => {
608 + const task = tasks.find((candidate) => candidate.id === taskId);
609 + const label = `Delegated task ${taskId}${task?.title == null ? "" : ` (${task.title})`}${task === undefined ? " reached a terminal state" : ` [${task.status}]`}`;
610 + if (task?.result != null) {
611 + const detail = `${label}:\n${task.result}`;
612 + const bytes = Buffer.byteLength(detail);
613 + if (bytes <= remainingBytes) {
614 + remainingBytes -= bytes;
615 + return detail;
616 + }
617 + }
618 + return `${label}. Use task_status with taskId ${taskId} to read the result.`;
619 + })
620 + .join("\n\n");
621 }
622
623 function isTerminalDelegatedTaskStatus(status: OrchestrationV2Subagent["status"]): boolean {
@@ -2247,7 +2264,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2264 occurredAt: now,
2265 payload: {
2266 ...message,
2250 - text: delegatedCompletionWakeDetail(remainingTaskIds),
2267 + text: delegatedCompletionWakeDetail(remainingTaskIds, projection.subagents),
2268 delegatedCompletion: {
2269 parentRunId: parentRun.id,
2270 generation: delivery.generation,
@@ -5092,7 +5109,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5109 const dispatchText =
5110 delegatedCompletion === undefined
5111 ? command.text
5095 - : delegatedCompletionWakeDetail(delegatedCompletion.taskIds);
5112 + : delegatedCompletionWakeDetail(delegatedCompletion.taskIds, projection.subagents);
5113 const sourcePlanProjection =
5114 command.sourcePlanRef === undefined
5115 ? null
@@ -10345,7 +10362,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10362 ? undefined
10363 : {
10364 ...message,
10348 - text: delegatedCompletionWakeDetail(taskIds),
10365 + text: delegatedCompletionWakeDetail(
10366 + taskIds,
10367 + input.parentProjection.subagents.map((task) =>
10368 + task.id === input.updatedTask.id ? input.updatedTask : task,
10369 + ),
10370 + ),
10371 delegatedCompletion: {
10372 parentRunId: input.parentRun.id,
10373 generation: delivery.generation,
@@ -10635,46 +10657,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10657 targetThreadId: parentThreadId,
10658 type: "subagent_result",
10659 });
10638 - const childProviderThread =
10639 - childRun.providerThreadId === null
10640 - ? undefined
10641 - : childProjection.providerThreads.find(
10642 - (candidate) => candidate.id === childRun.providerThreadId,
10643 - );
10644 - const parentProviderThread =
10645 - parentRun?.providerThreadId === null || parentRun?.providerThreadId === undefined
10646 - ? undefined
10647 - : parentProjection.providerThreads.find(
10648 - (candidate) => candidate.id === parentRun.providerThreadId,
10649 - );
10650 - const resultHandoff: OrchestrationV2ContextHandoff | null =
10651 - parentRun === undefined ||
10652 - childProviderThread === undefined ||
10653 - parentProviderThread === undefined
10654 - ? null
10655 - : {
10656 - id: yield* idAllocator.allocate.contextHandoff({
10657 - threadId: parentThreadId,
10658 - fromProviderInstanceId: childRun.providerInstanceId,
10659 - toProviderInstanceId: parentRun.providerInstanceId,
10660 - }),
10661 - transferId: resultTransferId,
10662 - threadId: parentThreadId,
10663 - targetRunId: parentRun.id,
10664 - fromProviderThreadIds: [childProviderThread.id],
10665 - toProviderThreadId: parentProviderThread.id,
10666 - coveredRunOrdinals: {
10667 - from: childRun.ordinal,
10668 - to: childRun.ordinal,
10669 - },
10670 - strategy: "manual_context",
10671 - status: "ready",
10672 - summaryMessageId: result.messageId,
10673 - summaryText: result.text,
10674 - createdByProviderInstanceId: childRun.providerInstanceId,
10675 - createdAt: now,
10676 - updatedAt: now,
10677 - };
10660 const resultTransfer: OrchestrationV2ContextTransfer = {
10661 id: resultTransferId,
10662 type: "subagent_result",
@@ -10690,13 +10672,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10672 parentRun?.providerInstanceId ?? parentProjection.thread.providerInstanceId,
10673 targetRunId: parentRun?.id ?? null,
10674 status: "consumed",
10693 - resolution:
10694 - resultHandoff === null
10695 - ? null
10696 - : {
10697 - strategy: "portable_context",
10698 - contextHandoffId: resultHandoff.id,
10699 - },
10675 + resolution: null,
10676 createdBy: "system",
10677 error: null,
10678 createdAt: now,
@@ -10785,18 +10761,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10761 },
10762 },
10763 ]),
10788 - ...(resultHandoff === null
10789 - ? []
10790 - : [
10791 - {
10792 - type: "context-handoff.updated" as const,
10793 - threadId: parentThreadId,
10794 - ...(parentRun === undefined ? {} : { runId: parentRun.id }),
10795 - providerInstanceId: childRun.providerInstanceId,
10796 - occurredAt: now,
10797 - payload: resultHandoff,
10798 - },
10799 - ]),
10764 {
10765 type: "context-transfer.created",
10766 threadId: parentThreadId,
apps/server/src/orchestration-v2/ProviderTurnStartService.memory.test.ts
+1 -1
@@ -6,7 +6,7 @@ import { expect, it } from "vite-plus/test";
6
7 const execFile = NodeUtil.promisify(NodeChildProcess.execFile);
8
9 -it.each(["regular", "handoff", "handoff-compact", "handoff-failure"])(
9 +it.each(["regular", "handoff", "handoff-compact", "handoff-failure", "subagent-result"])(
10 "releases startup history while %s run workers remain alive",
11 async (mode) => {
12 const root = NodeURL.fileURLToPath(new URL("../../../../", import.meta.url));
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+8
@@ -252,8 +252,16 @@ export const layer: Layer.Layer<
252 const checkpointScope = projection.checkpointScopes.find(
253 (candidate) => candidate.id === rootNode?.checkpointScopeId,
254 );
255 + // Older versions also stored subagent replies as history handoffs. Their
256 + // queued completion messages carry the results without a history budget.
257 + const subagentResultTransfers = new Set(
258 + projection.contextTransfers
259 + .filter((transfer) => transfer.type === "subagent_result")
260 + .map((transfer) => transfer.id),
261 + );
262 const handoffs = projection.contextHandoffs.filter(
263 (handoff) =>
264 + (handoff.transferId == null || !subagentResultTransfers.has(handoff.transferId)) &&
265 handoff.status === "ready" &&
266 (handoff.targetRunId === run.id ||
267 (handoff.toProviderThreadId === run.providerThreadId &&
apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs
+9 -4
@@ -4,7 +4,7 @@ import * as NodeCrypto from "node:crypto";
4 import * as NodeAssert from "node:assert/strict";
5 const root = process.argv[2];
6 const mode = process.argv[3];
7 -const withHandoff = mode.startsWith("handoff");
7 +const withHandoff = mode.startsWith("handoff") || mode === "subagent-result";
8 const require = NodeModule.createRequire(root + "/apps/server/package.json");
9 const load = (name) => import(NodeURL.pathToFileURL(require.resolve("effect/" + name)));
10 const [Effect, Layer, FileSystem, Path] = await Promise.all([
@@ -160,7 +160,10 @@ function fixture(index) {
160 driver: "codex",
161 providerSessionId: "session",
162 nativeThreadRef: { nativeId: "native", driver: "codex", strength: "strong" },
163 - contextUsage: { usedTokens: 0, maxTokens: 128000 },
163 + contextUsage:
164 + mode === "subagent-result"
165 + ? { usedTokens: 390458, maxTokens: 475000 }
166 + : { usedTokens: 0, maxTokens: 128000 },
167 handoffIds: [],
168 },
169 ],
@@ -170,19 +173,21 @@ function fixture(index) {
173 ? [
174 {
175 id: "handoff",
176 + transferId: mode === "subagent-result" ? "subagent-transfer" : null,
177 threadId: "thread",
178 targetRunId: runId,
179 toProviderThreadId: "provider",
180 fromProviderThreadIds: ["provider"],
181 coveredRunOrdinals: { from: 1, to: 1 },
182 status: "ready",
179 - strategy: "full_thread_summary",
183 + strategy: mode === "subagent-result" ? "manual_context" : "full_thread_summary",
184 summaryText: "Synthetic summary",
185 handoffIds: [],
186 },
187 ]
188 : [],
185 - contextTransfers: [],
189 + contextTransfers:
190 + mode === "subagent-result" ? [{ id: "subagent-transfer", type: "subagent_result" }] : [],
191 providerSessions: [],
192 providerTurns: [],
193 subagents: [],