@devries-cameron20 / t3code Mirror · read-only / commits / 5393882fb8
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, 13:30 UTC

fix(mcp): return delegated task handles before client timeouts (#15622)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

maria committed Nov 14, 2026 at 21:55 UTC 5393882fb805a7331f48cebf6278d58975504551
8 files changed +181 -64
apps/server/src/mcp/OrchestratorMcpService.test.ts
+145
@@ -1636,6 +1636,151 @@ describe("OrchestratorMcpService provider resolution", () => {
1636 }),
1637 );
1638
1639 + it.effect.each([
1640 + { name: "default", timeoutMs: undefined, budgetMs: 30_000 },
1641 + { name: "capped", timeoutMs: 3_600_000, budgetMs: 45_000 },
1642 + { name: "shorter requested", timeoutMs: 500, budgetMs: 500 },
1643 + ])("returns task and thread handles at the $name wait budget", (scenario) =>
1644 + Effect.gen(function* () {
1645 + const subscribed = yield* Deferred.make<void>();
1646 + const returned = yield* Deferred.make<void>();
1647 + const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
1648 + const threadWaitBudgets = yield* Ref.make<ReadonlyArray<number | undefined>>([]);
1649 + const task = {
1650 + id: taskId,
1651 + threadId: parentThreadId,
1652 + runId: parentRunId,
1653 + parentNodeId,
1654 + origin: "app_owned",
1655 + providerInstanceId: codexInstanceId,
1656 + driver: "codex",
1657 + childThreadId,
1658 + model: "gpt-5.4",
1659 + status: "running",
1660 + result: null,
1661 + };
1662 + const dependencies = Layer.mergeAll(
1663 + NodeServices.layer,
1664 + NodeCrypto.layer,
1665 + Layer.mock(ThreadManagementService.ThreadManagementService)({
1666 + hasReceipt: () => Effect.succeed(false),
1667 + assertProviderInstanceEnabled: () => Effect.void,
1668 + isProviderInstanceEnabledForProject: () => Effect.succeed(true),
1669 + getThreadRecords: (threadId) =>
1670 + Effect.succeed(
1671 + threadId === parentThreadId ? parentProjection([task]) : childProjection,
1672 + ),
1673 + getThreadEventSequence: () => Effect.succeed(0),
1674 + delegatedTaskResultPending: () => Effect.succeed(false),
1675 + streamStoredEventsFrom: () =>
1676 + Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
1677 + Stream.drain,
1678 + Stream.concat(Stream.never),
1679 + ),
1680 + waitForThread: (input) =>
1681 + Ref.update(threadWaitBudgets, (budgets) => [...budgets, input.timeoutMs]).pipe(
1682 + Effect.as({ threadId: parentThreadId, run: null, timedOut: true }),
1683 + ),
1684 + dispatch: (command) =>
1685 + Ref.update(dispatched, (commands) => [...commands, command]).pipe(
1686 + Effect.as({
1687 + sequence: 1,
1688 + storedEvents: [{ event: { type: "subagent.updated", payload: task } }],
1689 + } as never),
1690 + ),
1691 + }),
1692 + ServerSettings.layerTest(),
1693 + providerRegistryLayer([
1694 + providerSnapshot({
1695 + instanceId: codexInstanceId,
1696 + driver: ProviderDriverKind.make("codex"),
1697 + model: "gpt-5.4",
1698 + }),
1699 + ]),
1700 + adapterRegistryLayer([codexInstanceId]),
1701 + Layer.mock(ProjectService.ProjectService)({}),
1702 + Layer.mock(SecretRequests.SecretRequests)({}),
1703 + Layer.mock(RemoteDelegation.RemoteDelegation)({}),
1704 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
1705 + );
1706 + yield* Effect.gen(function* () {
1707 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
1708 + const budget = scenario.timeoutMs === undefined ? {} : { timeoutMs: scenario.timeoutMs };
1709 + const waiting = yield* service
1710 + .delegateTask(scope, { task: "Review the change.", mode: "wait", ...budget })
1711 + .pipe(
1712 + Effect.tap(() => Deferred.succeed(returned, undefined)),
1713 + Effect.forkChild,
1714 + );
1715 + yield* Deferred.await(subscribed);
1716 + yield* TestClock.adjust(Duration.millis(scenario.budgetMs - 1));
1717 + assert.isFalse(yield* Deferred.isDone(returned));
1718 + yield* TestClock.adjust(Duration.millis(1));
1719 + const result = yield* Fiber.join(waiting);
1720 + assert.include(result, { taskId, childThreadId, status: "running", waitTimedOut: true });
1721 + assert.include((yield* Ref.get(dispatched)).at(-1), {
1722 + type: "delegated_task.wake-policy",
1723 + completionWake: "always",
1724 + });
1725 +
1726 + yield* service.waitForThread(scope, { threadId: parentThreadId, ...budget });
1727 + assert.deepEqual(yield* Ref.get(threadWaitBudgets), [scenario.budgetMs]);
1728 + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies))));
1729 + }),
1730 + );
1731 +
1732 + it.effect.each([
1733 + { name: "ten-minute default", timeoutMs: undefined, budgetMs: 600_000 },
1734 + { name: "one-hour maximum", timeoutMs: 3_600_000, budgetMs: 3_600_000 },
1735 + ])("keeps a secret request pending for its $name", (scenario) =>
1736 + Effect.gen(function* () {
1737 + const pending = yield* Deferred.make<void>();
1738 + const returned = yield* Deferred.make<void>();
1739 + const statuses = yield* Ref.make<ReadonlyArray<string>>([]);
1740 + const dependencies = Layer.mergeAll(
1741 + NodeServices.layer,
1742 + NodeCrypto.layer,
1743 + Layer.mock(ThreadManagementService.ThreadManagementService)({
1744 + getThreadRecords: () => Effect.succeed({ ...parentProjection([]), turnItems: [] }),
1745 + dispatch: (command) => {
1746 + if (command.type !== "secret_request.record") return Effect.die("Unexpected command");
1747 + return Ref.update(statuses, (values) => [...values, command.secretStatus]).pipe(
1748 + Effect.andThen(Deferred.succeed(pending, undefined)),
1749 + Effect.as({} as never),
1750 + );
1751 + },
1752 + }),
1753 + ServerSettings.layerTest(),
1754 + providerRegistryLayer([]),
1755 + adapterRegistryLayer([]),
1756 + Layer.mock(ProjectService.ProjectService)({}),
1757 + Layer.mock(SecretRequests.SecretRequests)({}),
1758 + Layer.mock(RemoteDelegation.RemoteDelegation)({}),
1759 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
1760 + );
1761 + yield* Effect.gen(function* () {
1762 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
1763 + const waiting = yield* service
1764 + .requestSecret(scope, {
1765 + label: "Token",
1766 + reason: "Connect the account.",
1767 + ...(scenario.timeoutMs === undefined ? {} : { timeoutMs: scenario.timeoutMs }),
1768 + })
1769 + .pipe(
1770 + Effect.tap(() => Deferred.succeed(returned, undefined)),
1771 + Effect.forkChild,
1772 + );
1773 + yield* Deferred.await(pending);
1774 + yield* TestClock.adjust(Duration.millis(scenario.budgetMs - 1));
1775 + assert.isFalse(yield* Deferred.isDone(returned));
1776 + assert.deepEqual(yield* Ref.get(statuses), ["pending"]);
1777 + yield* TestClock.adjust(Duration.millis(1));
1778 + assert.include(yield* Fiber.join(waiting), { status: "timed_out" });
1779 + assert.deepEqual(yield* Ref.get(statuses), ["pending", "cancelled"]);
1780 + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies))));
1781 + }),
1782 + );
1783 +
1784 it.effect(
1785 "advertises orchestration capability from registered adapters rather than a driver allowlist",
1786 () =>
apps/server/src/mcp/OrchestratorMcpService.ts
+10 -6
@@ -137,10 +137,11 @@ import * as SecretRequests from "../secrets/SecretRequests.ts";
137 import * as PeerForwarding from "../peer/PeerForwarding.ts";
138 import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
139
140 -const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
141 -// Nothing is written while a task wait blocks, and Node fetch drops a silent call at 300 s.
142 -const DEFAULT_TASK_WAIT_TIMEOUT_MS = 4 * 60 * 1_000;
143 -const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
140 +// Return recoverable handles before common MCP client timeouts expire.
141 +const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
142 +const MAX_WAIT_TIMEOUT_MS = 45_000;
143 +const DEFAULT_SECRET_REQUEST_TIMEOUT_MS = 10 * 60 * 1_000;
144 +const MAX_SECRET_REQUEST_TIMEOUT_MS = 60 * 60 * 1_000;
145 const TASK_WAKE_EVENTS = [
146 { thread: "parent", eventType: "subagent.updated" },
147 { thread: "child", eventType: "run.updated" },
@@ -1829,7 +1830,7 @@ const make = Effect.gen(function* () {
1830 ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
1831 const timeoutMs = Math.min(
1832 MAX_WAIT_TIMEOUT_MS,
1832 - Math.max(1, requestedTimeoutMs ?? DEFAULT_TASK_WAIT_TIMEOUT_MS),
1833 + Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
1834 );
1835 const upgradeWake = threadManagement
1836 .dispatch({
@@ -2428,7 +2429,10 @@ const make = Effect.gen(function* () {
2429 }).pipe(
2430 Effect.timeoutOption(
2431 Duration.millis(
2431 - Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),
2432 + Math.min(
2433 + input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS,
2434 + MAX_SECRET_REQUEST_TIMEOUT_MS,
2435 + ),
2436 ),
2437 ),
2438 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+1 -1
@@ -2402,7 +2402,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
2402 "mcp__t3-code__send_to_user",
2403 ];
2404
2405 -// T3 waits can block for an hour; exceed Claude's default 60 s timeout.
2405 +// request_secret can wait an hour; exceed Claude's default 60 s timeout.
2406 export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000;
2407
2408 // allowedTools pre-approves calls; tools controls availability. Pre-approve T3 tools for headless modes,
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+1 -1
@@ -1440,7 +1440,7 @@ export const CODEX_THREAD_CONFIG = {
1440 "features.concurrent_reasoning_summaries": true,
1441 } as const;
1442
1443 -// T3 waits can block for an hour; keep Codex's MCP timeout above that.
1443 +// request_secret can wait an hour; keep Codex's MCP timeout above that.
1444 const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60;
1445 // Holds T3 tools Codex must call directly, never from Code Mode. Calls arrive as
1446 // `t3-code-direct.<tool>`; t3McpToolPresentation.ts must keep resolving that form.
apps/server/src/peer/PeerForwarding.test.ts
+4 -15
@@ -133,12 +133,8 @@ const boxThreads = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) => {
133 stops: [...current.stops, `delegated-tasks.stop ${input.threadId}`],
134 })),
135 waitForThread: (input) =>
136 - Ref.updateAndGet(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe(
137 - Effect.map(({ waits }) => ({
138 - threadId: input.threadId,
139 - run: run(waits.length < 3 ? "running" : "completed"),
140 - timedOut: waits.length < 3,
141 - })),
136 + Ref.update(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe(
137 + Effect.as({ threadId: input.threadId, run: run("completed"), timedOut: false }),
138 ),
139 });
140 };
@@ -476,15 +472,8 @@ it.effect("keeps a forwarded wait short and its retries scoped to the caller", (
472 status: "completed",
473 timedOut: false,
474 });
479 - // Three pieces of at most 50 s each, the later ones pinned to the run
480 - // the first one found.
481 - expect(
482 - (yield* Ref.get(seen)).waits.map(({ timeoutMs, runId }) => [timeoutMs, runId]),
483 - ).toEqual([
484 - [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, undefined],
485 - [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun],
486 - [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun],
487 - ]);
475 + // One capped piece, so the caller's MCP request returns before its client times out.
476 + expect((yield* Ref.get(seen)).waits.map(({ timeoutMs }) => timeoutMs)).toEqual([45_000]);
477
478 const send = (caller: string, clientRequestId: string) =>
479 a.call(caller, "t3_thread_send", {
apps/server/src/peer/PeerForwarding.ts
+18 -39
@@ -25,14 +25,9 @@ import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.t
25 import * as PeerLinks from "./PeerLinks.ts";
26 import * as PeerMcpClient from "./PeerMcpClient.ts";
27
28 -/**
29 - * A peer's `/mcp` holds a wait open for its whole timeout without sending
30 - * anything, and T3 Connect's edge drops a request idle for about 100 s, so a
31 - * forwarded wait goes out in pieces no longer than this.
32 - */
33 -export const FORWARDED_WAIT_CHUNK_MS = 50_000;
34 -const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
35 -const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
28 +// Match local waits: return before MCP client timeouts and T3 Connect's ~100 s idle drop.
29 +const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
30 +const MAX_WAIT_TIMEOUT_MS = 45_000;
31
32 type Scope = McpInvocationContext.McpInvocationScope;
33
@@ -67,7 +62,7 @@ export class PeerForwarding extends Context.Service<
62 environmentId: EnvironmentId,
63 input: OrchestratorMcpThreadInterruptInput,
64 ) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;
70 - /** `t3_thread_wait` there, in pieces short enough to survive any route. */
65 + /** `t3_thread_wait` there, bounded like a local wait. */
66 readonly waitForThread: (
67 scope: Scope,
68 environmentId: EnvironmentId,
@@ -188,37 +183,21 @@ const make = Effect.gen(function* () {
183 input,
184 );
185
191 - const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn(
192 - "PeerForwarding.waitForThread",
193 - )(function* (scope, environmentId, input) {
194 - let remaining = Math.min(
195 - MAX_WAIT_TIMEOUT_MS,
196 - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
186 + const waitForThread: PeerForwarding["Service"]["waitForThread"] = (scope, environmentId, input) =>
187 + forward<OrchestratorMcpThreadWaitResult>(
188 + scope,
189 + "t3_thread_wait",
190 + OrchestratorMcpThreadWaitInput,
191 + OrchestratorMcpThreadWaitResult,
192 + environmentId,
193 + {
194 + ...input,
195 + timeoutMs: Math.min(
196 + MAX_WAIT_TIMEOUT_MS,
197 + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
198 + ),
199 + },
200 );
198 - let runId = input.runId;
199 - while (true) {
200 - const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS);
201 - const result = yield* forward<OrchestratorMcpThreadWaitResult>(
202 - scope,
203 - "t3_thread_wait",
204 - OrchestratorMcpThreadWaitInput,
205 - OrchestratorMcpThreadWaitResult,
206 - environmentId,
207 - {
208 - threadId: input.threadId,
209 - ...(runId === undefined ? {} : { runId }),
210 - timeoutMs: chunk,
211 - ...(input.untilDelegatedWorkSettled === undefined
212 - ? {}
213 - : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }),
214 - },
215 - );
216 - remaining -= chunk;
217 - if (!result.timedOut || remaining <= 0) return result;
218 - // Later pieces wait for the run the first one picked, not a newer one.
219 - runId = result.runId ?? undefined;
220 - }
221 - });
201
202 // While the beta is off, agents start nothing over links. Tasks already running there keep
203 // following through readThread, waitForThread and interruptThread, so they still finish.
apps/server/src/provider/agentContextBudget.json
+1 -1
@@ -1,5 +1,5 @@
1 {
2 "claudeSystemAppendBytes": 5930,
3 "codexAdditionalContextBytes": 7324,
4 - "mcpToolListJsonBytes": 49791
4 + "mcpToolListJsonBytes": 49790
5 }
packages/contracts/src/orchestratorMcp.ts
+1 -1
@@ -185,7 +185,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({
185 }),
186 ),
187 timeoutMs: Schema.optional(Schema.Finite).annotate({
188 - description: "Mode 'wait' only. Default 4 min. A timeout does not cancel the child.",
188 + description: "Mode 'wait' only. At most 45 s. A timeout does not cancel the child.",
189 }),
190 clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
191 runtimeMode: Schema.optional(