@devries-cameron20 / t3code Mirror · read-only / commits / 303903acd9
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, 23:30 UTC

fix(server): a steer during a delegate_task wait no longer drops the child's result (#27387)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 11:54 UTC 303903acd9b571033b99b1c71616505ae386883d
2 files changed +193 -56
apps/server/src/mcp/OrchestratorMcpService.test.ts
+151
@@ -2261,6 +2261,157 @@ describe("OrchestratorMcpService provider resolution", () => {
2261 ),
2262 );
2263
2264 + it.effect.each(["local", "remote"] as const)(
2265 + "a blocking %s delegation cancelled mid-wait wakes its parent like an async task",
2266 + (placement) =>
2267 + Effect.gen(function* () {
2268 + const driver = ProviderDriverKind.make("codex");
2269 + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2270 + {
2271 + instanceId: codexInstanceId,
2272 + driver,
2273 + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
2274 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
2275 + openSession: () => Effect.die("The child never starts: the effect worker is off."),
2276 + },
2277 + ]);
2278 + const layerDatabase = SqlitePersistence.layerMemory;
2279 + const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
2280 + { name: "mcp-wait-cancelled" },
2281 + layerRegistry,
2282 + { databaseLayer: layerDatabase, runEffectWorker: false },
2283 + );
2284 + const layerSettings = ServerSettings.layerTest({
2285 + providerInstances: { [codexInstanceId]: { driver: "codex", enabled: true } },
2286 + });
2287 + const layerThreads = ThreadManagementService.layer.pipe(
2288 + Layer.provideMerge(layerOrchestrator),
2289 + Layer.provide(
2290 + LegacyV1ThreadImporter.layer.pipe(
2291 + Layer.provide(layerOrchestrator),
2292 + Layer.provide(layerDatabase),
2293 + ),
2294 + ),
2295 + Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
2296 + Layer.provideMerge(layerSettings),
2297 + );
2298 + const waiting = yield* Deferred.make<void>();
2299 + const layerWatchedThreads = Layer.effect(
2300 + ThreadManagementService.ThreadManagementService,
2301 + Effect.gen(function* () {
2302 + const threads = yield* ThreadManagementService.ThreadManagementService;
2303 + return {
2304 + ...threads,
2305 + streamStoredEventsFrom: (input) =>
2306 + Stream.unwrap(
2307 + Deferred.succeed(waiting, undefined).pipe(
2308 + Effect.as(threads.streamStoredEventsFrom(input)),
2309 + ),
2310 + ),
2311 + } satisfies ThreadManagementService.ThreadManagementService["Service"];
2312 + }),
2313 + ).pipe(Layer.provideMerge(layerThreads));
2314 + const remoteChild = {
2315 + environmentId: EnvironmentId.make("environment:mcp-providers-box"),
2316 + threadId: ThreadId.make("thread:mcp-providers-on-the-box"),
2317 + label: "Box",
2318 + };
2319 + // Records the task as the real delegation does once the linked environment launched it.
2320 + const layerRemoteDelegation = Layer.unwrap(
2321 + Effect.gen(function* () {
2322 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2323 + return Layer.mock(RemoteDelegation.RemoteDelegation)({
2324 + delegate: (_scope, input) =>
2325 + Effect.gen(function* () {
2326 + const run = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
2327 + yield* orchestrator.dispatch({
2328 + type: "delegated_task.remote.request",
2329 + commandId: CommandId.make("command:remote-delegate:wait-cancelled"),
2330 + parentThreadId,
2331 + parentRunId: run.id,
2332 + parentNodeId: run.rootNodeId!,
2333 + task: input.task,
2334 + driver: ProviderDriverKind.make("remote"),
2335 + modelSelection: run.modelSelection,
2336 + remoteChild,
2337 + completionWake: "settled_only",
2338 + });
2339 + const parent = yield* orchestrator.getThreadProjection(parentThreadId);
2340 + return { taskId: parent.subagents[0]!.id };
2341 + }).pipe(Effect.orDie),
2342 + });
2343 + }),
2344 + ).pipe(Layer.provide(layerWatchedThreads));
2345 + const layerTest = layerOrchestratorService.pipe(
2346 + Layer.provideMerge(layerWatchedThreads),
2347 + Layer.provide(
2348 + Layer.mergeAll(
2349 + NodeServices.layer,
2350 + layerRegistry,
2351 + layerSettings,
2352 + providerRegistryLayer([
2353 + providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }),
2354 + ]),
2355 + Layer.mock(ProjectService.ProjectService)({}),
2356 + Layer.mock(SecretRequests.SecretRequests)({}),
2357 + layerRemoteDelegation,
2358 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
2359 + ),
2360 + ),
2361 + );
2362 + yield* Effect.gen(function* () {
2363 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2364 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
2365 + yield* orchestrator.dispatch({
2366 + type: "thread.create",
2367 + createdBy: "user",
2368 + creationSource: "web",
2369 + commandId: CommandId.make("parent:create"),
2370 + threadId: parentThreadId,
2371 + projectId,
2372 + title: "MCP parent",
2373 + modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" },
2374 + runtimeMode: "full-access",
2375 + interactionMode: "default",
2376 + branch: null,
2377 + worktreePath: null,
2378 + });
2379 + yield* orchestrator.dispatch({
2380 + type: "message.dispatch",
2381 + createdBy: "user",
2382 + creationSource: "web",
2383 + commandId: CommandId.make("parent:start"),
2384 + threadId: parentThreadId,
2385 + messageId: MessageId.make("parent:message"),
2386 + text: "Delegate a review and wait for it.",
2387 + attachments: [],
2388 + dispatchMode: { type: "start_immediately" },
2389 + });
2390 + const call = yield* service
2391 + .delegateTask(scope, {
2392 + task: "Review the change.",
2393 + ...(placement === "remote"
2394 + ? { target: { environmentId: remoteChild.environmentId } }
2395 + : {}),
2396 + mode: "wait",
2397 + clientRequestId: "delegate-wait-cancelled",
2398 + })
2399 + .pipe(Effect.forkChild);
2400 + yield* Deferred.await(waiting);
2401 + // A steered Claude parent cancels the tools/call, which interrupts this fiber.
2402 + yield* Fiber.interrupt(call);
2403 + const parent = yield* orchestrator.getThreadProjection(parentThreadId);
2404 + const task = parent.subagents.find((subagent) => subagent.origin === "app_owned");
2405 + assert.equal(task?.status, "running");
2406 + assert.equal(
2407 + task?.completionWake,
2408 + "always",
2409 + "a cancelled blocking delegation left the task settled_only, so its result never reaches the still-live parent run",
2410 + );
2411 + }).pipe(Effect.provide(layerTest));
2412 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
2413 + );
2414 +
2415 it.effect(
2416 "inherits an available parent instance for driver-only targets and otherwise selects a healthy peer",
2417 () =>
apps/server/src/mcp/OrchestratorMcpService.ts
+42 -56
@@ -1667,33 +1667,61 @@ const make = Effect.gen(function* () {
1667 return response;
1668 });
1669
1670 - /** `mode=wait` on a task already recorded, as `delegateTask` does for its own. */
1670 + /**
1671 + * Blocks for `mode=wait`. A wait that ends without a terminal result, including an
1672 + * interrupted tools/call, upgrades the wake so a later result still reaches the parent.
1673 + */
1674 const awaitTask = Effect.fn("OrchestratorMcpService.awaitTask")(function* (
1675 scope: McpThreadInvocationScope,
1676 taskId: NodeId,
1677 + wakePolicyRequestKey: string,
1678 requestedTimeoutMs: number | undefined,
1679 ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
1680 const timeoutMs = Math.min(
1681 MAX_WAIT_TIMEOUT_MS,
1682 Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
1683 );
1680 - const waited = yield* waitForTask(scope, taskId, timeoutMs);
1681 - if (Option.isSome(waited)) return waited.value;
1682 - // As for a local task: once the blocking wait ends, a later result wakes the parent.
1683 - yield* threadManagement
1684 + const upgradeWake = threadManagement
1685 .dispatch({
1686 type: "delegated_task.wake-policy",
1687 commandId: stableCommandId({
1688 scope,
1688 - requestKey: taskId,
1689 + requestKey: wakePolicyRequestKey,
1690 operation: "delegate-task-wake-policy",
1691 }),
1692 parentThreadId: scope.thread.threadId,
1693 taskId,
1694 completionWake: "always",
1695 })
1695 - .pipe(Effect.ignoreCause({ log: true }));
1696 - return yield* readTask(scope, taskId, true, true);
1696 + .pipe(
1697 + Effect.catch((error) =>
1698 + Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
1699 + taskId,
1700 + outcome:
1701 + error._tag === "OrchestratorCommandPreviouslyRejectedError"
1702 + ? "previously_rejected"
1703 + : "dispatch_failed",
1704 + error,
1705 + }),
1706 + ),
1707 + Effect.catchCause((cause) =>
1708 + Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
1709 + taskId,
1710 + outcome: "defect",
1711 + cause,
1712 + }),
1713 + ),
1714 + );
1715 + const delivered = (waited: Option.Option<OrchestratorMcpDelegateTaskResult>) =>
1716 + Option.isSome(waited) && isTerminalTaskStatus(waited.value.status);
1717 + // The finalizer runs uninterruptibly, so a cancel right after the wait returns still upgrades.
1718 + const waited = yield* waitForTask(scope, taskId, timeoutMs).pipe(
1719 + Effect.onExit((exit) =>
1720 + Exit.isSuccess(exit) && delivered(exit.value) ? Effect.void : upgradeWake,
1721 + ),
1722 + );
1723 + if (Option.isSome(waited) && delivered(waited)) return waited.value;
1724 + return yield* readTask(scope, taskId, Option.isNone(waited), true);
1725 });
1726
1727 /**
@@ -2384,7 +2412,7 @@ const make = Effect.gen(function* () {
2412 target: { ...input.target, environmentId },
2413 });
2414 return yield* input.mode === "wait"
2387 - ? awaitTask(scope, taskId, input.timeoutMs)
2415 + ? awaitTask(scope, taskId, taskId, input.timeoutMs)
2416 : readTask(scope, taskId, false, true);
2417 }
2418 const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");
@@ -2482,8 +2510,8 @@ const make = Effect.gen(function* () {
2510 interactionMode,
2511 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
2512 // Async delegations wake the parent on every child terminal; wait
2485 - // delegations deliver through the blocking tool call, so a wake is
2486 - // only needed if the parent settled first (timeout, disconnect).
2513 + // delegations deliver through the blocking tool call until `awaitTask`
2514 + // gives up the wait (timeout, cancelled call) and upgrades the wake.
2515 completionWake: input.mode === "wait" ? "settled_only" : "always",
2516 })
2517 .pipe(
@@ -2523,51 +2551,9 @@ const make = Effect.gen(function* () {
2551 });
2552 }
2553
2526 - if (input.mode !== "wait") {
2527 - return yield* readTask(scope, taskId, false, true);
2528 - }
2529 - const timeoutMs = Math.min(
2530 - MAX_WAIT_TIMEOUT_MS,
2531 - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2532 - );
2533 - const waited = yield* waitForTask(scope, taskId, timeoutMs);
2534 - if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) {
2535 - return waited.value;
2536 - }
2537 - // An incomplete wait gives up delivery: upgrade so a later terminal
2538 - // wakes the parent even mid-turn.
2539 - yield* threadManagement
2540 - .dispatch({
2541 - type: "delegated_task.wake-policy",
2542 - commandId: stableCommandId({
2543 - scope,
2544 - requestKey: key,
2545 - operation: "delegate-task-wake-policy",
2546 - }),
2547 - parentThreadId: scope.thread.threadId,
2548 - taskId,
2549 - completionWake: "always",
2550 - })
2551 - .pipe(
2552 - Effect.catch((error) =>
2553 - Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2554 - taskId,
2555 - outcome:
2556 - error._tag === "OrchestratorCommandPreviouslyRejectedError"
2557 - ? "previously_rejected"
2558 - : "dispatch_failed",
2559 - error,
2560 - }),
2561 - ),
2562 - Effect.catchCause((cause) =>
2563 - Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2564 - taskId,
2565 - outcome: "defect",
2566 - cause,
2567 - }),
2568 - ),
2569 - );
2570 - return yield* readTask(scope, taskId, Option.isNone(waited), true);
2554 + return yield* input.mode === "wait"
2555 + ? awaitTask(scope, taskId, key, input.timeoutMs)
2556 + : readTask(scope, taskId, false, true);
2557 }),
2558 taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) {
2559 const scope = yield* requireThreadScope(callerScope, "task_status");