Skip to content

Commit e8f46d3

Browse files
fix(server): Codex goals wait for a delegated task instead of re-prompting
Codex continues an active goal as soon as a goal turn completes, and the adapter ran every continuation for the 5 s grace window with no check for a T3 delegated task that will wake the thread. A parent waiting on an async delegate_task child kept starting turns that only reported the child was still running, spending goal tokens until it finished. When a delegated task will still wake the thread, the goal hold now pauses the goal at once and settles the run. The next ordinary turn (the child's wake or a user message) re-activates the goal through the same path as /goal resume. The wake check is the hasPendingWake session field shared with the Claude fix, counted only while the task's result can be delivered. Fixes #26857 AI-assisted; verified with the tests and tools listed above.
1 parent 31a108c commit e8f46d3

5 files changed

Lines changed: 262 additions & 50 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9882,6 +9882,104 @@ describe("CodexAdapterV2 post-settle continuation", () => {
98829882
),
98839883
);
98849884

9885+
it.effect("pauses a goal at once while a delegated task will wake the thread", () =>
9886+
Effect.gen(function* () {
9887+
const turnStart = (id: number, text: string) =>
9888+
Effect.map(
9889+
CodexAdapterV2.buildCodexTurnStartParams({
9890+
nativeThreadId,
9891+
codexInput: [{ type: "text", text }],
9892+
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
9893+
modelSelection: CODEX_TEST_MODEL_SELECTION,
9894+
hasT3Mcp: true,
9895+
}),
9896+
(params): CodexReplay.CodexAppServerReplayEntry => ({
9897+
type: "expect_outbound",
9898+
label: "turn/start",
9899+
frame: { id, method: "turn/start", params },
9900+
}),
9901+
);
9902+
const transcript = makeCodexReplayTranscript({
9903+
scenario: "goal-paused-for-wake",
9904+
entries: [
9905+
...sessionStart,
9906+
yield* turnStart(3, "Delegate and wait"),
9907+
...withReplayRequestId(
9908+
codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt: "" }).slice(
9909+
6,
9910+
),
9911+
3,
9912+
),
9913+
notification("goal active", "thread/goal/updated", {
9914+
threadId: nativeThreadId,
9915+
turnId: "goal-turn",
9916+
goal: codexGoal("active", 10),
9917+
}),
9918+
notification("turn done", "turn/completed", {
9919+
threadId: nativeThreadId,
9920+
turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
9921+
}),
9922+
...request(
9923+
4,
9924+
"thread/goal/set",
9925+
{ threadId: nativeThreadId, status: "paused" },
9926+
{ goal: codexGoal("paused", 10) },
9927+
),
9928+
yield* turnStart(5, "Child finished"),
9929+
...withReplayRequestId(
9930+
codexReplayPreamble({ nativeThreadId, nativeTurnId: "wake-turn", prompt: "" }).slice(
9931+
6,
9932+
),
9933+
5,
9934+
),
9935+
...request(
9936+
6,
9937+
"thread/goal/set",
9938+
{ threadId: nativeThreadId, status: "active" },
9939+
{ goal: codexGoal("active", 10) },
9940+
),
9941+
notification("goal resumed", "thread/goal/updated", {
9942+
threadId: nativeThreadId,
9943+
turnId: "wake-turn",
9944+
goal: codexGoal("active", 10),
9945+
}),
9946+
],
9947+
});
9948+
const harness = yield* makeCodexReplayHarness(transcript);
9949+
yield* (yield* McpProviderSessions.McpProviderSessions).set({
9950+
environmentId: EnvironmentId.make("test"),
9951+
threadId: harness.threadId,
9952+
providerSessionId: "wake-session",
9953+
providerInstanceId: ProviderInstanceId.make("codex"),
9954+
endpoint: "http://127.0.0.1:43123/mcp",
9955+
authorizationHeader: "Bearer test",
9956+
browserToolsAvailable: true,
9957+
hasPendingWake: Effect.succeed(true),
9958+
});
9959+
yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "Delegate and wait"));
9960+
// Settles without waiting out the continuation grace.
9961+
yield* harness.firstTerminal;
9962+
assert.deepEqual(providerGoals(harness.events), ["active", "paused"]);
9963+
assert.deepEqual(
9964+
harness.terminalEvents().map((event) => event.status),
9965+
["completed"],
9966+
);
9967+
9968+
yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "Child finished"));
9969+
yield* harness.until(() => providerGoals(harness.events).at(-1) === "active");
9970+
}).pipe(
9971+
Effect.scoped,
9972+
Effect.provide(
9973+
Layer.mergeAll(
9974+
IdAllocator.layer,
9975+
McpProviderSessions.layer,
9976+
NodeServices.layer,
9977+
NodeCrypto.layer,
9978+
),
9979+
),
9980+
),
9981+
);
9982+
98859983
it.effect("stops a turn Codex starts while the expiry pause is in flight", () =>
98869984
Effect.gen(function* () {
98879985
const prompt = "Keep going";

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts‎

Lines changed: 85 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2045,6 +2045,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
20452045
const goalActivations = new Map<string, { stopped: boolean }>();
20462046
// Held runs must not complete while Stop resolves its target.
20472047
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>();
20482050
const latestRunTurnId = (providerTurnId: ProviderTurnId) =>
20492051
continuedRuns.get(providerTurnId)?.at(-1)?.providerTurnId ?? providerTurnId;
20502052
const isContinuedRunDescendant = (
@@ -6257,8 +6259,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
62576259
completedTurn: input.goalHoldTurn,
62586260
next: yield* Deferred.make<ActiveCodexTurnContext | undefined>(),
62596261
});
6260-
yield* Effect.sleep(CODEX_GOAL_CONTINUATION_GRACE).pipe(
6261-
Effect.andThen(pauseUncontinuedGoal(nativeThreadId, event)),
6262+
const hasPendingWake = (yield* mcpSessions.read(input.context.input.threadId))
6263+
?.hasPendingWake;
6264+
// A continuation turn would only report that the delegated task is still running.
6265+
yield* (hasPendingWake ?? Effect.succeed(false)).pipe(
6266+
Effect.tap((waitsForWake) =>
6267+
waitsForWake ? Effect.void : Effect.sleep(CODEX_GOAL_CONTINUATION_GRACE),
6268+
),
6269+
Effect.flatMap((waitsForWake) =>
6270+
pauseUncontinuedGoal(nativeThreadId, event, waitsForWake),
6271+
),
62626272
Effect.andThen(
62636273
turnTerminalizationPermit.withPermits(1)(releaseGoalHold(nativeThreadId, event)),
62646274
),
@@ -6276,6 +6286,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
62766286
const pauseUncontinuedGoal = Effect.fnUntraced(function* (
62776287
nativeThreadId: string,
62786288
expected: CodexRootTerminalEvent,
6289+
waitsForWake: boolean,
62796290
) {
62806291
const hold = goalHolds.get(nativeThreadId);
62816292
if (
@@ -6288,16 +6299,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
62886299
goalHolds.delete(nativeThreadId);
62896300
// Keeps a turn Codex starts before settlement an orphan once the goal reads paused.
62906301
goalStops.set(nativeThreadId, (goalStops.get(nativeThreadId) ?? 0) + 1);
6291-
yield* Effect.logWarning("orchestration-v2.codex-goal-continuation-expired", {
6292-
nativeThreadId,
6293-
});
6302+
if (!waitsForWake) {
6303+
yield* Effect.logWarning("orchestration-v2.codex-goal-continuation-expired", {
6304+
nativeThreadId,
6305+
});
6306+
}
62946307
yield* client
62956308
.request("thread/goal/set", { threadId: nativeThreadId, status: "paused" })
62966309
.pipe(
62976310
// The hold is already claimed, so an unanswered pause must not keep the run open.
62986311
Effect.timeout("10 seconds"),
62996312
Effect.flatMap(({ goal }) => {
63006313
goalsByNativeThread.set(nativeThreadId, providerGoalFromCodex(goal));
6314+
if (waitsForWake && goal.status === "paused")
6315+
goalsPausedForWake.add(nativeThreadId);
63016316
return emitGoalUpdate(nativeThreadId);
63026317
}),
63036318
Effect.catch((cause) =>
@@ -7247,6 +7262,47 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
72477262
),
72487263
);
72497264

7265+
/** Starts a turn and then activates its paused goal; Stop cancels activation. */
7266+
const activateGoal = Effect.fnUntraced(function* (
7267+
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
7268+
threadId: string,
7269+
codexInput: ReturnType<typeof toCodexInput>,
7270+
) {
7271+
goalsPausedForWake.delete(threadId);
7272+
// Hold fast first turns until activation.
7273+
const activation = { stopped: false };
7274+
goalActivations.set(threadId, activation);
7275+
yield* Effect.gen(function* () {
7276+
yield* startNativeTurn(turnInput, yield* codexInput);
7277+
if (activation.stopped) return;
7278+
const { goal } = yield* client.request("thread/goal/set", {
7279+
threadId,
7280+
status: "active",
7281+
});
7282+
goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
7283+
if (activation.stopped) {
7284+
const paused = yield* client.request("thread/goal/set", {
7285+
threadId,
7286+
status: "paused",
7287+
});
7288+
goalsByNativeThread.set(threadId, providerGoalFromCodex(paused.goal));
7289+
}
7290+
}).pipe(
7291+
Effect.ensuring(
7292+
turnTerminalizationPermit.withPermits(1)(
7293+
Effect.gen(function* () {
7294+
if (goalActivations.get(threadId) === activation) {
7295+
goalActivations.delete(threadId);
7296+
}
7297+
if (goalsByNativeThread.get(threadId)?.status !== "active") {
7298+
yield* releaseGoalHold(threadId);
7299+
}
7300+
}),
7301+
),
7302+
),
7303+
);
7304+
});
7305+
72507306
/**
72517307
* Setting or resuming a goal starts the first goal turn with this run's
72527308
* turn configuration (approvals, sandbox, model, plan mode), since a
@@ -7260,6 +7316,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
72607316
if (command.type === "set") yield* validateCodexGoalObjective(command.objective);
72617317
const threadId = yield* getNativeThreadId(turnInput.providerThread);
72627318
rootProviderThreads.set(threadId, turnInput.providerThread);
7319+
goalsPausedForWake.delete(threadId);
72637320
const readGoal = client
72647321
.request("thread/goal/get", { threadId })
72657322
.pipe(
@@ -7302,50 +7359,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
73027359
});
73037360
goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
73047361
}
7305-
// Hold fast first turns until activation; Stop cancels activation.
7306-
const activation = { stopped: false };
7307-
goalActivations.set(threadId, activation);
7308-
yield* Effect.gen(function* () {
7309-
// A bare objective gets echoed back, and "start this goal" gets a
7310-
// create_goal call that Codex rejects because the goal already exists.
7311-
yield* startNativeTurn(
7312-
turnInput,
7313-
command.type === "set"
7314-
? yield* toCodexInput({
7315-
...turnInput,
7316-
message: {
7317-
...turnInput.message,
7318-
text: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${command.objective}`,
7319-
},
7320-
})
7321-
: [],
7322-
);
7323-
if (activation.stopped) return;
7324-
const { goal } = yield* client.request("thread/goal/set", {
7325-
threadId,
7326-
status: "active",
7327-
});
7328-
goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
7329-
if (activation.stopped) {
7330-
const paused = yield* client.request("thread/goal/set", {
7331-
threadId,
7332-
status: "paused",
7333-
});
7334-
goalsByNativeThread.set(threadId, providerGoalFromCodex(paused.goal));
7335-
}
7336-
}).pipe(
7337-
Effect.ensuring(
7338-
turnTerminalizationPermit.withPermits(1)(
7339-
Effect.gen(function* () {
7340-
if (goalActivations.get(threadId) === activation) {
7341-
goalActivations.delete(threadId);
7342-
}
7343-
if (goalsByNativeThread.get(threadId)?.status !== "active") {
7344-
yield* releaseGoalHold(threadId);
7345-
}
7346-
}),
7347-
),
7348-
),
7362+
// A bare objective gets echoed back, and "start this goal" gets a
7363+
// create_goal call that Codex rejects because the goal already exists.
7364+
yield* activateGoal(
7365+
turnInput,
7366+
threadId,
7367+
command.type === "set"
7368+
? toCodexInput({
7369+
...turnInput,
7370+
message: {
7371+
...turnInput.message,
7372+
text: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${command.objective}`,
7373+
},
7374+
})
7375+
: Effect.succeed([]),
73497376
);
73507377
},
73517378
(effect, turnInput) =>
@@ -7641,7 +7668,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
76417668
? parseGoalCommand(turnInput.message)
76427669
: null;
76437670
if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand);
7671+
const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId;
76447672
return Effect.gen(function* () {
7673+
if (
7674+
turnInput.restartContinuationOfRunId === undefined &&
7675+
nativeThreadId != null &&
7676+
goalsPausedForWake.has(nativeThreadId) &&
7677+
goalsByNativeThread.get(nativeThreadId)?.status === "paused"
7678+
) {
7679+
return yield* activateGoal(turnInput, nativeThreadId, toCodexInput(turnInput));
7680+
}
76457681
yield* startNativeTurn(
76467682
turnInput,
76477683
turnInput.restartContinuationOfRunId === undefined

‎apps/server/src/orchestration-v2/ProviderSessionManager.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
ProviderDriverKind,
1818
ProviderInstanceId,
1919
type ProviderSessionId,
20+
RunId,
2021
ThreadId,
2122
} from "@t3tools/contracts";
2223
import * as Cause from "effect/Cause";
@@ -2277,6 +2278,43 @@ it.effect("ProviderSessionManagerV2 fails a turn whose provider retry never resu
22772278
}),
22782279
);
22792280

2281+
it("ProviderSessionManagerV2 counts a delegated task as a wake only while its result can be delivered", () => {
2282+
const runId = RunId.make("run-delegating");
2283+
const thread = { archivedAt: null, deletedAt: null };
2284+
const task = {
2285+
origin: "app_owned" as const,
2286+
status: "running" as const,
2287+
runId,
2288+
completionDelivery: undefined,
2289+
};
2290+
const run = (disposition: "open" | "disposed") => ({
2291+
id: runId,
2292+
delegatedCompletion: { disposition, nextGeneration: 1, delivery: null },
2293+
});
2294+
assert.isTrue(
2295+
ProviderSessionManager.delegatedTaskWillWake({
2296+
thread,
2297+
runs: [run("open")],
2298+
subagents: [task],
2299+
}),
2300+
);
2301+
// An interrupted completion wake disposes the cohort, so the result never wakes the thread.
2302+
assert.isFalse(
2303+
ProviderSessionManager.delegatedTaskWillWake({
2304+
thread,
2305+
runs: [run("disposed")],
2306+
subagents: [task],
2307+
}),
2308+
);
2309+
assert.isFalse(
2310+
ProviderSessionManager.delegatedTaskWillWake({
2311+
thread,
2312+
runs: [run("open")],
2313+
subagents: [{ ...task, origin: "provider_native" }],
2314+
}),
2315+
);
2316+
});
2317+
22802318
it.effect(
22812319
"ProviderSessionManagerV2 issues MCP credentials before opening and revokes them on close",
22822320
() =>
@@ -2322,6 +2360,8 @@ it.effect(
23222360
new Set(["preview", "orchestration", "worktree", "pull-requests"]),
23232361
);
23242362

2363+
assert.isFalse(yield* captured!.hasPendingWake!);
2364+
23252365
yield* manager.close(providerSessionId);
23262366
assert.isUndefined(yield* mcpSessions.read(threadId));
23272367
assert.isUndefined(yield* registry.resolve(token!));

0 commit comments

Comments
 (0)