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, 21:00 UTC
fix(server): Codex goals wait for a delegated task instead of re-prompting (#34898)
Julius Marminge committed
Nov 11, 2026 at 23:53 UTC
1e438c8f806c361943f6f20ed5b1a5cc7ec70e4e
5 files changed
+320
-54
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+139
@@ -9888,6 +9888,145 @@ describe("CodexAdapterV2 post-settle continuation", () => {
9888
),
9889
);
9890
9891
+ it.effect("pauses a goal at once while a delegated task will wake the thread", () =>
9892
+ Effect.gen(function* () {
9893
+ const lookupStarted = yield* Deferred.make<void>();
9894
+ const lookupAnswered = yield* Deferred.make<void>();
9895
+ const turnStart = (id: number, text: string) =>
9896
+ Effect.map(
9897
+ CodexAdapterV2.buildCodexTurnStartParams({
9898
+ nativeThreadId,
9899
+ codexInput: [{ type: "text", text }],
9900
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
9901
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
9902
+ hasT3Mcp: true,
9903
+ }),
9904
+ (params): CodexReplay.CodexAppServerReplayEntry => ({
9905
+ type: "expect_outbound",
9906
+ label: "turn/start",
9907
+ frame: { id, method: "turn/start", params },
9908
+ }),
9909
+ );
9910
+ const transcript = makeCodexReplayTranscript({
9911
+ scenario: "goal-paused-for-wake",
9912
+ entries: [
9913
+ ...sessionStart,
9914
+ yield* turnStart(3, "Delegate and wait"),
9915
+ ...withReplayRequestId(
9916
+ codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt: "" }).slice(
9917
+ 6,
9918
+ ),
9919
+ 3,
9920
+ ),
9921
+ notification("goal active", "thread/goal/updated", {
9922
+ threadId: nativeThreadId,
9923
+ turnId: "goal-turn",
9924
+ goal: codexGoal("active", 10),
9925
+ }),
9926
+ notification("turn done", "turn/completed", {
9927
+ threadId: nativeThreadId,
9928
+ turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
9929
+ }),
9930
+ // Codex continues before the wake lookup answers.
9931
+ notification("continuation", "turn/started", {
9932
+ threadId: nativeThreadId,
9933
+ turn: makeCodexReplayTurn({ id: "goal-turn-2", status: "inProgress" }),
9934
+ }),
9935
+ ...request(
9936
+ 4,
9937
+ "thread/goal/set",
9938
+ { threadId: nativeThreadId, status: "paused" },
9939
+ { goal: codexGoal("paused", 10) },
9940
+ ),
9941
+ ...request(
9942
+ 5,
9943
+ "thread/goal/set",
9944
+ { threadId: nativeThreadId, status: "paused" },
9945
+ { goal: codexGoal("paused", 10) },
9946
+ ),
9947
+ ...request(
9948
+ 6,
9949
+ "turn/interrupt",
9950
+ { threadId: nativeThreadId, turnId: "goal-turn-2" },
9951
+ {},
9952
+ ),
9953
+ ...request(
9954
+ 7,
9955
+ "thread/goal/get",
9956
+ { threadId: nativeThreadId },
9957
+ { goal: codexGoal("paused", 10) },
9958
+ ),
9959
+ yield* turnStart(8, "Child finished"),
9960
+ ...withReplayRequestId(
9961
+ codexReplayPreamble({ nativeThreadId, nativeTurnId: "wake-turn", prompt: "" }).slice(
9962
+ 6,
9963
+ ),
9964
+ 8,
9965
+ ),
9966
+ ...request(
9967
+ 9,
9968
+ "thread/goal/set",
9969
+ { threadId: nativeThreadId, status: "active" },
9970
+ { goal: codexGoal("active", 10) },
9971
+ ),
9972
+ notification("goal resumed", "thread/goal/updated", {
9973
+ threadId: nativeThreadId,
9974
+ turnId: "wake-turn",
9975
+ goal: codexGoal("active", 10),
9976
+ }),
9977
+ ],
9978
+ });
9979
+ const harness = yield* makeCodexReplayHarness(transcript);
9980
+ yield* (yield* McpProviderSessions.McpProviderSessions).set({
9981
+ environmentId: EnvironmentId.make("test"),
9982
+ threadId: harness.threadId,
9983
+ providerSessionId: "wake-session",
9984
+ providerInstanceId: ProviderInstanceId.make("codex"),
9985
+ endpoint: "http://127.0.0.1:43123/mcp",
9986
+ authorizationHeader: "Bearer test",
9987
+ browserToolsAvailable: true,
9988
+ hasPendingWake: Deferred.succeed(lookupStarted, undefined).pipe(
9989
+ Effect.andThen(Deferred.await(lookupAnswered)),
9990
+ Effect.as(true),
9991
+ ),
9992
+ });
9993
+ yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "Delegate and wait"));
9994
+ yield* Deferred.await(lookupStarted);
9995
+ yield* Deferred.succeed(lookupAnswered, undefined);
9996
+ // Settles without waiting out the continuation grace.
9997
+ yield* harness.firstTerminal;
9998
+ assert.deepEqual(providerGoals(harness.events), ["active", "paused"]);
9999
+ assert.deepEqual(
10000
+ harness.terminalEvents().map((event) => event.status),
10001
+ ["completed"],
10002
+ );
10003
+ yield* harness.until(() => harness.terminalEvents().length === 1);
10004
+ assert.deepEqual(
10005
+ harness.events.flatMap((event) =>
10006
+ event.type === "provider_turn.updated" && event.providerTurn.status === "running"
10007
+ ? [event.providerTurn.ordinal]
10008
+ : [],
10009
+ ),
10010
+ [1],
10011
+ );
10012
+
10013
+ // Inspecting the goal must not cancel its resume on the wake.
10014
+ yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "/goal"));
10015
+ yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "Child finished"));
10016
+ yield* harness.until(() => providerGoals(harness.events).at(-1) === "active");
10017
+ }).pipe(
10018
+ Effect.scoped,
10019
+ Effect.provide(
10020
+ Layer.mergeAll(
10021
+ IdAllocator.layer,
10022
+ McpProviderSessions.layer,
10023
+ NodeServices.layer,
10024
+ NodeCrypto.layer,
10025
+ ),
10026
+ ),
10027
+ ),
10028
+ );
10029
+
10030
it.effect("stops a turn Codex starts while the expiry pause is in flight", () =>
10031
Effect.gen(function* () {
10032
const prompt = "Keep going";
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+102
-53
@@ -2045,6 +2045,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2045
const goalActivations = new Map<string, { stopped: boolean }>();
2046
// Held runs must not complete while Stop resolves its target.
2047
const goalStops = new Map<string, number>();
2048
+ // Goals paused because a delegated task will wake the thread; the next ordinary turn resumes them.
2049
+ const goalsPausedForWake = new Set<string>();
2050
const latestRunTurnId = (providerTurnId: ProviderTurnId) =>
2051
continuedRuns.get(providerTurnId)?.at(-1)?.providerTurnId ?? providerTurnId;
2052
const isContinuedRunDescendant = (
@@ -6279,14 +6281,31 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6281
event.status === "completed" &&
6282
nativeThreadId != null
6283
) {
6284
+ const hasPendingWake = (yield* mcpSessions.read(input.context.input.threadId))
6285
+ ?.hasPendingWake;
6286
+ // Decided under the permit before the hold exists, so no continuation can adopt it first.
6287
+ const waitsForWake = hasPendingWake === undefined ? false : yield* hasPendingWake;
6288
goalHolds.set(nativeThreadId, {
6289
context: input.context,
6290
event,
6291
completedTurn: input.goalHoldTurn,
6292
next: yield* Deferred.make<ActiveCodexTurnContext | undefined>(),
6293
});
6294
+ // A continuation turn would only report that the delegated task is still running.
6295
+ const claimed = waitsForWake ? claimGoalHold(nativeThreadId, event) : undefined;
6296
+ if (claimed !== undefined) {
6297
+ yield* pauseClaimedGoal(nativeThreadId, claimed, true).pipe(Effect.forkIn(scope));
6298
+ return;
6299
+ }
6300
yield* Effect.sleep(CODEX_GOAL_CONTINUATION_GRACE).pipe(
6289
- Effect.andThen(pauseUncontinuedGoal(nativeThreadId, event)),
6301
+ Effect.andThen(
6302
+ Effect.suspend(() => {
6303
+ const hold = claimGoalHold(nativeThreadId, event);
6304
+ return hold === undefined
6305
+ ? Effect.void
6306
+ : pauseClaimedGoal(nativeThreadId, hold, false);
6307
+ }),
6308
+ ),
6309
Effect.andThen(
6310
turnTerminalizationPermit.withPermits(1)(releaseGoalHold(nativeThreadId, event)),
6311
),
@@ -6301,24 +6320,31 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6320
6321
// A goal must not read as active once its run ends. Claiming the hold first
6322
// makes a turn Codex starts during the pause an orphan, which is stopped.
6304
- const pauseUncontinuedGoal = Effect.fnUntraced(function* (
6305
- nativeThreadId: string,
6306
- expected: CodexRootTerminalEvent,
6307
- ) {
6323
+ const claimGoalHold = (nativeThreadId: string, expected: CodexRootTerminalEvent) => {
6324
const hold = goalHolds.get(nativeThreadId);
6325
if (
6326
hold?.event !== expected ||
6327
goalStops.has(nativeThreadId) ||
6328
goalsByNativeThread.get(nativeThreadId)?.status !== "active"
6329
) {
6314
- return;
6330
+ return undefined;
6331
}
6332
goalHolds.delete(nativeThreadId);
6333
// Keeps a turn Codex starts before settlement an orphan once the goal reads paused.
6334
goalStops.set(nativeThreadId, (goalStops.get(nativeThreadId) ?? 0) + 1);
6319
- yield* Effect.logWarning("orchestration-v2.codex-goal-continuation-expired", {
6320
- nativeThreadId,
6321
- });
6335
+ return hold;
6336
+ };
6337
+
6338
+ const pauseClaimedGoal = Effect.fnUntraced(function* (
6339
+ nativeThreadId: string,
6340
+ hold: CodexGoalHold,
6341
+ waitsForWake: boolean,
6342
+ ) {
6343
+ if (!waitsForWake) {
6344
+ yield* Effect.logWarning("orchestration-v2.codex-goal-continuation-expired", {
6345
+ nativeThreadId,
6346
+ });
6347
+ }
6348
yield* client
6349
.request("thread/goal/set", { threadId: nativeThreadId, status: "paused" })
6350
.pipe(
@@ -6326,6 +6352,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6352
Effect.timeout("10 seconds"),
6353
Effect.flatMap(({ goal }) => {
6354
goalsByNativeThread.set(nativeThreadId, providerGoalFromCodex(goal));
6355
+ if (waitsForWake && goal.status === "paused")
6356
+ goalsPausedForWake.add(nativeThreadId);
6357
return emitGoalUpdate(nativeThreadId);
6358
}),
6359
Effect.catch((cause) =>
@@ -7275,6 +7303,47 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7303
),
7304
);
7305
7306
+ /** Starts a turn and then activates its paused goal; Stop cancels activation. */
7307
+ const activateGoal = Effect.fnUntraced(function* (
7308
+ turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
7309
+ threadId: string,
7310
+ codexInput: ReturnType<typeof toCodexInput>,
7311
+ ) {
7312
+ goalsPausedForWake.delete(threadId);
7313
+ // Hold fast first turns until activation.
7314
+ const activation = { stopped: false };
7315
+ goalActivations.set(threadId, activation);
7316
+ yield* Effect.gen(function* () {
7317
+ yield* startNativeTurn(turnInput, yield* codexInput);
7318
+ if (activation.stopped) return;
7319
+ const { goal } = yield* client.request("thread/goal/set", {
7320
+ threadId,
7321
+ status: "active",
7322
+ });
7323
+ goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
7324
+ if (activation.stopped) {
7325
+ const paused = yield* client.request("thread/goal/set", {
7326
+ threadId,
7327
+ status: "paused",
7328
+ });
7329
+ goalsByNativeThread.set(threadId, providerGoalFromCodex(paused.goal));
7330
+ }
7331
+ }).pipe(
7332
+ Effect.ensuring(
7333
+ turnTerminalizationPermit.withPermits(1)(
7334
+ Effect.gen(function* () {
7335
+ if (goalActivations.get(threadId) === activation) {
7336
+ goalActivations.delete(threadId);
7337
+ }
7338
+ if (goalsByNativeThread.get(threadId)?.status !== "active") {
7339
+ yield* releaseGoalHold(threadId);
7340
+ }
7341
+ }),
7342
+ ),
7343
+ ),
7344
+ );
7345
+ });
7346
+
7347
/**
7348
* Setting or resuming a goal starts the first goal turn with this run's
7349
* turn configuration (approvals, sandbox, model, plan mode), since a
@@ -7303,6 +7372,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7372
current === null ? "No goal is set." : describeCodexGoal(current),
7373
);
7374
}
7375
+ goalsPausedForWake.delete(threadId);
7376
if (command.type === "clear") {
7377
const { cleared } = yield* client.request("thread/goal/clear", { threadId });
7378
goalsByNativeThread.set(threadId, null);
@@ -7330,50 +7400,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7400
});
7401
goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
7402
}
7333
- // Hold fast first turns until activation; Stop cancels activation.
7334
- const activation = { stopped: false };
7335
- goalActivations.set(threadId, activation);
7336
- yield* Effect.gen(function* () {
7337
- // A bare objective gets echoed back, and "start this goal" gets a
7338
- // create_goal call that Codex rejects because the goal already exists.
7339
- yield* startNativeTurn(
7340
- turnInput,
7341
- command.type === "set"
7342
- ? yield* toCodexInput({
7343
- ...turnInput,
7344
- message: {
7345
- ...turnInput.message,
7346
- text: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${command.objective}`,
7347
- },
7348
- })
7349
- : [],
7350
- );
7351
- if (activation.stopped) return;
7352
- const { goal } = yield* client.request("thread/goal/set", {
7353
- threadId,
7354
- status: "active",
7355
- });
7356
- goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
7357
- if (activation.stopped) {
7358
- const paused = yield* client.request("thread/goal/set", {
7359
- threadId,
7360
- status: "paused",
7361
- });
7362
- goalsByNativeThread.set(threadId, providerGoalFromCodex(paused.goal));
7363
- }
7364
- }).pipe(
7365
- Effect.ensuring(
7366
- turnTerminalizationPermit.withPermits(1)(
7367
- Effect.gen(function* () {
7368
- if (goalActivations.get(threadId) === activation) {
7369
- goalActivations.delete(threadId);
7370
- }
7371
- if (goalsByNativeThread.get(threadId)?.status !== "active") {
7372
- yield* releaseGoalHold(threadId);
7373
- }
7374
- }),
7375
- ),
7376
- ),
7403
+ // A bare objective gets echoed back, and "start this goal" gets a
7404
+ // create_goal call that Codex rejects because the goal already exists.
7405
+ yield* activateGoal(
7406
+ turnInput,
7407
+ threadId,
7408
+ command.type === "set"
7409
+ ? toCodexInput({
7410
+ ...turnInput,
7411
+ message: {
7412
+ ...turnInput.message,
7413
+ text: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${command.objective}`,
7414
+ },
7415
+ })
7416
+ : Effect.succeed([]),
7417
);
7418
},
7419
(effect, turnInput) =>
@@ -7669,7 +7709,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7709
? parseGoalCommand(turnInput.message)
7710
: null;
7711
if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand);
7712
+ const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId;
7713
return Effect.gen(function* () {
7714
+ if (
7715
+ turnInput.restartContinuationOfRunId === undefined &&
7716
+ nativeThreadId != null &&
7717
+ goalsPausedForWake.has(nativeThreadId) &&
7718
+ goalsByNativeThread.get(nativeThreadId)?.status === "paused"
7719
+ ) {
7720
+ return yield* activateGoal(turnInput, nativeThreadId, toCodexInput(turnInput));
7721
+ }
7722
yield* startNativeTurn(
7723
turnInput,
7724
turnInput.restartContinuationOfRunId === undefined
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+40
@@ -17,6 +17,7 @@ import {
17
ProviderDriverKind,
18
ProviderInstanceId,
19
type ProviderSessionId,
20
+ RunId,
21
ThreadId,
22
} from "@t3tools/contracts";
23
import * as Cause from "effect/Cause";
@@ -2296,6 +2297,43 @@ it.effect("ProviderSessionManagerV2 fails a turn whose provider retry never resu
2297
}),
2298
);
2299
2300
+it("ProviderSessionManagerV2 counts a delegated task as a wake only while its result can be delivered", () => {
2301
+ const runId = RunId.make("run-delegating");
2302
+ const thread = { archivedAt: null, deletedAt: null };
2303
+ const task = {
2304
+ origin: "app_owned" as const,
2305
+ status: "running" as const,
2306
+ runId,
2307
+ completionDelivery: undefined,
2308
+ };
2309
+ const run = (disposition: "open" | "disposed") => ({
2310
+ id: runId,
2311
+ delegatedCompletion: { disposition, nextGeneration: 1, delivery: null },
2312
+ });
2313
+ assert.isTrue(
2314
+ ProviderSessionManager.delegatedTaskWillWake({
2315
+ thread,
2316
+ runs: [run("open")],
2317
+ subagents: [task],
2318
+ }),
2319
+ );
2320
+ // An interrupted completion wake disposes the cohort, so the result never wakes the thread.
2321
+ assert.isFalse(
2322
+ ProviderSessionManager.delegatedTaskWillWake({
2323
+ thread,
2324
+ runs: [run("disposed")],
2325
+ subagents: [task],
2326
+ }),
2327
+ );
2328
+ assert.isFalse(
2329
+ ProviderSessionManager.delegatedTaskWillWake({
2330
+ thread,
2331
+ runs: [run("open")],
2332
+ subagents: [{ ...task, origin: "provider_native" }],
2333
+ }),
2334
+ );
2335
+});
2336
+
2337
it.effect(
2338
"ProviderSessionManagerV2 issues MCP credentials before opening and revokes them on close",
2339
() =>
@@ -2341,6 +2379,8 @@ it.effect(
2379
new Set(["preview", "orchestration", "worktree", "pull-requests"]),
2380
);
2381
2382
+ assert.isFalse(yield* captured!.hasPendingWake!);
2383
+
2384
yield* manager.close(providerSessionId);
2385
assert.isUndefined(yield* mcpSessions.read(threadId));
2386
assert.isUndefined(yield* registry.resolve(token!));
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+36
-1
@@ -4,11 +4,14 @@ import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
4
import {
5
isOrchestrationV2WorkActive,
6
ModelSelection,
7
+ type OrchestrationV2AppThread,
8
OrchestrationV2DomainEvent,
9
OrchestrationV2ProviderSession,
10
type OrchestrationV2PromptSuggestion,
11
type OrchestrationV2ProviderThread,
12
+ type OrchestrationV2Run,
13
OrchestrationV2RuntimeRequest,
14
+ type OrchestrationV2Subagent,
15
ProviderInstanceId,
16
ProviderSessionId,
17
ThreadId,
@@ -86,6 +89,30 @@ const WORKING_RUN_STATUSES: ReadonlySet<string> = new Set([
89
"waiting",
90
]);
91
92
+/** Matches planDelegatedCompletionDelivery: true while a delegated task's result still wakes the thread. */
93
+export const delegatedTaskWillWake = (records: {
94
+ readonly thread: Pick<OrchestrationV2AppThread, "archivedAt" | "deletedAt">;
95
+ readonly runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "delegatedCompletion">>;
96
+ readonly subagents: ReadonlyArray<
97
+ Pick<OrchestrationV2Subagent, "origin" | "status" | "runId" | "completionDelivery">
98
+ >;
99
+}): boolean =>
100
+ records.thread.archivedAt === null &&
101
+ records.thread.deletedAt === null &&
102
+ records.subagents.some((task) => {
103
+ const run = records.runs.find((candidate) => candidate.id === task.runId);
104
+ const delivery = task.completionDelivery?.state;
105
+ return (
106
+ task.origin === "app_owned" &&
107
+ isOrchestrationV2WorkActive(task.status) &&
108
+ run !== undefined &&
109
+ (run.delegatedCompletion?.disposition ?? "open") === "open" &&
110
+ delivery !== "acknowledged" &&
111
+ delivery !== "delivered" &&
112
+ delivery !== "disposed"
113
+ );
114
+ });
115
+
116
export const ProviderSessionReleaseReason = Schema.Literals([
117
"idle_timeout",
118
"runtime_error",
@@ -551,7 +578,15 @@ export const layerWithOptions = (
578
capabilities,
579
subagent,
580
});
554
- yield* mcpSessions.set(credential.config);
581
+ yield* mcpSessions.set({
582
+ ...credential.config,
583
+ hasPendingWake: projectionStore
584
+ .getThreadRecords(threadId, ["runs", "subagents"])
585
+ .pipe(
586
+ Effect.map(delegatedTaskWillWake),
587
+ Effect.orElseSucceed(() => false),
588
+ ),
589
+ });
590
reserveMcpCredential(threadId, credential.config.providerSessionId);
591
return { mcpCredentialId: credential.config.providerSessionId, issued: true };
592
}),
packages/provider-core/src/server/mcpSession.ts
+3
@@ -1,4 +1,5 @@
1
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2
+import type * as Effect from "effect/Effect";
3
4
/**
5
* Sent by MCP clients that cannot defer tools themselves. The T3 MCP server then
@@ -17,6 +18,8 @@ export interface McpProviderSessionConfig {
18
readonly browserToolsAvailable: boolean;
19
readonly capabilities?: ReadonlySet<string>;
20
readonly agentDeviceEnvironment?: Readonly<Record<string, string>>;
21
+ /** True while a delegated task this thread started will wake it with its result. */
22
+ readonly hasPendingWake?: Effect.Effect<boolean>;
23
}
24
25
export function withAgentDeviceEnvironment(