Skip to content
TypeScript

fix(server): Codex sessions get T3CODE_THREAD_ID like Claude sessions (#28604)

Ruslan Panamarenkafa31b66bbb2a
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 8e73db37843..54a4c2e2bf2 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -486,6 +486,11 @@ const CODEX_TEST_RUNTIME_POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy
interactionMode: "default",
cwd: "/workspace",
});
+const T3_THREAD_ENV_KEY = "shell_environment_policy.set.T3CODE_THREAD_ID";
+const threadEnvOf = (params: unknown) =>
+ Predicate.hasProperty(params, "config") && Predicate.hasProperty(params.config, T3_THREAD_ENV_KEY)
+ ? params.config[T3_THREAD_ENV_KEY]
+ : undefined;
function makeCodexTestAppThread(input: {
readonly threadId: ThreadId;
@@ -1180,6 +1185,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
onRequest(method, params).pipe(
Effect.andThen(client.request(method, params)),
),
+ raw: {
+ ...client.raw,
+ request: (method, params) =>
+ onRequest(method, params).pipe(
+ Effect.andThen(client.raw.request(method, params)),
+ ),
+ },
}) satisfies CodexClient.CodexAppServerClient["Service"],
),
Effect.provide(context),
@@ -1513,6 +1525,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
config: {
"tools.update_plan.enabled": true,
mcp_optional_startup_grace_ms: 10_000,
+ "shell_environment_policy.set.T3CODE_THREAD_ID": `thread-${scenario}`,
"mcp_servers.t3-code": {
url: "http://127.0.0.1:43123/mcp",
tool_timeout_sec: 3_900,
@@ -2508,18 +2521,75 @@ describe("CodexAdapterV2 post-settle continuation", () => {
label: "thread/resume",
frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
},
+ {
+ type: "expect_outbound",
+ label: "thread/resume without an app thread",
+ frame: {
+ id: 4,
+ method: "thread/resume",
+ params: {
+ threadId: nativeThreadId,
+ excludeTurns: true,
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
+ },
+ },
+ },
+ {
+ type: "emit_inbound",
+ label: "thread/resume without an app thread",
+ frame: { id: 4, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
+ },
+ {
+ type: "expect_outbound",
+ label: "thread/resume with an explicit app thread",
+ frame: {
+ id: 5,
+ method: "thread/resume",
+ params: {
+ threadId: nativeThreadId,
+ excludeTurns: true,
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
+ },
+ },
+ },
+ {
+ type: "emit_inbound",
+ label: "thread/resume with an explicit app thread",
+ frame: { id: 5, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
+ },
],
});
- const harness = yield* makeCodexReplayHarness(transcript);
+ const resumeThreadEnvs: Array<unknown> = [];
+ const harness = yield* makeCodexReplayHarness(
+ transcript,
+ () => Effect.void,
+ (method, params) =>
+ Effect.sync(() => {
+ if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params));
+ }),
+ );
const resumed = yield* harness.runtime.resumeThread({
providerThread: harness.providerThread,
modelSelection: CODEX_TEST_MODEL_SELECTION,
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
});
+ yield* harness.runtime.resumeThread({
+ providerThread: { ...harness.providerThread, appThreadId: null },
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
+ });
+ const explicitThreadId = ThreadId.make(`thread-${scenario}-explicit`);
+ yield* harness.runtime.resumeThread({
+ threadId: explicitThreadId,
+ providerThread: harness.providerThread,
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
+ });
assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
assert.equal(resumed.status, "idle");
assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
+ assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]);
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -7489,12 +7559,14 @@ describe("CodexAdapterV2 post-settle continuation", () => {
],
});
const outbound: Array<string> = [];
+ const forkThreadEnvs: Array<unknown> = [];
const harness = yield* makeCodexReplayHarness(
transcript,
() => Effect.void,
- (method) =>
+ (method, params) =>
Effect.sync(() => {
outbound.push(method);
+ if (method === "thread/fork") forkThreadEnvs.push(threadEnvOf(params));
}),
);
const now = yield* DateTime.now;
@@ -7524,6 +7596,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.notEqual(forkedProviderThread.id, harness.providerThread.id);
assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, firstTurn.id);
assert.deepEqual(outbound.slice(-2), ["thread/turns/list", "thread/revert"]);
+ assert.deepEqual(forkThreadEnvs, ["thread-fork-paginated-fallback-target"]);
}).pipe(
Effect.scoped,
Effect.provide(
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index 1003ea48b12..e6399ff36fd 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -101,6 +101,7 @@ import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts";
+import * as PortScanner from "../../preview/PortScanner.ts";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
@@ -1335,6 +1336,7 @@ export const CODEX_THREAD_CONFIG = {
const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60;
function codexThreadRuntimeParams(input: {
+ readonly threadId: ThreadId | null;
readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
readonly modelSelection?: { readonly model: string };
readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
@@ -1349,6 +1351,10 @@ function codexThreadRuntimeParams(input: {
...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }),
config: {
...CODEX_THREAD_CONFIG,
+ // One app-server serves many threads, so the id goes in per-thread shell config, not its env.
+ ...(input.threadId === null
+ ? {}
+ : { [`shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`]: input.threadId }),
...(mcpSession === undefined
? {}
: {
@@ -6977,6 +6983,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
client.request(
"thread/start",
codexThreadRuntimeParams({
+ threadId: threadInput.threadId,
mcpSession,
modelSelection: threadInput.modelSelection,
runtimePolicy: threadInput.runtimePolicy,
@@ -7005,13 +7012,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
resumeThread: Effect.fn("CodexAdapterV2.resumeThread")(
function* (threadInput) {
const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread);
+ const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId;
const resume = client.raw.request("thread/resume", {
threadId: nativeThreadId,
excludeTurns: true,
...codexThreadRuntimeParams({
- mcpSession: yield* readMcpSession(
- threadInput.threadId ?? threadInput.providerThread.appThreadId,
- ),
+ threadId: appThreadId,
+ mcpSession: yield* readMcpSession(appThreadId),
...(threadInput.modelSelection === undefined
? {}
: { modelSelection: threadInput.modelSelection }),
@@ -7796,6 +7803,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
threadId,
excludeTurns: true,
...codexThreadRuntimeParams({
+ threadId: threadInput.providerThread.appThreadId,
mcpSession: yield* readMcpSession(threadInput.providerThread.appThreadId),
modelSelection: input.modelSelection,
runtimePolicy: input.runtimePolicy,
@@ -7848,6 +7856,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
? {}
: { lastTurnId: boundary.lastTurnId }),
...codexThreadRuntimeParams({
+ threadId: threadInput.targetThreadId,
mcpSession: yield* mcpSessions.read(threadInput.targetThreadId),
...(threadInput.modelSelection === undefined
? {}
diff --git a/packages/effect-codex-app-server/src/replay.ts b/packages/effect-codex-app-server/src/replay.ts
index 11ef80c02f5..7aba60a1cfd 100644
--- a/packages/effect-codex-app-server/src/replay.ts
+++ b/packages/effect-codex-app-server/src/replay.ts
@@ -237,9 +237,9 @@ function recorderThreadConfigKeys(transcript: CodexAppServerReplayTranscript): R
}
/**
- * `cwd`, `model` and host-supplied MCP servers (machine-local URLs, short-lived
- * authorization headers) vary per machine, and recorder-only keys are not the
- * client's.
+ * `cwd`, `model`, host-supplied MCP servers (machine-local URLs, short-lived
+ * authorization headers) and the T3 thread id vary per machine or run, and
+ * recorder-only keys are not the client's.
*/
function normalizeThreadRequest(frame: unknown, ignoredConfigKeys: ReadonlySet<string>): unknown {
if (typeof frame !== "object" || frame === null) return frame;
@@ -257,7 +257,10 @@ function normalizeThreadRequest(frame: unknown, ignoredConfigKeys: ReadonlySet<s
if (typeof config !== "object" || config === null) return { ...record, params };
const owned = Object.fromEntries(
Object.entries(config as Record<string, unknown>).filter(
- ([key]) => key !== "mcp_servers" && !key.startsWith("mcp_servers."),
+ ([key]) =>
+ key !== "mcp_servers" &&
+ !key.startsWith("mcp_servers.") &&
+ key !== "shell_environment_policy.set.T3CODE_THREAD_ID",
),
);
for (const key of ignoredConfigKeys) delete owned[key];