Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 97 additions & 2 deletions apps/server/src/cua/codexCuaConfig.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
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", () => {
Expand All @@ -9,11 +16,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.effect.skipIf(!codexBinary)(
"parses fresh and revoked configurations with the actual Codex binary",
() =>
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<string, unknown>).flatMap(([field, setting]) => [
"-c",
`${key}.${field}=${JSON.stringify(setting)}`,
]),
);
for (const saved of [false, true]) {
if (saved) {
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 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,
transport: expect.objectContaining({
command: "t3-windows-cua-disabled",
args: [],
}),
}),
]);
}
}).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", () => {
expect(
codexCuaConfig(
Expand Down
9 changes: 8 additions & 1 deletion apps/server/src/cua/codexCuaConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {},
},
});
137 changes: 124 additions & 13 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as CuaControl from "../../cua/CuaControl.ts";
import { AgentObservatoryInvocationResult } from "@t3tools/contracts";
import * as NodeOS from "node:os";

Expand Down Expand Up @@ -970,7 +971,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: {},
},
},
},
);
Expand Down Expand Up @@ -2540,16 +2546,21 @@ describe("CodexAdapterV2 post-settle continuation", () => {
readChildMetadata?: Parameters<typeof withCodexReplayChildMetadata>[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);
const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
[];
const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = {
open: (openInput) =>
Layer.build(CodexReplay.layerReplay(transcript)).pipe(
Layer.build(CodexReplay.layerReplayWithDriver(driver)).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterOpenSessionError({
Expand Down Expand Up @@ -4710,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<void>();
const allowClosed = yield* Deferred.make<void>();
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;
Expand Down Expand Up @@ -4782,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<CodexReplay.CodexAppServerReplayEntry>)
: []),
{
type: "expect_outbound",
get frame() {
return { id: 4, method: "thread/resume", params: resumeRequest };
},
},
...preamble.slice(4, 5).map((entry) => withReplayRequestId(entry, 4)),
] satisfies Array<CodexReplay.CodexAppServerReplayEntry>)),
{
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" }),
Expand Down Expand Up @@ -4843,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,
Expand Down Expand Up @@ -4893,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({
Expand Down
28 changes: 26 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1646,7 +1646,7 @@
});
});

const layerCodexAppServerClientFactoryCommand = (

Check warning on line 1649 in apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts

View workflow job for this annotation

GitHub Actions / check

eslint(no-unused-vars)

apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:1649:7: Variable 'layerCodexAppServerClientFactoryCommand' is declared but never used. Unused variables should start with a '_'.
options: CodexClient.CodexAppServerClientOptions & {
readonly command: string;
readonly args?: ReadonlyArray<string>;
Expand Down Expand Up @@ -1882,7 +1882,7 @@
create: createCodexAdapterV2,
};

const layer: Layer.Layer<

Check warning on line 1885 in apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts

View workflow job for this annotation

GitHub Actions / check

eslint(no-unused-vars)

apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:1885:7: Variable 'layer' is declared but never used. Unused variables should start with a '_'.
ProviderAdapter.ProviderAdapterV2,
never,
| CodexAppServerClientFactory
Expand Down Expand Up @@ -2100,6 +2100,7 @@
);
const activeTurns = yield* Ref.make(new Map<string, ActiveCodexTurnContext>());
const observatoryRegisteredThreads = new Set<string>();
const cuaUnloadWaiters = new Map<string, Deferred.Deferred<void>>();
const observatoryCalls = new WeakMap<
ActiveCodexTurnContext,
Map<
Expand Down Expand Up @@ -4971,6 +4972,8 @@
// 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;
Expand Down Expand Up @@ -6619,19 +6622,40 @@
const cuaConnection = yield* readCuaConnection(turnInput.threadId);
const generation = cuaConnection?.generation ?? null;
if ((cuaGenerations.get(turnInput.threadId) ?? null) !== generation) {
// 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<void>();
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({
Expand Down Expand Up @@ -6888,7 +6912,7 @@
)
return refuse("Agent observatory unavailable for this native invocation.");
const callback = context.input.onObservatoryInvocation;
const intent = yield* Schema.decodeUnknownEffect(AgentObservatoryIntent)(

Check warning on line 6915 in apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts

View workflow job for this annotation

GitHub Actions / check

t3code(no-inline-schema-compile)

apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:6915:37: Hoist Schema.decodeUnknownEffect(...) to module scope: the compiled function is rebuilt on every call. Move it to a module-level const.
payload.arguments,
);
const codec = Schema.fromJsonString(AgentObservatoryIntent);
Expand Down Expand Up @@ -6939,7 +6963,7 @@
return refuse(
"Agent observatory invocation is stale; reconcile the original request.",
);
const text = yield* Schema.encodeEffect(

Check warning on line 6966 in apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts

View workflow job for this annotation

GitHub Actions / check

t3code(no-inline-schema-compile)

apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:6966:37: Hoist Schema.encodeEffect(...) to module scope: both the inline schema literal and the compiled function are rebuilt on every call. Move the compiled function to a module-level const.
Schema.fromJsonString(AgentObservatoryInvocationResult),
)(response);
return {
Expand Down Expand Up @@ -7035,7 +7059,7 @@
new ProviderAdapter.ProviderAdapterProtocolError({
driver: CODEX_PROVIDER,
detail:
Schema.is(ProviderAdapter.ProviderAdapterProtocolError)(cause) &&

Check warning on line 7062 in apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts

View workflow job for this annotation

GitHub Actions / check

t3code(no-inline-schema-compile)

apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:7062:15: Hoist Schema.is(...) to module scope: the compiled function is rebuilt on every call. Move it to a module-level const.
cause.detail === "Managed ChatGPT account is required for Codex Live."
? cause.detail
: `Codex Live ${operation} failed.`,
Expand Down
Loading