From 8b80457ed9e4f944eb2d96aad663f459f541305b Mon Sep 17 00:00:00 2001 From: evilweasel <38261180+EvilWeasel@users.noreply.github.com> Date: Wed, 21 Oct 2026 08:36:58 +0200 Subject: [PATCH 1/4] fix(codex): revoke CUA with valid disabled transport --- apps/server/src/cua/codexCuaConfig.test.ts | 94 ++++++++++++++++++- apps/server/src/cua/codexCuaConfig.ts | 9 +- .../Adapters/CodexAdapterV2.test.ts | 7 +- .../Adapters/CodexAdapterV2.ts | 3 + 4 files changed, 110 insertions(+), 3 deletions(-) diff --git a/apps/server/src/cua/codexCuaConfig.test.ts b/apps/server/src/cua/codexCuaConfig.test.ts index 138e208a5da86..43681ede58a84 100644 --- a/apps/server/src/cua/codexCuaConfig.test.ts +++ b/apps/server/src/cua/codexCuaConfig.test.ts @@ -1,3 +1,7 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; import { expect, it } from "vite-plus/test"; import { codexCuaConfig } from "./codexCuaConfig.ts"; @@ -9,11 +13,99 @@ it("preserves T3 and user MCP servers while revoking its own saved configuration }; expect(codexCuaConfig(servers, undefined)).toEqual({ ...servers, - "mcp_servers.t3-windows-cua": { enabled: false }, + "mcp_servers.t3-windows-cua": { + enabled: false, + command: "t3-windows-cua-disabled", + args: [], + env: {}, + }, }); expect(servers["mcp_servers.t3-windows-cua"]).toEqual({ command: "old-managed-driver" }); }); +it("clears routing and environment when an attached session is revoked", () => { + const active = codexCuaConfig( + {}, + { + generation: "revoked", + driverVersion: "0.37.0", + contractVersion: "fixture", + mcpProtocolVersion: "fixture", + mcp: { + command: "previous-driver.exe", + args: ["mcp", "--socket", "previous-generation"], + environment: [{ name: "PREVIOUS_ATTACHMENT", value: "fixture" }], + }, + }, + ); + const off = codexCuaConfig(active, undefined); + expect(off["mcp_servers.t3-windows-cua"]).toEqual({ + enabled: false, + command: "t3-windows-cua-disabled", + args: [], + env: {}, + }); + expect(codexCuaConfig(off, undefined)).toEqual(off); +}); + +const codexBinary = process.env.T3CODE_CODEX_CONFIG_TEST_BINARY; + +it.skipIf(!codexBinary)( + "parses fresh and revoked configurations with the actual Codex binary", + () => { + const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cua-config-")); + const env = { ...process.env, CODEX_HOME: home }; + try { + const invalid = NodeChildProcess.spawnSync( + codexBinary!, + ["-c", "mcp_servers.t3-windows-cua={enabled=false}", "mcp", "list", "--json"], + { + cwd: home, + env, + encoding: "utf8", + timeout: 10_000, + }, + ); + expect(invalid.status).not.toBe(0); + expect(invalid.stderr).toContain("invalid transport"); + const overrides = Object.entries(codexCuaConfig({}, undefined)).flatMap(([key, value]) => + Object.entries(value as Record).flatMap(([field, setting]) => [ + "-c", + `${key}.${field}=${JSON.stringify(setting)}`, + ]), + ); + for (const saved of [false, true]) { + if (saved) { + NodeFS.writeFileSync( + NodePath.join(home, "config.toml"), + '[mcp_servers.t3-windows-cua]\nenabled = true\ncommand = "previous-driver.exe"\nargs = ["mcp", "--socket", "previous-generation"]\nenv = { PREVIOUS_ATTACHMENT = "fixture" }\n', + ); + } + const servers = JSON.parse( + NodeChildProcess.execFileSync(codexBinary!, [...overrides, "mcp", "list", "--json"], { + cwd: home, + env, + encoding: "utf8", + timeout: 10_000, + }), + ); + expect(servers).toEqual([ + expect.objectContaining({ + name: "t3-windows-cua", + enabled: false, + transport: expect.objectContaining({ + command: "t3-windows-cua-disabled", + args: [], + }), + }), + ]); + } + } finally { + NodeFS.rmSync(home, { recursive: true, force: true }); + } + }, +); + it("uses the host's exact private routing descriptor without changing approval policy", () => { expect( codexCuaConfig( diff --git a/apps/server/src/cua/codexCuaConfig.ts b/apps/server/src/cua/codexCuaConfig.ts index 1ef3882f07070..86e6bd9abcf2f 100644 --- a/apps/server/src/cua/codexCuaConfig.ts +++ b/apps/server/src/cua/codexCuaConfig.ts @@ -16,5 +16,12 @@ export const codexCuaConfig = ( args: [...connection.mcp.args], env: Object.fromEntries(connection.mcp.environment.map(({ name, value }) => [name, value])), } - : { enabled: false }, + : { + // Codex validates the transport even when disabled. Replace saved routing + // as well as revoking it, so resume cannot retain a previous attachment. + enabled: false, + command: "t3-windows-cua-disabled", + args: [], + env: {}, + }, }); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 81ca55f01949f..c10e592472894 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -970,7 +970,12 @@ describe("CodexAdapterV2 process spawning", () => { tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token" }, }, - "mcp_servers.t3-windows-cua": { enabled: false }, + "mcp_servers.t3-windows-cua": { + enabled: false, + command: "t3-windows-cua-disabled", + args: [], + env: {}, + }, }, }, ); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e9cc8fcb8a2b0..4bbf55d899c8d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6619,6 +6619,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const cuaConnection = yield* readCuaConnection(turnInput.threadId); const generation = cuaConnection?.generation ?? null; if ((cuaGenerations.get(turnInput.threadId) ?? null) !== generation) { + // Resume reuses a loaded thread's MCP connections. Unload it first + // so a revoked attachment cannot survive the configuration change. + yield* client.request("thread/unsubscribe", { threadId }); // Rebind only after an explicit new turn, never replay an interrupted action. yield* client.raw.request("thread/resume", { threadId, From bde4f425578d8cc34796b5a489dd2518ba24a420 Mon Sep 17 00:00:00 2001 From: evilweasel <38261180+EvilWeasel@users.noreply.github.com> Date: Wed, 21 Oct 2026 08:48:32 +0200 Subject: [PATCH 2/4] test(codex): use Effect services for parser regression --- apps/server/src/cua/codexCuaConfig.test.ts | 75 +++++++++++----------- 1 file changed, 39 insertions(+), 36 deletions(-) diff --git a/apps/server/src/cua/codexCuaConfig.test.ts b/apps/server/src/cua/codexCuaConfig.test.ts index 43681ede58a84..2521ac42f4e75 100644 --- a/apps/server/src/cua/codexCuaConfig.test.ts +++ b/apps/server/src/cua/codexCuaConfig.test.ts @@ -1,8 +1,11 @@ -import * as NodeChildProcess from "node:child_process"; -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import { expect, it } from "vite-plus/test"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as ProcessRunner from "../processRunner.ts"; +import { it } from "@effect/vitest"; +import { expect } from "vite-plus/test"; import { codexCuaConfig } from "./codexCuaConfig.ts"; it("preserves T3 and user MCP servers while revoking its own saved configuration", () => { @@ -50,23 +53,26 @@ it("clears routing and environment when an attached session is revoked", () => { const codexBinary = process.env.T3CODE_CODEX_CONFIG_TEST_BINARY; -it.skipIf(!codexBinary)( +it.effect.skipIf(!codexBinary)( "parses fresh and revoked configurations with the actual Codex binary", - () => { - const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cua-config-")); - const env = { ...process.env, CODEX_HOME: home }; - try { - const invalid = NodeChildProcess.spawnSync( - codexBinary!, - ["-c", "mcp_servers.t3-windows-cua={enabled=false}", "mcp", "list", "--json"], - { - cwd: home, - env, - encoding: "utf8", - timeout: 10_000, - }, - ); - expect(invalid.status).not.toBe(0); + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const runner = yield* ProcessRunner.ProcessRunner; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cua-config-" }); + const invocation = { + command: codexBinary!, + cwd: home, + env: { ...process.env, CODEX_HOME: home }, + timeout: "10 seconds" as const, + maxOutputBytes: 64 * 1024, + }; + const invalid = yield* runner.run({ + ...invocation, + args: ["-c", "mcp_servers.t3-windows-cua={enabled=false}", "mcp", "list", "--json"], + }); + expect(invalid.code).not.toBe(0); expect(invalid.stderr).toContain("invalid transport"); const overrides = Object.entries(codexCuaConfig({}, undefined)).flatMap(([key, value]) => Object.entries(value as Record).flatMap(([field, setting]) => [ @@ -76,20 +82,17 @@ it.skipIf(!codexBinary)( ); for (const saved of [false, true]) { if (saved) { - NodeFS.writeFileSync( - NodePath.join(home, "config.toml"), + yield* fs.writeFileString( + path.join(home, "config.toml"), '[mcp_servers.t3-windows-cua]\nenabled = true\ncommand = "previous-driver.exe"\nargs = ["mcp", "--socket", "previous-generation"]\nenv = { PREVIOUS_ATTACHMENT = "fixture" }\n', ); } - const servers = JSON.parse( - NodeChildProcess.execFileSync(codexBinary!, [...overrides, "mcp", "list", "--json"], { - cwd: home, - env, - encoding: "utf8", - timeout: 10_000, - }), - ); - expect(servers).toEqual([ + const parsed = yield* runner.run({ + ...invocation, + args: [...overrides, "mcp", "list", "--json"], + }); + expect(parsed.code).toBe(0); + expect(JSON.parse(parsed.stdout)).toEqual([ expect.objectContaining({ name: "t3-windows-cua", enabled: false, @@ -100,10 +103,10 @@ it.skipIf(!codexBinary)( }), ]); } - } finally { - NodeFS.rmSync(home, { recursive: true, force: true }); - } - }, + }).pipe( + Effect.scoped, + Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer))), + ), ); it("uses the host's exact private routing descriptor without changing approval policy", () => { From 6db5b2d71f0bf139168bd398eac029c6e7db607b Mon Sep 17 00:00:00 2001 From: evilweasel <38261180+EvilWeasel@users.noreply.github.com> Date: Wed, 21 Oct 2026 08:50:07 +0200 Subject: [PATCH 3/4] fix(codex): clear dynamic tool registration after CUA unload --- apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 4bbf55d899c8d..04dcc4c18889c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6622,6 +6622,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // Resume reuses a loaded thread's MCP connections. Unload it first // so a revoked attachment cannot survive the configuration change. yield* client.request("thread/unsubscribe", { threadId }); + observatoryRegisteredThreads.delete(threadId); // Rebind only after an explicit new turn, never replay an interrupted action. yield* client.raw.request("thread/resume", { threadId, From d9286c6894f2a7174b67b4dd76474b51d9dced7c Mon Sep 17 00:00:00 2001 From: evilweasel <38261180+EvilWeasel@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:08:09 +0200 Subject: [PATCH 4/4] fix(codex): await CUA unload and preserve observatory registration --- .../Adapters/CodexAdapterV2.test.ts | 130 ++++++++++++++++-- .../Adapters/CodexAdapterV2.ts | 32 ++++- 2 files changed, 144 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index c10e592472894..c4ae43f7442f5 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1,3 +1,4 @@ +import * as CuaControl from "../../cua/CuaControl.ts"; import { AgentObservatoryInvocationResult } from "@t3tools/contracts"; import * as NodeOS from "node:os"; @@ -2545,8 +2546,13 @@ describe("CodexAdapterV2 post-settle continuation", () => { readChildMetadata?: Parameters[2], observatoryAvailable?: boolean, effectiveRuntime?: CodexEffectiveRuntime, + beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"], ) => Effect.gen(function* () { + const driver = yield* CodexReplay.makeReplayDriver( + transcript, + beforeEmitInbound === undefined ? {} : { beforeEmitInbound }, + ); const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const serverConfig = yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie); @@ -2554,7 +2560,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { []; const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = { open: (openInput) => - Layer.build(CodexReplay.layerReplay(transcript)).pipe( + Layer.build(CodexReplay.layerReplayWithDriver(driver)).pipe( Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterOpenSessionError({ @@ -4715,14 +4721,48 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); it.effect.each([ - { registered: true, callback: true }, - { registered: false, callback: true }, - { registered: true, callback: false }, + { registered: true, callback: true, rebind: undefined }, + { registered: false, callback: true, rebind: undefined }, + { registered: true, callback: false, rebind: undefined }, + { registered: true, callback: true, rebind: "unsubscribed" as const }, + { registered: true, callback: true, rebind: "notLoaded" as const }, ])( - "normal native observatory registration/instruction/read-publish protocol $registered/$callback", - ({ registered, callback }) => + "normal native observatory registration/instruction/read-publish protocol $registered/$callback/$rebind", + ({ registered, callback, rebind }) => Effect.gen(function* () { - const scenario = `observatory-protocol-${registered}-${callback}`; + const scenario = `observatory-protocol-${registered}-${callback}-${rebind}`; + let revoked = false; + let closedDelivered = false; + const unsubscribed = yield* Deferred.make(); + const allowClosed = yield* Deferred.make(); + let resumeRequest: unknown; + const rebindOffset = rebind === undefined ? 0 : 2; + const control = CuaControl.CuaControl.of({ + status: Effect.succeed({ + environmentId: EnvironmentId.make("env:protocol"), + supported: true, + enabled: true, + phase: "ready", + owner: null, + }), + changes: Stream.empty, + subscribe: () => Stream.empty, + setEnabled: () => Effect.void, + attach: () => + Effect.suspend(() => + rebind !== undefined && !revoked + ? Effect.succeed({ + generation: "generation-one", + driverVersion: "0.37.0", + contractVersion: "0.8.0", + mcpProtocolVersion: "2025-06-18", + mcp: { command: "unused-fixture", args: [], environment: [] }, + }) + : Effect.fail(new CuaControl.CuaUnavailableError({ reason: "disabled" })), + ), + release: () => Effect.void, + stop: () => Effect.void, + }); const nativeThreadId = `native-${scenario}`; const nativeTurnId = `turn-${scenario}`; let startRequest: unknown; @@ -4787,13 +4827,46 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, ...preamble.slice(4, 5), + ...(rebind === undefined + ? [] + : ([ + { + type: "expect_outbound", + frame: { + id: 3, + method: "thread/unsubscribe", + params: { threadId: nativeThreadId }, + }, + }, + { type: "emit_inbound", frame: { id: 3, result: { status: rebind } } }, + ...(rebind === "unsubscribed" + ? ([ + { + type: "emit_inbound", + label: "delayed-close", + frame: { method: "thread/closed", params: { threadId: nativeThreadId } }, + }, + ] satisfies Array) + : []), + { + type: "expect_outbound", + get frame() { + return { id: 4, method: "thread/resume", params: resumeRequest }; + }, + }, + ...preamble.slice(4, 5).map((entry) => withReplayRequestId(entry, 4)), + ] satisfies Array)), { type: "expect_outbound", get frame() { - return { id: 3, method: "turn/start", params: turnRequest }; + return { id: 3 + rebindOffset, method: "turn/start", params: turnRequest }; }, }, - ...preamble.slice(6), + ...preamble + .slice(6) + .map((entry, index) => + index === 0 ? withReplayRequestId(entry, 3 + rebindOffset) : entry, + ), call(10, "read-own", { action: "read", threadId: "model-forged-thread" }), response(10, () => (active ? '{"action":"read","snapshot":null}' : refusal), active), call(11, "read-own", { action: "read" }), @@ -4848,10 +4921,32 @@ describe("CodexAdapterV2 post-settle continuation", () => { Effect.sync(() => { if (method === "thread/start") startRequest = params; if (method === "turn/start") turnRequest = params; - }), + if (method === "thread/resume") { + if (rebind === "unsubscribed") assert.isTrue(closedDelivered); + resumeRequest = params; + } + }).pipe( + Effect.andThen( + method === "thread/unsubscribe" + ? Deferred.succeed(unsubscribed, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), undefined, registered, - ); + undefined, + (entry) => + entry.label === "delayed-close" + ? Deferred.await(allowClosed).pipe( + Effect.tap(() => + Effect.sync(() => { + closedDelivered = true; + }), + ), + ) + : Effect.void, + ).pipe(Effect.provideService(CuaControl.CuaControl, control)); + revoked = true; const now = yield* DateTime.now; const turnInput = makeCodexTestTurnInput({ threadId: harness.threadId, @@ -4898,10 +4993,21 @@ describe("CodexAdapterV2 post-settle continuation", () => { )(result).pipe(Effect.orDie); return result; }); - yield* harness.runtime.startTurn({ + const startingTurn = harness.runtime.startTurn({ ...turnInput, ...(callback ? { onObservatoryInvocation } : {}), }); + if (rebind === "unsubscribed") { + const starting = yield* startingTurn.pipe(Effect.forkScoped); + yield* Deferred.await(unsubscribed); + yield* Effect.yieldNow; + assert.isUndefined(resumeRequest); + assert.isUndefined(turnRequest); + yield* Deferred.succeed(allowClosed, undefined); + yield* Fiber.join(starting); + } else { + yield* startingTurn; + } yield* harness.firstTerminal; const start = yield* Schema.decodeUnknownEffect( Schema.Struct({ diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 04dcc4c18889c..2e0b511a5ad52 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -2100,6 +2100,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); const activeTurns = yield* Ref.make(new Map()); const observatoryRegisteredThreads = new Set(); + const cuaUnloadWaiters = new Map>(); const observatoryCalls = new WeakMap< ActiveCodexTurnContext, Map< @@ -4971,6 +4972,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // their command items, while the shared provider session stays alive. yield* client.handleServerNotification("thread/closed", (payload) => Effect.gen(function* () { + const unloaded = cuaUnloadWaiters.get(payload.threadId); + if (unloaded !== undefined) yield* Deferred.succeed(unloaded, undefined); const completedAt = yield* DateTime.now; for (const context of (yield* Ref.get(settledTurns)).values()) { if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue; @@ -6619,23 +6622,40 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const cuaConnection = yield* readCuaConnection(turnInput.threadId); const generation = cuaConnection?.generation ?? null; if ((cuaGenerations.get(turnInput.threadId) ?? null) !== generation) { - // Resume reuses a loaded thread's MCP connections. Unload it first - // so a revoked attachment cannot survive the configuration change. - yield* client.request("thread/unsubscribe", { threadId }); - observatoryRegisteredThreads.delete(threadId); + // Unsubscribe only schedules an idle unload. Resuming before thread/closed + // would cancel it and retain the old MCP connections. Fail closed if another + // subscriber or an active turn prevents unloading; never replay an action. + const unloaded = yield* Deferred.make(); + cuaUnloadWaiters.set(threadId, unloaded); + yield* Effect.gen(function* () { + const result = yield* client.request("thread/unsubscribe", { threadId }); + if (result.status !== "notLoaded") { + yield* Deferred.await(unloaded).pipe(Effect.timeout("90 seconds")); + } + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (cuaUnloadWaiters.get(threadId) === unloaded) + cuaUnloadWaiters.delete(threadId); + }), + ), + ); + const reboundConnection = yield* readCuaConnection(turnInput.threadId); + // This same session registered the dynamic tool. Codex persists its + // definition in the rollout and restores it during the cold resume. // Rebind only after an explicit new turn, never replay an interrupted action. yield* client.raw.request("thread/resume", { threadId, excludeTurns: true, ...codexThreadRuntimeParams({ mcpSession, - cuaConnection, + cuaConnection: reboundConnection, modelSelection: turnInput.modelSelection, runtimePolicy: turnInput.runtimePolicy, ...(resolvedRuntime?.nativeSubagents === false ? { nativeSubagents: false } : {}), }), }); - cuaGenerations.set(turnInput.threadId, generation); + cuaGenerations.set(turnInput.threadId, reboundConnection?.generation ?? null); } const turnStartParams = yield* buildCodexTurnStartParams({