Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexManagedRuntime.test.ts

195 lines8.7 KB

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