Skip to content

Commit eb8e447

Browse files
committed
fix(server): Codex threads open in another client are no longer silently replaced
When Codex refuses to resume a thread because another client (the Codex app, the CLI, or an IDE extension) still holds its writer lock, T3 treated it like any other resume failure: it started a fresh native thread and handed it a summary of the conversation. The user saw no sign of the switch, the native history was abandoned, and the other client kept working in the original thread. The Codex adapter now reports that conflict as a typed ProviderAdapterThreadInUseError, and turn start fails the run with a message that says which client to close, instead of falling back. Once the other client lets go, the next send resumes the same native thread.
1 parent 16918b5 commit eb8e447

7 files changed

Lines changed: 175 additions & 16 deletions

File tree

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3372,6 +3372,68 @@ describe("CodexAdapterV2 post-settle continuation", () => {
33723372
),
33733373
);
33743374

3375+
it.effect("reports a thread another Codex client is writing to as in use", () =>
3376+
Effect.scoped(
3377+
Effect.gen(function* () {
3378+
const nativeThreadId = "thread-open-elsewhere";
3379+
const harness = yield* makeCodexReplayHarness(
3380+
makeCodexReplayTranscript({
3381+
scenario: "codex-resume-active-writer",
3382+
entries: [
3383+
...codexReplayPreamble({
3384+
nativeThreadId,
3385+
nativeTurnId: "unused-turn",
3386+
prompt: "unused-prompt",
3387+
}).slice(0, 5),
3388+
{
3389+
type: "expect_outbound",
3390+
label: "thread/resume",
3391+
frame: {
3392+
id: 3,
3393+
method: "thread/resume",
3394+
params: {
3395+
threadId: nativeThreadId,
3396+
excludeTurns: true,
3397+
cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
3398+
model: CODEX_TEST_MODEL_SELECTION.model,
3399+
config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3400+
},
3401+
},
3402+
},
3403+
{
3404+
type: "emit_inbound",
3405+
label: "active writer",
3406+
frame: {
3407+
id: 3,
3408+
error: {
3409+
code: -32600,
3410+
message: `thread ${nativeThreadId} already has an active writer`,
3411+
},
3412+
},
3413+
},
3414+
],
3415+
}),
3416+
);
3417+
3418+
const error = yield* Effect.flip(
3419+
harness.runtime.resumeThread({
3420+
providerThread: harness.providerThread,
3421+
modelSelection: CODEX_TEST_MODEL_SELECTION,
3422+
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3423+
}),
3424+
);
3425+
3426+
assert.equal(error._tag, "ProviderAdapterThreadInUseError");
3427+
assert.nestedPropertyVal(error, "providerThreadId", harness.providerThread.id);
3428+
assert.include(error.message, "open in another Codex client");
3429+
}).pipe(
3430+
Effect.provide(
3431+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3432+
),
3433+
),
3434+
),
3435+
);
3436+
33753437
it.effect("continues an interrupted native thread with empty input and reasoning summaries", () =>
33763438
Effect.scoped(
33773439
Effect.gen(function* () {

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

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,21 @@ function normalizeCodexCause(error: unknown): unknown {
338338
return error;
339339
}
340340

341+
const CODEX_THREAD_IN_USE_MESSAGE =
342+
"This conversation is open in another Codex client, such as the Codex app, the Codex CLI, or an IDE extension. Codex lets one client write to a conversation at a time. Quit that client, then send your message again.";
343+
344+
const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
345+
346+
// Codex holds a per-thread writer lock for as long as a thread stays loaded in
347+
// any app-server sharing the same CODEX_HOME, and reports a conflict this way.
348+
function isCodexActiveWriterError(error: unknown): boolean {
349+
return (
350+
isCodexAppServerRequestError(error) &&
351+
error.code === -32600 &&
352+
error.errorMessage.includes("already has an active writer")
353+
);
354+
}
355+
341356
function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {
342357
return seconds === null || seconds === undefined
343358
? DateTime.nowUnsafe()
@@ -6539,14 +6554,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
65396554
updatedAt: codexTimestamp(response.thread.updatedAt),
65406555
} satisfies OrchestrationV2ProviderThread;
65416556
}).pipe(
6542-
Effect.mapError(
6543-
(cause) =>
6544-
new ProviderAdapter.ProviderAdapterResumeThreadError({
6545-
driver: CODEX_PROVIDER,
6546-
providerSessionId: input.providerSessionId,
6547-
providerThreadId: threadInput.providerThread.id,
6548-
cause: normalizeCodexCause(cause),
6549-
}),
6557+
Effect.mapError((cause) =>
6558+
isCodexActiveWriterError(cause)
6559+
? new ProviderAdapter.ProviderAdapterThreadInUseError({
6560+
driver: CODEX_PROVIDER,
6561+
providerThreadId: threadInput.providerThread.id,
6562+
detail: CODEX_THREAD_IN_USE_MESSAGE,
6563+
})
6564+
: new ProviderAdapter.ProviderAdapterResumeThreadError({
6565+
driver: CODEX_PROVIDER,
6566+
providerSessionId: input.providerSessionId,
6567+
providerThreadId: threadInput.providerThread.id,
6568+
cause: normalizeCodexCause(cause),
6569+
}),
65506570
),
65516571
),
65526572
compactThread: (turnInput) =>

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

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ function makeLocalCommandHarness(input: {
284284
readonly openFailure?: unknown;
285285
readonly ensureThreadFailure?: unknown;
286286
readonly historyReadFailureAfterFallback?: unknown;
287+
readonly resumeFailure?: ProviderAdapter.ProviderAdapterV2Error;
287288
readonly interruptOpen?: boolean;
288289
readonly interruptRunBeforeOpenFailure?: boolean;
289290
readonly writeFailure?: unknown;
@@ -460,7 +461,7 @@ function makeLocalCommandHarness(input: {
460461
checkpoints: [],
461462
updatedAt: now,
462463
};
463-
if ("historyReadFailureAfterFallback" in input) {
464+
if ("historyReadFailureAfterFallback" in input || "resumeFailure" in input) {
464465
const nativeThreadRef = {
465466
driver: providerThread.driver,
466467
nativeId: "native-resume-thread",
@@ -499,22 +500,24 @@ function makeLocalCommandHarness(input: {
499500
),
500501
),
501502
);
503+
const fallbackEnsureThread = vi.fn(() => Effect.succeed(providerThread));
502504
const resumeFallbackSession = {
503505
driver: providerThread.driver,
504506
resumeThread: () =>
505507
Effect.fail(
506-
new ProviderAdapter.ProviderAdapterEventStreamError({
507-
driver: providerThread.driver,
508-
providerSessionId,
509-
cause: "native thread is gone",
510-
}),
508+
input.resumeFailure ??
509+
new ProviderAdapter.ProviderAdapterEventStreamError({
510+
driver: providerThread.driver,
511+
providerSessionId,
512+
cause: "native thread is gone",
513+
}),
511514
),
512-
ensureThread: () => Effect.succeed(providerThread),
515+
ensureThread: fallbackEnsureThread,
513516
};
514517
const open = vi.fn(() =>
515518
input.interruptOpen === true
516519
? Effect.interrupt
517-
: "historyReadFailureAfterFallback" in input
520+
: "historyReadFailureAfterFallback" in input || "resumeFailure" in input
518521
? Effect.succeed(resumeFallbackSession as never)
519522
: "ensureThreadFailure" in input
520523
? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)
@@ -677,6 +680,7 @@ function makeLocalCommandHarness(input: {
677680
resolveRuntimePolicy,
678681
createWorktree,
679682
open,
683+
fallbackEnsureThread,
680684
writeIfRunCurrent,
681685
startRootRun,
682686
tryHandlePromptCommand,
@@ -1038,6 +1042,39 @@ effectIt.effect(
10381042
}),
10391043
);
10401044

1045+
effectIt.effect("fails the run instead of replacing a native thread another client holds", () =>
1046+
Effect.gen(function* () {
1047+
const detail = "This conversation is open in another Codex client.";
1048+
const harness = makeLocalCommandHarness({
1049+
text: "Continue",
1050+
resumeFailure: new ProviderAdapter.ProviderAdapterThreadInUseError({
1051+
driver: ProviderDriverKind.make("codex"),
1052+
providerThreadId: ProviderThreadId.make("new-provider-thread"),
1053+
detail,
1054+
}),
1055+
});
1056+
1057+
const exit = yield* Effect.exit(harness.start);
1058+
1059+
expect(harness.fallbackEnsureThread).not.toHaveBeenCalled();
1060+
expect(exit._tag).toBe("Success");
1061+
expect(harness.startRootRun).not.toHaveBeenCalled();
1062+
const projection = harness.projection();
1063+
expect(projection.providerThreads.at(-1)?.nativeThreadRef?.nativeId).toBe(
1064+
"native-resume-thread",
1065+
);
1066+
expect(projection.contextHandoffs).toEqual([]);
1067+
expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
1068+
expect(projection.turnItems).toMatchObject([
1069+
{
1070+
type: "error",
1071+
title: "Provider turn failed to start",
1072+
failure: { class: "provider_error", message: detail },
1073+
},
1074+
]);
1075+
}),
1076+
);
1077+
10411078
effectIt.effect("does not mistake a failed state read for a superseded run", () =>
10421079
Effect.gen(function* () {
10431080
const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true });

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,11 @@ export const layer: Layer.Layer<
676676
if (resumed._tag === "Success") {
677677
return resumed.success;
678678
}
679+
// Another client is still writing to the native thread. A fresh
680+
// session here would silently split the conversation from it.
681+
if (resumed.failure._tag === "ProviderAdapterThreadInUseError") {
682+
return yield* loadFromProvider(Effect.fail(resumed.failure));
683+
}
679684

680685
yield* Effect.logWarning("Provider resume failed; attempting a fresh native session", {
681686
driver: session.driver,

‎packages/provider-core/src/server/ProviderAdapter.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,23 @@ export class ProviderAdapterResumeThreadError extends Schema.TaggedError<Provide
220220
}
221221
}
222222

223+
/**
224+
* The native thread is live in another process that owns its writes. Starting
225+
* a replacement would split the conversation, so callers must not fall back.
226+
*/
227+
export class ProviderAdapterThreadInUseError extends Schema.TaggedError<ProviderAdapterThreadInUseError>()(
228+
"ProviderAdapterThreadInUseError",
229+
{
230+
driver: ProviderDriverKind,
231+
providerThreadId: ProviderThreadId,
232+
detail: Schema.String,
233+
},
234+
) {
235+
override get message(): string {
236+
return this.detail;
237+
}
238+
}
239+
223240
export class ProviderAdapterEnsureThreadError extends Schema.TaggedError<ProviderAdapterEnsureThreadError>()(
224241
"ProviderAdapterEnsureThreadError",
225242
{
@@ -373,6 +390,7 @@ export const ProviderAdapterV2Error = Schema.Union([
373390
ProviderAdapterOpenSessionError,
374391
ProviderAdapterCloseSessionError,
375392
ProviderAdapterResumeThreadError,
393+
ProviderAdapterThreadInUseError,
376394
ProviderAdapterEnsureThreadError,
377395
ProviderAdapterReadThreadSnapshotError,
378396
ProviderAdapterRollbackThreadError,

‎packages/provider-core/src/server/failure.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,22 @@ it("preserves actionable handoff errors wrapped by turn startup", () => {
101101
);
102102
});
103103

104+
it("explains a native thread another client is writing to", () => {
105+
const inUse = new ProviderAdapter.ProviderAdapterThreadInUseError({
106+
driver: ProviderDriverKind.make("codex"),
107+
providerThreadId: ProviderThreadId.make("provider-thread:in-use"),
108+
detail: "This conversation is open in another Codex client.",
109+
});
110+
const cause = new ProviderAdapter.ProviderAdapterTurnStartError({
111+
driver: ProviderDriverKind.make("codex"),
112+
threadId: ThreadId.make("thread:in-use"),
113+
providerThreadId: ProviderThreadId.make("provider-thread:in-use"),
114+
runId: RunId.make("run:in-use"),
115+
cause: inUse,
116+
});
117+
assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, inUse.message);
118+
});
119+
104120
it("does not expose defect text nested inside a known error category", () => {
105121
const failure = makeProviderFailure({
106122
cause: {

‎packages/provider-core/src/server/failure.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ function causeMessage(cause: unknown): string | undefined {
4545
case "ContextHandoffBudgetError":
4646
return new ContextHandoffBudgetError().message;
4747
case "ClaudeBackgroundWorkBlocksQueryReplacementError":
48+
case "ProviderAdapterThreadInUseError":
4849
return stringField(cause, "message");
4950
case "ContextHandoffDeliveryUncertainError":
5051
return "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.";

0 commit comments

Comments
 (0)