Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - checks the host's default Codex directory without writing to it.
2import * as NodeOS from "node:os";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
6import * as Clock from "effect/Clock";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import { HttpClient, HttpClientResponse } from "effect/unstable/http";
14import { ServerConfig } from "../config.ts";
15import { ServerSecretStore } from "../auth/ServerSecretStore.ts";
16import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts";
17import { CodexInstallation } from "./CodexInstallation.ts";
18import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts";
19import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
20import { codexAppServerArgs } from "./Layers/codexLaunchArgs.ts";
21import { resolveManagedCodexHomeLayout } from "./CodexManagedHome.ts";
22
23const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
24const decodeSettings = Schema.decodeSync(CodexSettings);
25it.effect("managed home defaults to the global Codex home and honors configured home paths", () =>
26 Effect.gen(function* () {
27 const path = yield* Path.Path;
28 const primary = yield* resolveManagedCodexHomeLayout(
29 "/t3-state",
30 ProviderInstanceId.make("codex"),
31 decodeSettings({}),
32 );
33 assert.equal(primary.sharedHomePath, path.join(NodeOS.homedir(), ".codex"));
34 assert.equal(primary.mode, "direct");
35 const additional = yield* resolveManagedCodexHomeLayout(
36 "/t3-state",
37 ProviderInstanceId.make("codex-work"),
38 decodeSettings({}),
39 );
40 assert.equal(additional.sharedHomePath, primary.sharedHomePath);
41 assert.equal(additional.mode, "authOverlay");
42 const configured = yield* resolveManagedCodexHomeLayout(
43 "/t3-state",
44 ProviderInstanceId.make("codex-work"),
45 decodeSettings({ homePath: "/custom/shared", shadowHomePath: "/custom/shadow" }),
46 );
47 assert.equal(configured.sharedHomePath, "/custom/shared");
48 assert.equal(configured.effectiveHomePath, "/custom/shadow");
49 }).pipe(Effect.provide(NodeServices.layer)),
50);
51for (const source of ["managed", "local"] as const)
52 for (const account of ["primary", "additional"] as const)
53 it.effect(
54 `${source} Codex ${account} account shares home state without routing owned tokens through ambient CLI overrides`,
55 () =>
56 Effect.gen(function* () {
57 const instanceId = ProviderInstanceId.make(
58 account === "primary" ? "codex" : "codex-personal",
59 );
60 const fs = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-shared-home-" });
63 yield* fs.writeFileString(path.join(sharedHome, "auth.json"), "native-auth-unchanged");
64 yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "# shared config\n");
65 const data = new Map<string, Uint8Array>();
66 const secrets = ServerSecretStore.of({
67 get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))),
68 set: (key, value) =>
69 Effect.sync(() => {
70 data.set(key, value);
71 }),
72 remove: (key) =>
73 Effect.sync(() => {
74 data.delete(key);
75 }),
76 create: () => Effect.die("unused"),
77 getOrCreateRandom: () => Effect.die("unused"),
78 });
79 let leases = 0;
80 const executable = {
81 executablePath:
82 source === "managed" ? "/isolated/tools/codex/0.156.1/bin/codex" : "/user/bin/codex",
83 managedVersionDirectory: source === "managed" ? "/isolated/tools/codex/0.156.1" : null,
84 source,
85 version: "0.156.1",
86 };
87 const installerLayer = Layer.mock(CodexInstallation)({
88 managedDirectory: "/isolated/tools/codex",
89 resolve: () => Effect.succeed(executable),
90 acquire: () =>
91 Effect.gen(function* () {
92 leases++;
93 yield* Effect.addFinalizer(() =>
94 Effect.sync(() => {
95 leases--;
96 }),
97 );
98 return executable;
99 }),
100 });
101 yield* Effect.gen(function* () {
102 const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
103 const json = yield* encodeJson({
104 clientId: "oaiapp_test",
105 accessToken: "dummy-owned-access",
106 refreshToken: "dummy-refresh",
107 expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000,
108 earliestRefreshAt: null,
109 scopes: ["chatgpt.tokens.use.direct"],
110 subject: "test-user",
111 email: null,
112 });
113 yield* store.set(new TextEncoder().encode(json));
114 const ambient = {
115 CODEX_HOME: "/user/.codex",
116 OPENAI_API_KEY: "dummy-global-key",
117 OPENAI_BASE_URL: "https://user-proxy.test",
118 T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy",
119 PATH: "/usr/bin",
120 };
121 const runtime = yield* makeCodexManagedRuntime({
122 instanceId,
123 enabled: true,
124 config: decodeSettings({ setupMode: "managed", homePath: sharedHome }),
125 environment: ambient,
126 });
127 yield* Effect.gen(function* () {
128 const effective = yield* runtime.resolve;
129 assert.strictEqual(leases, 1);
130 assert.strictEqual(effective.config.binaryPath, executable.executablePath);
131 assert.notStrictEqual(effective.config.homePath, ambient.CODEX_HOME);
132 assert.equal(runtime.homeLayout.sharedHomePath, sharedHome);
133 if (account === "primary") {
134 assert.equal(effective.config.homePath, sharedHome);
135 assert.equal(runtime.homeLayout.mode, "direct");
136 } else {
137 assert.include(effective.config.homePath, instanceId);
138 assert.include(effective.config.homePath, "userdata/providers/codex");
139 assert.equal(runtime.homeLayout.mode, "authOverlay");
140 assert.equal(
141 yield* fs.readLink(path.join(effective.config.homePath, "sessions")),
142 path.join(sharedHome, "sessions"),
143 );
144 assert.equal(
145 yield* fs.readLink(path.join(effective.config.homePath, "config.toml")),
146 path.join(sharedHome, "config.toml"),
147 );
148 assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json")));
149 }
150 assert.strictEqual(effective.environment.ACCESS_TOKEN, "dummy-owned-access");
151 assert.isUndefined(effective.environment.OPENAI_API_KEY);
152 assert.isUndefined(effective.environment.OPENAI_BASE_URL);
153 assert.isUndefined(effective.environment.T3CODE_CODEX_LAUNCH_ARGS);
154 const args = codexAppServerArgs(effective.config.launchArgs);
155 assert.include(
156 args,
157 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"',
158 );
159 assert.include(
160 args,
161 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"',
162 );
163 assert.include(args, "features.api_key_model_discovery=true");
164 assert.notInclude(effective.config.launchArgs, "model_catalog_json");
165 assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test");
166 assert.include(
167 args,
168 "model_providers.openai_token_sharing.supports_websockets=false",
169 );
170 assert.include(
171 args,
172 "model_providers.openai_token_sharing.requires_openai_auth=false",
173 );
174 assert.notInclude(effective.config.launchArgs, "dummy-owned-access");
175 assert.strictEqual(ambient.CODEX_HOME, "/user/.codex");
176 }).pipe(Effect.scoped);
177 assert.strictEqual(leases, 0);
178 yield* runtime.auth.controller.logout(Effect.void);
179 assert.equal(
180 yield* fs.readFileString(path.join(sharedHome, "auth.json")),
181 "native-auth-unchanged",
182 );
183 }).pipe(
184 Effect.provideService(ServerSecretStore, secrets),
185 Effect.provideService(ServerEnvironmentIdentity, {
186 getEnvironmentId: Effect.succeed(
187 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
188 ),
189 }),
190 Effect.provide(installerLayer),
191 Effect.provideService(
192 HttpClient.HttpClient,
193 HttpClient.make((request) =>
194 Effect.sync(() => {
195 assert.isTrue(
196 [
197 "https://auth.openai.com/.well-known/openid-configuration",
198 "https://auth.openai.com/revoke",
199 ].includes(request.url),
200 );
201 return HttpClientResponse.fromWeb(
202 request,
203 request.url.endsWith("/revoke")
204 ? new Response(null, { status: 200 })
205 : Response.json({
206 issuer: "https://auth.openai.com",
207 authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
208 token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
209 jwks_uri: "https://auth.openai.com/jwks",
210 revocation_endpoint: "https://auth.openai.com/revoke",
211 }),
212 );
213 }),
214 ),
215 ),
216 );
217 }).pipe(
218 Effect.scoped,
219 Effect.provide(
220 ServerConfig.layerTest(process.cwd(), { prefix: "t3-managed-runtime-" }).pipe(
221 Layer.provideMerge(NodeServices.layer),
222 ),
223 ),
224 ),
225 );