The best way to control Claude Code, Codex and more from any computer or phone
fix(server): a Codex Stop that never completes offers Force stop (#36331)
Julius Marminge committed
Nov 13, 2026 at 13:03 UTC
b5b470542a5fb95aed16f3d3a23f8cd8de17e5d8
2 files changed
+390
-163
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+181
@@ -9523,6 +9523,187 @@ describe("CodexAdapterV2 post-settle continuation", () => {
9523
),
9524
);
9525
9526
+ it.effect.each([
9527
+ "Codex completes it later",
9528
+ "its thread is unloaded",
9529
+ "Codex completes it after the session's Stop deadline",
9530
+ "Codex completes it after a second Stop fails",
9531
+ ] as const)("keeps a turn open after an unconfirmed Stop until %s", (ending) =>
9532
+ Effect.gen(function* () {
9533
+ const nativeThreadId = "unconfirmed-stop-thread";
9534
+ const nativeTurnId = "unconfirmed-stop-turn";
9535
+ const usage = {
9536
+ totalTokens: 15,
9537
+ inputTokens: 10,
9538
+ cachedInputTokens: 2,
9539
+ outputTokens: 5,
9540
+ reasoningOutputTokens: 1,
9541
+ };
9542
+ const pastDeadline = ending === "Codex completes it after the session's Stop deadline";
9543
+ const harness = yield* makeCodexReplayHarness(
9544
+ makeCodexReplayTranscript({
9545
+ scenario: `unconfirmed-stop-${ending.length}`,
9546
+ entries: [
9547
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }),
9548
+ {
9549
+ type: "expect_outbound",
9550
+ label: "turn/interrupt",
9551
+ frame: {
9552
+ id: 4,
9553
+ method: "turn/interrupt",
9554
+ params: { threadId: nativeThreadId, turnId: nativeTurnId },
9555
+ },
9556
+ },
9557
+ {
9558
+ type: "emit_inbound",
9559
+ label: "still working",
9560
+ frame: {
9561
+ method: "thread/tokenUsage/updated",
9562
+ params: {
9563
+ threadId: nativeThreadId,
9564
+ turnId: nativeTurnId,
9565
+ tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 },
9566
+ },
9567
+ },
9568
+ },
9569
+ {
9570
+ type: "emit_inbound",
9571
+ label: "turn/interrupt",
9572
+ // A slow acknowledgement leaves the adapter's own wait running past the deadline.
9573
+ ...(pastDeadline ? { afterMs: 6_000 } : {}),
9574
+ frame: { id: 4, result: {} },
9575
+ },
9576
+ ...(ending === "its thread is unloaded"
9577
+ ? ([
9578
+ {
9579
+ type: "expect_outbound",
9580
+ label: "thread/unsubscribe",
9581
+ frame: {
9582
+ id: 5,
9583
+ method: "thread/unsubscribe",
9584
+ params: { threadId: nativeThreadId },
9585
+ },
9586
+ },
9587
+ {
9588
+ type: "emit_inbound",
9589
+ label: "thread/unsubscribe",
9590
+ frame: { id: 5, result: { status: "unsubscribed" } },
9591
+ },
9592
+ ] satisfies Array<CodexReplay.CodexAppServerReplayEntry>)
9593
+ : ([
9594
+ ...(ending === "Codex completes it after a second Stop fails"
9595
+ ? ([
9596
+ {
9597
+ type: "expect_outbound",
9598
+ label: "turn/interrupt/second",
9599
+ frame: {
9600
+ id: 5,
9601
+ method: "turn/interrupt",
9602
+ params: { threadId: nativeThreadId, turnId: nativeTurnId },
9603
+ },
9604
+ },
9605
+ {
9606
+ type: "emit_inbound",
9607
+ label: "turn/interrupt/second",
9608
+ frame: { id: 5, error: { code: -32603, message: "internal error" } },
9609
+ },
9610
+ ] satisfies Array<CodexReplay.CodexAppServerReplayEntry>)
9611
+ : []),
9612
+ {
9613
+ type: "emit_inbound",
9614
+ label: "turn/completed",
9615
+ afterMs: 20_000,
9616
+ frame: {
9617
+ method: "turn/completed",
9618
+ params: {
9619
+ threadId: nativeThreadId,
9620
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
9621
+ },
9622
+ },
9623
+ },
9624
+ ] satisfies Array<CodexReplay.CodexAppServerReplayEntry>)),
9625
+ ],
9626
+ }),
9627
+ );
9628
+ yield* harness.runtime.startTurn(
9629
+ makeCodexTestTurnInput({
9630
+ threadId: harness.threadId,
9631
+ providerThread: harness.providerThread,
9632
+ now: yield* DateTime.now,
9633
+ attemptId: RunAttemptId.make("attempt-unconfirmed-stop"),
9634
+ text: "work",
9635
+ }),
9636
+ );
9637
+ const stopping = yield* harness.runtime
9638
+ .interruptTurn({
9639
+ providerThread: harness.providerThread,
9640
+ providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
9641
+ driver: CodexAdapterV2.CODEX_DRIVER_KIND,
9642
+ nativeTurnId,
9643
+ }),
9644
+ })
9645
+ .pipe(
9646
+ // The session manager bounds every Stop the same way.
9647
+ Effect.timeoutOrElse({
9648
+ duration: "15 seconds",
9649
+ orElse: () => Effect.fail({ _tag: "SessionStopDeadline" } as const),
9650
+ }),
9651
+ Effect.result,
9652
+ Effect.forkScoped,
9653
+ );
9654
+ // Codex received the interrupt and kept reporting work on the turn.
9655
+ yield* harness.until(() =>
9656
+ harness.events.some(
9657
+ (event) =>
9658
+ event.type === "provider_turn.updated" &&
9659
+ event.providerTurn.tokenUsage?.usedTokens === usage.totalTokens,
9660
+ ),
9661
+ );
9662
+ yield* TestClock.adjust(pastDeadline ? "15 seconds" : "10 seconds");
9663
+
9664
+ const stopped = yield* Fiber.join(stopping);
9665
+ assert.equal(
9666
+ stopped._tag === "Failure" ? stopped.failure._tag : "confirmed",
9667
+ pastDeadline ? "SessionStopDeadline" : "ProviderAdapterInterruptTimeoutError",
9668
+ );
9669
+ assert.deepEqual(harness.terminalEvents(), []);
9670
+
9671
+ if (ending === "Codex completes it after a second Stop fails") {
9672
+ const second = yield* harness.runtime
9673
+ .interruptTurn({
9674
+ providerThread: harness.providerThread,
9675
+ providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
9676
+ driver: CodexAdapterV2.CODEX_DRIVER_KIND,
9677
+ nativeTurnId,
9678
+ }),
9679
+ })
9680
+ .pipe(Effect.result);
9681
+ assert.equal(second._tag, "Failure");
9682
+ assert.deepEqual(harness.terminalEvents(), []);
9683
+ }
9684
+ if (ending === "its thread is unloaded") {
9685
+ yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
9686
+ } else {
9687
+ yield* TestClock.adjust("20 seconds");
9688
+ }
9689
+ yield* harness.awaitTerminal(1);
9690
+ assert.deepEqual(
9691
+ harness.terminalEvents().map((event) => event.status),
9692
+ ["interrupted"],
9693
+ );
9694
+ }).pipe(
9695
+ Effect.scoped,
9696
+ Effect.provide(
9697
+ Layer.mergeAll(
9698
+ IdAllocator.layer,
9699
+ McpProviderSessions.layer,
9700
+ NodeServices.layer,
9701
+ NodeCrypto.layer,
9702
+ ),
9703
+ ),
9704
+ ),
9705
+ );
9706
+
9707
describe("native goals", () => {
9708
const nativeThreadId = "goal-thread";
9709
const objective = "Ship the feature";
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+209
-163
@@ -89,6 +89,7 @@ import * as Digest from "effect/crypto/Digest";
89
import * as DateTime from "effect/DateTime";
90
import * as Deferred from "effect/Deferred";
91
import * as Effect from "effect/Effect";
92
+import * as Exit from "effect/Exit";
93
import * as Fiber from "effect/Fiber";
94
import * as FileSystem from "effect/FileSystem";
95
import * as Function from "effect/Function";
@@ -159,6 +160,8 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"
160
161
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
162
const CODEX_CAPACITY_MAX_RETRIES = 5;
163
+// How long Stop waits for Codex to end the turn before the user is offered Force stop.
164
+const CODEX_STOP_CONFIRM_TIMEOUT_MS = 10_000;
165
// Codex can announce a retry and never resume. Recovered retries resume model output within ~75s.
166
const CODEX_PROVIDER_RETRY_STALL_TIMEOUT = "10 minutes";
167
export const CODEX_DRIVER_KIND = CODEX_PROVIDER;
@@ -7896,13 +7899,30 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7899
// unarchives it on the next turn.
7900
if (unloadInput.archive === true) {
7901
yield* client.request("thread/archive", { threadId: nativeThreadId });
7899
- return;
7902
+ } else {
7903
+ // A resume may already wait on the pending entry; replacing it would strand that wait.
7904
+ if (!threadClosings.has(nativeThreadId)) {
7905
+ threadClosings.set(nativeThreadId, yield* Deferred.make<void>());
7906
+ }
7907
+ yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
7908
}
7901
- // A resume may already wait on the pending entry; replacing it would strand that wait.
7902
- if (!threadClosings.has(nativeThreadId)) {
7903
- threadClosings.set(nativeThreadId, yield* Deferred.make<void>());
7909
+ // No turn/completed arrives for an unloaded thread, so a Stop Codex never
7910
+ // confirmed would otherwise keep its turn open for the life of the session.
7911
+ const interrupting = yield* Ref.get(interruptingNativeTurns);
7912
+ const completedAt = yield* DateTime.now;
7913
+ for (const context of (yield* Ref.get(activeTurns)).values()) {
7914
+ if (
7915
+ context.providerThread.id !== unloadInput.providerThread.id ||
7916
+ !interrupting.has(context.nativeTurnId)
7917
+ )
7918
+ continue;
7919
+ yield* finalizeCodexTurn({
7920
+ context,
7921
+ nativeTurnId: context.nativeTurnId,
7922
+ status: "interrupted",
7923
+ completedAt,
7924
+ });
7925
}
7905
- yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
7926
},
7927
(effect, unloadInput) =>
7928
effect.pipe(
@@ -7990,23 +8010,30 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8010
readonly context: ActiveCodexTurnContext;
8011
readonly completion: Deferred.Deferred<void, never>;
8012
}> = [];
8013
+ const trackedInterruptNativeTurnIds = new Set<string>();
8014
+ let joinedPendingStop = false;
8015
+ // Untraced: runs once per lineage turn inside the interruptTurn span.
8016
+ const trackInterruptTarget = Effect.fnUntraced(function* (
8017
+ context: ActiveCodexTurnContext,
8018
+ ) {
8019
+ const fresh = yield* Deferred.make<void>();
8020
+ // An earlier Stop may still wait on this turn; replacing its waiter would strand it.
8021
+ const completion = yield* Ref.modify(turnWaiters, (current) => {
8022
+ const pending = current.get(context.nativeTurnId);
8023
+ return pending === undefined
8024
+ ? [fresh, new Map(current).set(context.nativeTurnId, fresh)]
8025
+ : [pending, current];
8026
+ });
8027
+ joinedPendingStop ||= completion !== fresh;
8028
+ yield* Ref.update(interruptingNativeTurns, (current) =>
8029
+ new Set(current).add(context.nativeTurnId),
8030
+ );
8031
+ interruptTargets.push({ context, completion });
8032
+ trackedInterruptNativeTurnIds.add(context.nativeTurnId);
8033
+ });
8034
for (const context of interruptTargetContexts) {
7994
- interruptTargets.push({ context, completion: yield* Deferred.make<void>() });
8035
+ yield* trackInterruptTarget(context);
8036
}
7996
- yield* Ref.update(turnWaiters, (current) => {
7997
- const updated = new Map(current);
7998
- for (const target of interruptTargets) {
7999
- updated.set(target.context.nativeTurnId, target.completion);
8000
- }
8001
- return updated;
8002
- });
8003
- yield* Ref.update(interruptingNativeTurns, (current) => {
8004
- const updated = new Set(current);
8005
- for (const target of interruptTargets) {
8006
- updated.add(target.context.nativeTurnId);
8007
- }
8008
- return updated;
8009
- });
8037
const registeredActiveTurns = yield* Ref.get(activeTurns);
8038
for (const target of interruptTargets) {
8039
if (registeredActiveTurns.get(target.context.nativeTurnId) !== target.context) {
@@ -8039,9 +8066,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8066
});
8067
});
8068
8042
- const trackedInterruptNativeTurnIds = new Set(
8043
- interruptTargets.map((target) => target.context.nativeTurnId),
8044
- );
8069
const finalizeRemainingInterruptLineage = Effect.gen(function* () {
8070
while (true) {
8071
const newlyDiscovered: Array<ActiveCodexTurnContext> = [];
@@ -8054,20 +8078,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8078
if (trackedInterruptNativeTurnIds.has(context.nativeTurnId)) {
8079
continue;
8080
}
8057
- const completion = yield* Deferred.make<void>();
8058
- interruptTargets.push({ context, completion });
8059
- trackedInterruptNativeTurnIds.add(context.nativeTurnId);
8081
+ yield* trackInterruptTarget(context);
8082
newlyDiscovered.push(context);
8061
- yield* Ref.update(turnWaiters, (current) => {
8062
- const updated = new Map(current);
8063
- updated.set(context.nativeTurnId, completion);
8064
- return updated;
8065
- });
8066
- yield* Ref.update(interruptingNativeTurns, (current) => {
8067
- const updated = new Set(current);
8068
- updated.add(context.nativeTurnId);
8069
- return updated;
8070
- });
8083
}
8084
return lineage;
8085
}),
@@ -8130,19 +8142,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8142
!trackedInterruptNativeTurnIds.has(context.nativeTurnId),
8143
);
8144
for (const context of lineage) {
8133
- const completion = yield* Deferred.make<void>();
8134
- interruptTargets.push({ context, completion });
8135
- trackedInterruptNativeTurnIds.add(context.nativeTurnId);
8136
- yield* Ref.update(turnWaiters, (current) => {
8137
- const updated = new Map(current);
8138
- updated.set(context.nativeTurnId, completion);
8139
- return updated;
8140
- });
8141
- yield* Ref.update(interruptingNativeTurns, (current) => {
8142
- const updated = new Set(current);
8143
- updated.add(context.nativeTurnId);
8144
- return updated;
8145
- });
8145
+ yield* trackInterruptTarget(context);
8146
}
8147
return lineage;
8148
}),
@@ -8169,114 +8169,55 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8169
}
8170
});
8171
8172
- yield* Effect.gen(function* () {
8173
- for (const target of interruptTargets) {
8174
- const context = target.context;
8175
- if (context.capacityRetryPending !== undefined) {
8176
- yield* finalizeCodexTurn({
8177
- context,
8178
- nativeTurnId: context.nativeTurnId,
8179
- status: "interrupted",
8180
- completedAt: yield* DateTime.now,
8181
- });
8182
- continue;
8183
- }
8184
- // Null start timestamps ACK queued turns; interruption must wait for turn/started.
8185
- if (context.nativeStartReady !== undefined) {
8186
- const ready = yield* Deferred.await(context.nativeStartReady).pipe(
8187
- Effect.timeoutOption("10 seconds"),
8188
- );
8189
- if (Option.isNone(ready)) {
8190
- return yield* toProtocolError(
8191
- "Codex did not start the queued turn within 10 seconds; Stop could not be delivered.",
8192
- );
8193
- }
8194
- }
8195
- if ((yield* Ref.get(activeTurns)).get(context.nativeTurnId) !== context) {
8196
- continue;
8197
- }
8198
- yield* client.request("turn/interrupt", {
8199
- threadId: yield* getNativeThreadId(context.providerThread),
8200
- turnId: context.nativeTurnId,
8201
- });
8202
- }
8203
- const containedTerminalKeys = new Set<string>();
8204
- const attemptedTerminalKeys = new Set<string>();
8205
- const collectTrackedTerminals = Effect.fn("CodexAdapterV2.collectTrackedTerminals")(
8206
- function* (targets: typeof interruptTargets) {
8207
- const trackedTerminals = new Map<
8208
- string,
8209
- { readonly nativeThreadId: string; readonly processId: string }
8210
- >();
8211
- const runningItems = yield* Ref.get(runningCommandItemsByTurn);
8212
- for (const target of targets) {
8213
- const nativeThreadId = yield* getNativeThreadId(
8214
- target.context.providerThread,
8215
- );
8216
- const items = runningItems.get(target.context.nativeTurnId);
8217
- for (const item of items?.values() ?? []) {
8218
- if (item.processId !== undefined) {
8219
- trackedTerminals.set(`${nativeThreadId}:${item.processId}`, {
8220
- nativeThreadId,
8221
- processId: item.processId,
8222
- });
8223
- }
8172
+ const containedTerminalKeys = new Set<string>();
8173
+ const attemptedTerminalKeys = new Set<string>();
8174
+ const collectTrackedTerminals = Effect.fn("CodexAdapterV2.collectTrackedTerminals")(
8175
+ function* (targets: typeof interruptTargets) {
8176
+ const trackedTerminals = new Map<
8177
+ string,
8178
+ { readonly nativeThreadId: string; readonly processId: string }
8179
+ >();
8180
+ const runningItems = yield* Ref.get(runningCommandItemsByTurn);
8181
+ for (const target of targets) {
8182
+ const nativeThreadId = yield* getNativeThreadId(target.context.providerThread);
8183
+ const items = runningItems.get(target.context.nativeTurnId);
8184
+ for (const item of items?.values() ?? []) {
8185
+ if (item.processId !== undefined) {
8186
+ trackedTerminals.set(`${nativeThreadId}:${item.processId}`, {
8187
+ nativeThreadId,
8188
+ processId: item.processId,
8189
+ });
8190
}
8191
}
8226
- return trackedTerminals;
8227
- },
8228
- );
8229
- const terminateTrackedTerminals = Effect.fn(
8230
- "CodexAdapterV2.terminateTrackedTerminals",
8231
- )(function* (targets: typeof interruptTargets) {
8232
- const trackedTerminals = yield* collectTrackedTerminals(targets);
8233
- const pendingTerminals = Array.from(trackedTerminals.entries())
8234
- .filter(([key]) => !containedTerminalKeys.has(key))
8235
- .sort(
8236
- ([leftKey], [rightKey]) =>
8237
- Number(attemptedTerminalKeys.has(leftKey)) -
8238
- Number(attemptedTerminalKeys.has(rightKey)),
8239
- );
8240
- return yield* Effect.forEach(
8241
- pendingTerminals,
8242
- ([key, { nativeThreadId, processId }]) =>
8243
- Effect.gen(function* () {
8244
- attemptedTerminalKeys.add(key);
8245
- yield* terminateBackgroundTerminal(nativeThreadId, processId);
8246
- containedTerminalKeys.add(key);
8247
- }).pipe(
8248
- Effect.as({ success: true as const }),
8249
- Effect.catch((error) => Effect.succeed({ success: false as const, error })),
8250
- ),
8192
+ }
8193
+ return trackedTerminals;
8194
+ },
8195
+ );
8196
+ const terminateTrackedTerminals = Effect.fn(
8197
+ "CodexAdapterV2.terminateTrackedTerminals",
8198
+ )(function* (targets: typeof interruptTargets) {
8199
+ const trackedTerminals = yield* collectTrackedTerminals(targets);
8200
+ const pendingTerminals = Array.from(trackedTerminals.entries())
8201
+ .filter(([key]) => !containedTerminalKeys.has(key))
8202
+ .sort(
8203
+ ([leftKey], [rightKey]) =>
8204
+ Number(attemptedTerminalKeys.has(leftKey)) -
8205
+ Number(attemptedTerminalKeys.has(rightKey)),
8206
);
8252
- });
8253
-
8254
- const [, completed] = yield* Effect.all(
8255
- [
8256
- terminateTrackedTerminals(interruptTargets),
8257
- Effect.forEach(
8258
- interruptTargets,
8259
- (target) => Deferred.await(target.completion),
8260
- { concurrency: "unbounded", discard: true },
8261
- ).pipe(Effect.timeoutOption("10 seconds")),
8262
- ],
8263
- { concurrency: "unbounded" },
8207
+ return yield* Effect.forEach(
8208
+ pendingTerminals,
8209
+ ([key, { nativeThreadId, processId }]) =>
8210
+ Effect.gen(function* () {
8211
+ attemptedTerminalKeys.add(key);
8212
+ yield* terminateBackgroundTerminal(nativeThreadId, processId);
8213
+ containedTerminalKeys.add(key);
8214
+ }).pipe(
8215
+ Effect.as({ success: true as const }),
8216
+ Effect.catch((error) => Effect.succeed({ success: false as const, error })),
8217
+ ),
8218
);
8265
- if (Option.isNone(completed)) {
8266
- for (const target of interruptTargets) {
8267
- const context = target.context;
8268
- if ((yield* Ref.get(activeTurns)).get(context.nativeTurnId) !== context) {
8269
- continue;
8270
- }
8271
- yield* Effect.logWarning("orchestration-v2.codex-interrupt-timeout", {
8272
- providerSessionId: input.providerSessionId,
8273
- providerThreadId: context.providerThread.id,
8274
- providerTurnId: context.providerTurnId,
8275
- nativeTurnId: context.nativeTurnId,
8276
- });
8277
- }
8278
- }
8279
-
8219
+ });
8220
+ const settleInterruptedLineage = Effect.gen(function* () {
8221
yield* interruptLateDescendants;
8222
yield* finalizeRemainingInterruptLineage;
8223
@@ -8316,10 +8257,114 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8257
}
8258
}),
8259
);
8260
+ });
8261
+ // Codex may still be working, so a root stays open and marked interrupting.
8262
+ // Whatever ends it later (Codex, Force stop) settles the rest of this Stop.
8263
+ const deferToActiveRoots = Effect.gen(function* () {
8264
+ const registered = yield* Ref.get(activeTurns);
8265
+ const roots = interruptTargets.filter(
8266
+ ({ context }) =>
8267
+ lineageRoots.includes(context) &&
8268
+ registered.get(context.nativeTurnId) === context,
8269
+ );
8270
+ if (roots.length === 0) return false;
8271
+ for (const { context } of roots) {
8272
+ yield* Effect.logWarning("orchestration-v2.codex-interrupt-timeout", {
8273
+ providerSessionId: input.providerSessionId,
8274
+ providerThreadId: context.providerThread.id,
8275
+ providerTurnId: context.providerTurnId,
8276
+ nativeTurnId: context.nativeTurnId,
8277
+ });
8278
+ }
8279
+ yield* Effect.forEach(roots, (target) => Deferred.await(target.completion), {
8280
+ concurrency: "unbounded",
8281
+ discard: true,
8282
+ }).pipe(
8283
+ Effect.andThen(settleInterruptedLineage),
8284
+ Effect.catchCause((cause) =>
8285
+ Cause.hasInterruptsOnly(cause)
8286
+ ? Effect.void
8287
+ : Effect.logWarning("orchestration-v2.codex-late-stop-settle-failed", {
8288
+ providerSessionId: input.providerSessionId,
8289
+ cause,
8290
+ }),
8291
+ ),
8292
+ Effect.ensuring(cleanupInterruptState),
8293
+ Effect.forkIn(scope),
8294
+ );
8295
+ return true;
8296
+ });
8297
+
8298
+ const unconfirmed = yield* Effect.gen(function* () {
8299
+ for (const target of interruptTargets) {
8300
+ const context = target.context;
8301
+ if (context.capacityRetryPending !== undefined) {
8302
+ yield* finalizeCodexTurn({
8303
+ context,
8304
+ nativeTurnId: context.nativeTurnId,
8305
+ status: "interrupted",
8306
+ completedAt: yield* DateTime.now,
8307
+ });
8308
+ continue;
8309
+ }
8310
+ // Null start timestamps ACK queued turns; interruption must wait for turn/started.
8311
+ if (context.nativeStartReady !== undefined) {
8312
+ const ready = yield* Deferred.await(context.nativeStartReady).pipe(
8313
+ Effect.timeoutOption("10 seconds"),
8314
+ );
8315
+ if (Option.isNone(ready)) {
8316
+ return yield* toProtocolError(
8317
+ "Codex did not start the queued turn within 10 seconds; Stop could not be delivered.",
8318
+ );
8319
+ }
8320
+ }
8321
+ if ((yield* Ref.get(activeTurns)).get(context.nativeTurnId) !== context) {
8322
+ continue;
8323
+ }
8324
+ yield* client.request("turn/interrupt", {
8325
+ threadId: yield* getNativeThreadId(context.providerThread),
8326
+ turnId: context.nativeTurnId,
8327
+ });
8328
+ }
8329
+ const [, completed] = yield* Effect.all(
8330
+ [
8331
+ terminateTrackedTerminals(interruptTargets),
8332
+ Effect.forEach(
8333
+ interruptTargets,
8334
+ (target) => Deferred.await(target.completion),
8335
+ { concurrency: "unbounded", discard: true },
8336
+ ).pipe(Effect.timeoutOption(CODEX_STOP_CONFIRM_TIMEOUT_MS)),
8337
+ ],
8338
+ { concurrency: "unbounded" },
8339
+ );
8340
+ if (Option.isSome(completed) || !(yield* deferToActiveRoots)) {
8341
+ yield* settleInterruptedLineage;
8342
+ return false;
8343
+ }
8344
+ return true;
8345
}).pipe(
8320
- Effect.onError(() => finalizeRemainingInterruptLineage),
8321
- Effect.ensuring(cleanupInterruptState),
8346
+ Effect.onExit((exit) => {
8347
+ if (Exit.isSuccess(exit)) return exit.value ? Effect.void : cleanupInterruptState;
8348
+ const abandon = finalizeRemainingInterruptLineage.pipe(
8349
+ Effect.ensuring(cleanupInterruptState),
8350
+ );
8351
+ // Neither a caller's deadline nor a failed retry of a pending Stop confirms
8352
+ // that the turn ended.
8353
+ return Cause.hasInterruptsOnly(exit.cause) || joinedPendingStop
8354
+ ? Effect.flatMap(deferToActiveRoots, (deferred) =>
8355
+ deferred ? Effect.void : abandon,
8356
+ )
8357
+ : abandon;
8358
+ }),
8359
);
8360
+ if (unconfirmed) {
8361
+ return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({
8362
+ driver: CODEX_PROVIDER,
8363
+ providerThreadId: turnInput.providerThread.id,
8364
+ providerTurnId: turnInput.providerTurnId,
8365
+ timeoutMs: CODEX_STOP_CONFIRM_TIMEOUT_MS,
8366
+ });
8367
+ }
8368
},
8369
(effect, requestedInput) =>
8370
Effect.acquireUseRelease(
@@ -8338,14 +8383,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8383
else goalStops.delete(nativeThreadId);
8384
}),
8385
).pipe(
8341
- Effect.mapError(
8342
- (cause) =>
8343
- new ProviderAdapter.ProviderAdapterInterruptError({
8344
- driver: CODEX_PROVIDER,
8345
- providerThreadId: requestedInput.providerThread.id,
8346
- providerTurnId: requestedInput.providerTurnId,
8347
- cause,
8348
- }),
8386
+ Effect.mapError((cause) =>
8387
+ cause._tag === "ProviderAdapterInterruptTimeoutError"
8388
+ ? cause
8389
+ : new ProviderAdapter.ProviderAdapterInterruptError({
8390
+ driver: CODEX_PROVIDER,
8391
+ providerThreadId: requestedInput.providerThread.id,
8392
+ providerTurnId: requestedInput.providerTurnId,
8393
+ cause,
8394
+ }),
8395
),
8396
),
8397
),