@devries-cameron20 / t3code-1 / commits / da54e47f26
Fork 0

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

fix(server): launches whose caller goes away still start (#36499)

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

Manuel Huez committed Nov 20, 2026 at 05:49 UTC da54e47f26066a02266c9db582b280c4a7de905f
4 files changed +321 -66
apps/server/src/mcp/OrchestratorMcpService.test.ts
+197
@@ -1898,6 +1898,92 @@ describe("OrchestratorMcpService provider resolution", () => {
1898 }),
1899 );
1900
1901 + it.effect("leaves a result undelivered when the caller goes away after its wait times out", () =>
1902 + Effect.gen(function* () {
1903 + const subscribed = yield* Deferred.make<void>();
1904 + const upgrading = yield* Deferred.make<void>();
1905 + const finishUpgrade = yield* Deferred.make<void>();
1906 + const dispatched = yield* Ref.make<ReadonlyArray<{ readonly type: string }>>([]);
1907 + let task: Record<string, unknown> = {
1908 + id: taskId,
1909 + threadId: parentThreadId,
1910 + runId: parentRunId,
1911 + parentNodeId,
1912 + origin: "app_owned",
1913 + providerInstanceId: codexInstanceId,
1914 + driver: "codex",
1915 + childThreadId,
1916 + model: "gpt-5.4",
1917 + status: "running",
1918 + result: null,
1919 + };
1920 + const dependencies = Layer.mergeAll(
1921 + NodeServices.layer,
1922 + NodeCrypto.layer,
1923 + Layer.mock(ThreadManagementService.ThreadManagementService)({
1924 + hasReceipt: () => Effect.succeed(false),
1925 + assertProviderInstanceEnabled: () => Effect.void,
1926 + isProviderInstanceEnabledForProject: () => Effect.succeed(true),
1927 + getThreadRecords: (threadId) =>
1928 + Effect.sync(() =>
1929 + threadId === parentThreadId ? parentProjection([task]) : childProjection,
1930 + ),
1931 + getThreadEventSequence: () => Effect.succeed(0),
1932 + delegatedTaskResultPending: () => Effect.succeed(false),
1933 + streamStoredEventsFrom: () =>
1934 + Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
1935 + Stream.drain,
1936 + Stream.concat(Stream.never),
1937 + ),
1938 + dispatch: (command) =>
1939 + Ref.update(dispatched, (commands) => [...commands, command]).pipe(
1940 + Effect.andThen(
1941 + command.type === "delegated_task.wake-policy"
1942 + ? Deferred.succeed(upgrading, undefined).pipe(
1943 + Effect.andThen(Deferred.await(finishUpgrade)),
1944 + )
1945 + : Effect.void,
1946 + ),
1947 + Effect.as({
1948 + sequence: 1,
1949 + storedEvents: [{ event: { type: "subagent.updated", payload: task } }],
1950 + } as never),
1951 + ),
1952 + }),
1953 + ServerSettings.layerTest(),
1954 + providerRegistryLayer([
1955 + providerSnapshot({
1956 + instanceId: codexInstanceId,
1957 + driver: ProviderDriverKind.make("codex"),
1958 + model: "gpt-5.4",
1959 + }),
1960 + ]),
1961 + adapterRegistryLayer([codexInstanceId]),
1962 + Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }),
1963 + Layer.mock(SecretRequests.SecretRequests)({}),
1964 + Layer.mock(RemoteDelegation.RemoteDelegation)({}),
1965 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
1966 + );
1967 + yield* Effect.gen(function* () {
1968 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
1969 + const waiting = yield* service
1970 + .delegateTask(scope, { task: "Review the change.", mode: "wait", timeoutMs: 500 })
1971 + .pipe(Effect.forkChild);
1972 + yield* Deferred.await(subscribed);
1973 + yield* TestClock.adjust(Duration.millis(500));
1974 + yield* Deferred.await(upgrading);
1975 + yield* Effect.sync(() => waiting.interruptUnsafe());
1976 + task = { ...task, status: "completed", result: "Reviewed." };
1977 + yield* Deferred.succeed(finishUpgrade, undefined);
1978 + yield* Fiber.await(waiting);
1979 + assert.notInclude(
1980 + (yield* Ref.get(dispatched)).map((command) => command.type),
1981 + "delegated_task.completion-delivery.acknowledge",
1982 + );
1983 + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies))));
1984 + }),
1985 + );
1986 +
1987 it.effect.each([
1988 { name: "ten-minute default", timeoutMs: undefined, budgetMs: 600_000 },
1989 { name: "one-hour maximum", timeoutMs: 3_600_000, budgetMs: 3_600_000 },
@@ -2941,6 +3027,117 @@ describe("OrchestratorMcpService provider resolution", () => {
3027 }),
3028 );
3029
3030 + it.effect.each(["async", "wait"] as const)(
3031 + "prepares a delegated child whose %s caller goes away after its run commits",
3032 + (mode) =>
3033 + Effect.gen(function* () {
3034 + const runCommitted = yield* Deferred.make<void>();
3035 + const wakePolicies = yield* Ref.make<ReadonlyArray<string>>([]);
3036 + const finishDispatch = yield* Deferred.make<void>();
3037 + const prepared = yield* Deferred.make<void>();
3038 + const childRunId = RunId.make("run:mcp-delegate-caller-gone");
3039 + const task = {
3040 + id: taskId,
3041 + threadId: parentThreadId,
3042 + runId: parentRunId,
3043 + parentNodeId,
3044 + origin: "app_owned",
3045 + createdBy: "agent",
3046 + driver: ProviderDriverKind.make("codex"),
3047 + providerInstanceId: codexInstanceId,
3048 + providerThreadId: null,
3049 + childThreadId,
3050 + nativeTaskRef: null,
3051 + prompt: "Summarize the diff.",
3052 + title: null,
3053 + model: "gpt-5.4",
3054 + status: "running",
3055 + result: null,
3056 + startedAt: null,
3057 + completedAt: null,
3058 + };
3059 + const layerDependencies = Layer.mergeAll(
3060 + NodeServices.layer,
3061 + NodeCrypto.layer,
3062 + Layer.mock(ThreadManagementService.ThreadManagementService)({
3063 + hasReceipt: () => Effect.succeed(false),
3064 + getThreadRecords: (threadId) =>
3065 + Effect.succeed(threadId === parentThreadId ? parentProjection([]) : childProjection),
3066 + isProviderInstanceEnabledForProject: () => Effect.succeed(true),
3067 + assertProviderInstanceEnabled: () => Effect.void,
3068 + dispatch: (command) =>
3069 + command.type === "delegated_task.wake-policy"
3070 + ? Ref.update(wakePolicies, (policies) => [
3071 + ...policies,
3072 + command.completionWake,
3073 + ]).pipe(Effect.as({ sequence: 3, storedEvents: [] } as never))
3074 + : Deferred.succeed(runCommitted, undefined).pipe(
3075 + Effect.andThen(Deferred.await(finishDispatch)),
3076 + Effect.as({
3077 + sequence: 2,
3078 + storedEvents: [
3079 + {
3080 + sequence: 1,
3081 + commandId: null,
3082 + event: { type: "subagent.updated", payload: task },
3083 + },
3084 + {
3085 + sequence: 2,
3086 + commandId: null,
3087 + event: {
3088 + type: "run.created",
3089 + threadId: childThreadId,
3090 + payload: { id: childRunId, workspacePreparation: { type: "root" } },
3091 + },
3092 + },
3093 + ],
3094 + } as never),
3095 + ),
3096 + }),
3097 + providerRegistryLayer([
3098 + providerSnapshot({
3099 + instanceId: codexInstanceId,
3100 + driver: ProviderDriverKind.make("codex"),
3101 + model: "gpt-5.4",
3102 + }),
3103 + ]),
3104 + adapterRegistryLayer([codexInstanceId]),
3105 + Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }),
3106 + Layer.mock(SecretRequests.SecretRequests)({}),
3107 + Layer.mock(RemoteDelegation.RemoteDelegation)({}),
3108 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
3109 + ServerSettings.layerTest(),
3110 + );
3111 + const layerService = OrchestratorMcpService.layer.pipe(
3112 + Layer.provide(
3113 + Layer.mock(ThreadLaunchService.ThreadLaunchService)({
3114 + prepareRun: (input) =>
3115 + input.runId === childRunId ? Deferred.succeed(prepared, undefined) : Effect.void,
3116 + }),
3117 + ),
3118 + Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
3119 + );
3120 +
3121 + yield* Effect.gen(function* () {
3122 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
3123 + const delegation = yield* Effect.forkChild(
3124 + service.delegateTask(scope, {
3125 + task: "Summarize the diff.",
3126 + target: { driverKind: ProviderDriverKind.make("codex") },
3127 + mode,
3128 + clientRequestId: `delegate-caller-gone-${mode}`,
3129 + }),
3130 + );
3131 + yield* Deferred.await(runCommitted);
3132 + yield* Effect.sync(() => delegation.interruptUnsafe());
3133 + yield* Deferred.succeed(finishDispatch, undefined);
3134 + yield* Fiber.await(delegation);
3135 + yield* Deferred.await(prepared);
3136 + assert.deepEqual(yield* Ref.get(wakePolicies), mode === "wait" ? ["always"] : []);
3137 + }).pipe(Effect.provide(layerService.pipe(Layer.provide(layerDependencies))));
3138 + }),
3139 + );
3140 +
3141 it.effect(
3142 "retrying an accepted driver-only delegation replays even after the project disables every candidate",
3143 () =>
apps/server/src/mcp/OrchestratorMcpService.ts
+77 -65
@@ -2035,6 +2035,8 @@ const make = Effect.gen(function* () {
2035 taskId: NodeId,
2036 wakePolicyRequestKey: string,
2037 requestedTimeoutMs: number | undefined,
2038 + restore: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> = (effect) =>
2039 + effect,
2040 ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
2041 const timeoutMs = Math.min(
2042 MAX_WAIT_TIMEOUT_MS,
@@ -2073,14 +2075,16 @@ const make = Effect.gen(function* () {
2075 );
2076 const delivered = (waited: Option.Option<OrchestratorMcpDelegateTaskResult>) =>
2077 Option.isSome(waited) && isTerminalTaskStatus(waited.value.status);
2076 - // The finalizer runs uninterruptibly, so a cancel right after the wait returns still upgrades.
2077 - const waited = yield* waitForTask(scope, taskId, timeoutMs).pipe(
2078 + // The finalizer runs uninterruptibly, and only the wait and the fallback read are
2079 + // restored, so a cancel just before or after the wait still upgrades without the read
2080 + // acknowledging a result the caller never receives.
2081 + const waited = yield* restore(waitForTask(scope, taskId, timeoutMs)).pipe(
2082 Effect.onExit((exit) =>
2083 Exit.isSuccess(exit) && delivered(exit.value) ? Effect.void : upgradeWake,
2084 ),
2085 );
2086 if (Option.isSome(waited) && delivered(waited)) return waited.value;
2083 - return yield* readTask(scope, taskId, Option.isNone(waited), true);
2087 + return yield* restore(readTask(scope, taskId, Option.isNone(waited), true));
2088 });
2089
2090 /**
@@ -2886,69 +2890,77 @@ const make = Effect.gen(function* () {
2890 }
2891 workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };
2892 }
2889 - // ThreadManagementService.dispatch is the chokepoint for this command
2890 - // type's own enablement check, using the same command id and its
2891 - // receipt-replay exemption, so no separate assert runs here.
2892 - const result = yield* threadManagement
2893 - .dispatch({
2894 - type: "delegated_task.request",
2895 - createdBy: "agent",
2896 - creationSource: "mcp",
2897 - commandId,
2898 - parentThreadId: scope.thread.threadId,
2899 - parentRunId: parentRun.id,
2900 - parentNodeId: parentRun.rootNodeId,
2901 - task: taskPrompt(input),
2902 - ...(input.title === undefined ? {} : { title: input.title }),
2903 - modelSelection: target.modelSelection,
2904 - runtimeMode,
2905 - interactionMode,
2906 - ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
2907 - // Async delegations wake the parent on every child terminal; wait
2908 - // delegations deliver through the blocking tool call until `awaitTask`
2909 - // gives up the wait (timeout, cancelled call) and upgrades the wake.
2910 - completionWake: input.mode === "wait" ? "settled_only" : "always",
2911 - })
2912 - .pipe(
2913 - Effect.mapError((error) =>
2914 - error._tag === "ThreadManagementProviderInstanceDisabledError"
2915 - ? threadManagementFailure(error)
2916 - : failure(
2917 - "orchestration_error",
2918 - `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
2919 - ),
2920 - ),
2921 - );
2922 - const taskEvent = result.storedEvents.find(
2923 - (stored) =>
2924 - stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",
2925 - );
2926 - if (taskEvent?.event.type !== "subagent.updated") {
2927 - return yield* failure(
2928 - "orchestration_error",
2929 - "Delegated task command did not produce a task projection.",
2930 - );
2931 - }
2932 - const taskId = taskEvent.event.payload.id;
2933 - const childThreadId = taskEvent.event.payload.childThreadId;
2934 - const childRunEvent = result.storedEvents.find(
2935 - (stored) => stored.event.type === "run.created" && stored.event.threadId === childThreadId,
2893 + const parentNodeId = parentRun.rootNodeId;
2894 + // The command commits the child's preparing run, which only this call
2895 + // prepares, so a caller that goes away must not stop it in between.
2896 + return yield* Effect.uninterruptibleMask((restore) =>
2897 + Effect.gen(function* () {
2898 + // ThreadManagementService.dispatch is the chokepoint for this command
2899 + // type's own enablement check, using the same command id and its
2900 + // receipt-replay exemption, so no separate assert runs here.
2901 + const result = yield* threadManagement
2902 + .dispatch({
2903 + type: "delegated_task.request",
2904 + createdBy: "agent",
2905 + creationSource: "mcp",
2906 + commandId,
2907 + parentThreadId: scope.thread.threadId,
2908 + parentRunId: parentRun.id,
2909 + parentNodeId,
2910 + task: taskPrompt(input),
2911 + ...(input.title === undefined ? {} : { title: input.title }),
2912 + modelSelection: target.modelSelection,
2913 + runtimeMode,
2914 + interactionMode,
2915 + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
2916 + // Async delegations wake the parent on every child terminal; wait
2917 + // delegations deliver through the blocking tool call until `awaitTask`
2918 + // gives up the wait (timeout, cancelled call) and upgrades the wake.
2919 + completionWake: input.mode === "wait" ? "settled_only" : "always",
2920 + })
2921 + .pipe(
2922 + Effect.mapError((error) =>
2923 + error._tag === "ThreadManagementProviderInstanceDisabledError"
2924 + ? threadManagementFailure(error)
2925 + : failure(
2926 + "orchestration_error",
2927 + `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
2928 + ),
2929 + ),
2930 + );
2931 + const taskEvent = result.storedEvents.find(
2932 + (stored) =>
2933 + stored.event.type === "subagent.updated" &&
2934 + stored.event.payload.origin === "app_owned",
2935 + );
2936 + if (taskEvent?.event.type !== "subagent.updated") {
2937 + return yield* failure(
2938 + "orchestration_error",
2939 + "Delegated task command did not produce a task projection.",
2940 + );
2941 + }
2942 + const taskId = taskEvent.event.payload.id;
2943 + const childThreadId = taskEvent.event.payload.childThreadId;
2944 + const childRunEvent = result.storedEvents.find(
2945 + (stored) =>
2946 + stored.event.type === "run.created" && stored.event.threadId === childThreadId,
2947 + );
2948 + if (
2949 + childThreadId !== null &&
2950 + childRunEvent?.event.type === "run.created" &&
2951 + childRunEvent.event.payload.workspacePreparation !== undefined
2952 + ) {
2953 + yield* threadLaunch.prepareRun({
2954 + commandId,
2955 + threadId: childThreadId,
2956 + runId: childRunEvent.event.payload.id,
2957 + });
2958 + }
2959 + return yield* input.mode === "wait"
2960 + ? awaitTask(scope, taskId, key, input.timeoutMs, restore)
2961 + : restore(readTask(scope, taskId, false, true));
2962 + }),
2963 );
2937 - if (
2938 - childThreadId !== null &&
2939 - childRunEvent?.event.type === "run.created" &&
2940 - childRunEvent.event.payload.workspacePreparation !== undefined
2941 - ) {
2942 - yield* threadLaunch.prepareRun({
2943 - commandId,
2944 - threadId: childThreadId,
2945 - runId: childRunEvent.event.payload.id,
2946 - });
2947 - }
2948 -
2949 - return yield* input.mode === "wait"
2950 - ? awaitTask(scope, taskId, key, input.timeoutMs)
2951 - : readTask(scope, taskId, false, true);
2964 }),
2965 taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) {
2966 const scope = yield* requireThreadScope(callerScope, "task_status");
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+41
@@ -38,6 +38,7 @@ import * as DateTime from "effect/DateTime";
38 import * as Duration from "effect/Duration";
39 import * as Effect from "effect/Effect";
40 import * as Exit from "effect/Exit";
41 +import * as Fiber from "effect/Fiber";
42 import * as Layer from "effect/Layer";
43 import * as Option from "effect/Option";
44 import * as Ref from "effect/Ref";
@@ -2511,6 +2512,46 @@ it.effect(
2512 }),
2513 );
2514
2515 +it.effect("prepares a launch whose caller goes away after its first message commits", () =>
2516 + Effect.gen(function* () {
2517 + const messageCommitted = yield* Deferred.make<void>();
2518 + const finishDispatch = yield* Deferred.make<void>();
2519 + const setupEntered = yield* Deferred.make<void>();
2520 + const harness = makeHarness({
2521 + runSetup: () =>
2522 + Deferred.succeed(setupEntered, undefined).pipe(Effect.as({ status: "no-script" as const })),
2523 + dispatch: (command, dispatch) =>
2524 + dispatch(command).pipe(
2525 + Effect.tap((result) =>
2526 + result.storedEvents.some((stored) => stored.event.type === "run.created")
2527 + ? Deferred.succeed(messageCommitted, undefined).pipe(
2528 + Effect.andThen(Deferred.await(finishDispatch)),
2529 + )
2530 + : Effect.void,
2531 + ),
2532 + ),
2533 + });
2534 + yield* Effect.gen(function* () {
2535 + const launches = yield* ThreadLaunch.ThreadLaunchService;
2536 + const launch = yield* Effect.forkChild(
2537 + launches.launch(
2538 + launchInput({
2539 + command: "command:launch:caller-gone",
2540 + thread: "thread:launch:caller-gone",
2541 + message: "Prepare without the caller",
2542 + workspace: { type: "worktree", baseRef: "main" },
2543 + }),
2544 + ),
2545 + );
2546 + yield* Deferred.await(messageCommitted);
2547 + yield* Effect.sync(() => launch.interruptUnsafe());
2548 + yield* Deferred.succeed(finishDispatch, undefined);
2549 + yield* Fiber.await(launch);
2550 + yield* Deferred.await(setupEntered);
2551 + }).pipe(Effect.provide(harness.layer));
2552 + }),
2553 +);
2554 +
2555 it.effect("creates a strong provider-thread mapping for an imported native session", () => {
2556 const harness = makeHarness();
2557 return Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+6 -1
@@ -1333,7 +1333,9 @@ const make = Effect.gen(function* () {
1333 },
1334 )
1335 : input.workspaceStrategy;
1336 - const initialBranch = yield* launchBranch(workspaceStrategy, project.workspaceRoot);
1336 + const initialBranch = yield* Effect.interruptible(
1337 + launchBranch(workspaceStrategy, project.workspaceRoot),
1338 + );
1339 const initialWorktreePath =
1340 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
1341 const initialMessage =
@@ -1515,6 +1517,9 @@ const make = Effect.gen(function* () {
1517 };
1518 });
1519 },
1520 + // The message commits a preparing run that only this call schedules, so a
1521 + // caller that goes away must not stop the launch between the two.
1522 + Effect.uninterruptible,
1523 );
1524
1525 const prepareRun: ThreadLaunchService["Service"]["prepareRun"] = Effect.fn(