@firstpick/pi-package-webui 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -25300,6 +25300,8 @@ function codexUsageStructureSignature() {
25300
25300
  return JSON.stringify({
25301
25301
  state: "data",
25302
25302
  plan: formatCodexPlanType(latestCodexUsage.planType),
25303
+ source: latestCodexUsage.source || "",
25304
+ sourceNotice: latestCodexUsage.sourceNotice || "",
25303
25305
  buckets: codexUsageBuckets(latestCodexUsage).map((bucket) => [bucket.key, bucket.label]),
25304
25306
  rateLimitReachedType: latestCodexUsage.rateLimitReachedType || "",
25305
25307
  error: codexUsageError?.message || String(codexUsageError || ""),
@@ -25367,6 +25369,12 @@ function renderCodexUsage() {
25367
25369
  make("span", "codex-usage-fetched", latestCodexUsage.fetchedAt ? `updated ${formatDurationParts(Date.now() - new Date(latestCodexUsage.fetchedAt).getTime())} ago` : "updated now"),
25368
25370
  );
25369
25371
  box.append(header);
25372
+ if (latestCodexUsage.source === "codex-cli") {
25373
+ box.append(make("div", "codex-usage-detail", "Source: Codex CLI account. Its login is separate from Pi; these limits may differ from Pi's ChatGPT-plan allowance."));
25374
+ } else {
25375
+ box.append(make("div", "codex-usage-detail", "Source: Pi's legacy Codex login."));
25376
+ }
25377
+ if (latestCodexUsage.sourceNotice) box.append(make("div", "codex-usage-detail", latestCodexUsage.sourceNotice));
25370
25378
 
25371
25379
  if (buckets.length === 0) {
25372
25380
  box.append(make("div", "codex-usage-detail", "No Codex rate-limit windows were returned."));
@@ -1,4 +1,4 @@
1
- export const PI_THEME_SCHEMA_URL = "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json";
1
+ export const PI_THEME_SCHEMA_URL = "https://pi.dev/schemas/theme.schema.json";
2
2
 
3
3
  export const THEME_TOKEN_GROUPS = Object.freeze([
4
4
  { id: "core", label: "Core UI", tokens: [
@@ -0,0 +1,189 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { after, test } from "node:test";
4
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { setTimeout as delay } from "node:timers/promises";
9
+ import { CodexCliUsageError, projectCodexCliUsage, readCodexCliUsage, resolveCodexCliInvocation } from "../lib/codex-cli-usage.mjs";
10
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
11
+
12
+ const fixture = fileURLToPath(new URL("./fixtures/fake-codex-app-server.mjs", import.meta.url));
13
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-codex-cli-"));
14
+ const children = [];
15
+ let serial = 0;
16
+ after(async () => {
17
+ for (const child of children) terminateProcessTree(child, "SIGKILL");
18
+ await rm(root, { recursive: true, force: true });
19
+ });
20
+
21
+ function run(mode, options = {}) {
22
+ const log = path.join(root, `${++serial}.jsonl`);
23
+ return {
24
+ log,
25
+ result: readCodexCliUsage({
26
+ invocation: { command: process.execPath, args: [fixture, "app-server", "--listen", "stdio://"] },
27
+ env: { ...process.env, FAKE_CODEX_MODE: mode, FAKE_CODEX_LOG: log },
28
+ timeoutMs: 3_000,
29
+ spawn: (...args) => { const child = spawn(...args); children.push(child); return child; },
30
+ ...options,
31
+ }),
32
+ };
33
+ }
34
+
35
+ async function entries(log) {
36
+ return (await readFile(log, "utf8")).split("\n").filter(Boolean).map(JSON.parse);
37
+ }
38
+
39
+ function alive(pid) {
40
+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === "EPERM"; }
41
+ }
42
+
43
+ async function assertExited(pid) {
44
+ for (let attempt = 0; attempt < 100 && alive(pid); attempt++) await delay(20);
45
+ assert.equal(alive(pid), false, `fixture process ${pid} should have exited`);
46
+ }
47
+
48
+ test("the usage client performs only initialization and read-only account requests", async () => {
49
+ const { result, log } = run("success");
50
+ const data = await result;
51
+ assert.equal(data.planType, "plus");
52
+ assert.equal(data.rateLimits.primary.usedPercent, 25);
53
+ assert.equal(data.rateLimits.secondary.usedPercent, 42);
54
+ assert.equal(data.rateLimits.credits.balance, "12.50");
55
+ const messages = await entries(log);
56
+ const frames = messages.filter((entry) => entry.kind === "frame");
57
+ assert.deepEqual(frames.map((frame) => frame.method), ["initialize", "initialized", "account/read", "account/rateLimits/read"]);
58
+ assert.deepEqual(frames[2].params, { refreshToken: false });
59
+ assert.equal(frames[3].params, null);
60
+ assert.doesNotMatch(JSON.stringify(data), /secret|private-account|email|profile|accessToken/);
61
+ await assertExited(messages[0].pid);
62
+ });
63
+
64
+ test("fragmented UTF-8 JSONL and harmless notifications preserve usage data", async () => {
65
+ const data = await run("fragmented").result;
66
+ assert.equal(data.rateLimits.primary.usedPercent, 25);
67
+ assert.equal(data.rateLimits.limitName, "Codex 漢字");
68
+ });
69
+
70
+ test("weekly-only and multi-bucket usage remain usable", async () => {
71
+ const weekly = await run("weekly-only").result;
72
+ assert.equal(weekly.rateLimits.primary, null);
73
+ assert.equal(weekly.rateLimits.secondary.usedPercent, 42);
74
+ const multiple = await run("multi-bucket").result;
75
+ assert.equal(multiple.rateLimitsByLimitId.extra.primary.usedPercent, 70);
76
+ });
77
+
78
+ test("unsolicited server auth requests are rejected without providing credentials", async () => {
79
+ const { result, log } = run("server-request");
80
+ await result;
81
+ const reply = (await entries(log)).find((frame) => frame.id === "server-auth-request");
82
+ assert.equal(reply.error.code, -32601);
83
+ assert.equal(reply.result, undefined);
84
+ assert.equal(reply.error.data, undefined);
85
+ });
86
+
87
+ test("signed-out and API-key CLI accounts never request subscription limits", async () => {
88
+ for (const [mode, code] of [["logged-out", "CODEX_CLI_LOGIN_REQUIRED"], ["api-key", "CODEX_CLI_AUTH_TYPE"]]) {
89
+ const { result, log } = run(mode);
90
+ await assert.rejects(result, (error) => error.code === code && error.statusCode === 401);
91
+ assert.equal((await entries(log)).some((frame) => frame.method === "account/rateLimits/read"), false);
92
+ }
93
+ });
94
+
95
+ test("upstream errors and stderr are replaced with static sanitized diagnostics", async () => {
96
+ await assert.rejects(run("rpc-error").result, (error) => {
97
+ assert.ok(error instanceof CodexCliUsageError);
98
+ assert.equal(error.code, "CODEX_CLI_REQUEST");
99
+ assert.doesNotMatch(error.message, /fixture-|Bearer|refreshToken|private/);
100
+ return true;
101
+ });
102
+ });
103
+
104
+ test("malformed, empty, oversized and prematurely closed peers fail safely", async () => {
105
+ for (const [mode, code] of [["malformed", "CODEX_CLI_PROTOCOL"], ["empty", "CODEX_CLI_NO_USAGE"], ["oversized", "CODEX_CLI_OUTPUT_LIMIT"], ["stderr-flood", "CODEX_CLI_OUTPUT_LIMIT"], ["early-exit", "CODEX_CLI_EXIT"]]) {
106
+ await assert.rejects(run(mode).result, (error) => error.code === code);
107
+ }
108
+ });
109
+
110
+ test("a silent app server times out and is terminated", async () => {
111
+ const start = Date.now();
112
+ const { result, log } = run("hang", { timeoutMs: 250 });
113
+ await assert.rejects(result, (error) => error.code === "CODEX_CLI_TIMEOUT" && error.statusCode === 504);
114
+ assert.ok(Date.now() - start < 7_000, "timeout and cleanup must remain bounded");
115
+ await assertExited((await entries(log))[0].pid);
116
+ });
117
+
118
+ test("successful reads also terminate stubborn processes and their descendants", async () => {
119
+ for (const mode of ["stubborn", "tree"]) {
120
+ const { result, log } = run(mode);
121
+ await result;
122
+ for (const entry of (await entries(log)).filter((entry) => entry.pid)) await assertExited(entry.pid);
123
+ }
124
+ });
125
+
126
+ test("cancellation cleans up the child and pre-cancellation does not spawn", async () => {
127
+ const controller = new AbortController();
128
+ const { result, log } = run("hang", { signal: controller.signal });
129
+ await delay(200);
130
+ controller.abort();
131
+ await assert.rejects(result, (error) => error.code === "CODEX_CLI_ABORTED");
132
+ await assertExited((await entries(log))[0].pid);
133
+ await assert.rejects(readCodexCliUsage({ signal: controller.signal, spawn: () => assert.fail("must not spawn") }), (error) => error.code === "CODEX_CLI_ABORTED");
134
+ });
135
+
136
+ test("completed reads leave no parent-exit listener behind", async () => {
137
+ const before = process.listenerCount("exit");
138
+ await run("success").result;
139
+ assert.equal(process.listenerCount("exit"), before);
140
+ await assert.rejects(run("rpc-error").result);
141
+ assert.equal(process.listenerCount("exit"), before);
142
+ });
143
+
144
+ test("parent shutdown terminates an in-flight usage process", async () => {
145
+ const log = path.join(root, `${++serial}.jsonl`);
146
+ const moduleUrl = new URL("../lib/codex-cli-usage.mjs", import.meta.url).href;
147
+ const script = `import {readCodexCliUsage} from ${JSON.stringify(moduleUrl)};
148
+ void readCodexCliUsage({ invocation: {command: process.execPath, args: [${JSON.stringify(fixture)}]}, timeoutMs: 3000 }).catch(() => {});
149
+ setTimeout(() => process.exit(0), 500);`;
150
+ const parent = spawn(process.execPath, ["--input-type=module", "-e", script], {
151
+ env: { ...process.env, FAKE_CODEX_MODE: "hang", FAKE_CODEX_LOG: log },
152
+ detached: process.platform !== "win32", stdio: "ignore",
153
+ });
154
+ children.push(parent);
155
+ await new Promise((resolve, reject) => { parent.once("close", resolve); parent.once("error", reject); });
156
+ assert.equal(parent.exitCode, 0);
157
+ const pid = (await entries(log))[0].pid;
158
+ try { await assertExited(pid); } finally { if (alive(pid)) process.kill(pid, "SIGKILL"); }
159
+ });
160
+
161
+ test("missing executables and synchronous spawn errors do not leak raw details", async () => {
162
+ await assert.rejects(readCodexCliUsage({ invocation: { command: path.join(root, "missing-codex"), args: [] } }), (error) => error.code === "CODEX_CLI_NOT_FOUND");
163
+ await assert.rejects(readCodexCliUsage({ spawn: () => { throw new Error("fixture-secret"); }, invocation: { command: "codex", args: [] } }), (error) => error.code === "CODEX_CLI_START" && !error.message.includes("fixture-secret"));
164
+ });
165
+
166
+ test("quota projection allowlists fields, caps buckets and rejects malformed windows", () => {
167
+ const window = { usedPercent: 0, windowDurationMins: 300, resetsAt: 2000000000, token: "fixture-secret" };
168
+ const byId = Object.fromEntries(Array.from({ length: 100 }, (_, index) => [`bucket-${index}`, { primary: window }]));
169
+ const projected = projectCodexCliUsage({ rateLimits: { primary: window, credits: { balance: { token: "fixture-secret" } } }, rateLimitsByLimitId: byId, accountId: "private" }, "plus");
170
+ assert.equal(Object.keys(projected.rateLimitsByLimitId).length, 16);
171
+ assert.equal(projected.rateLimits.primary.usedPercent, 0);
172
+ assert.equal(projected.rateLimits.credits.balance, null);
173
+ assert.doesNotMatch(JSON.stringify(projected), /fixture-secret|private|token/);
174
+ for (const value of [null, [], { rateLimits: { primary: { usedPercent: "25" } } }, { rateLimits: { primary: { usedPercent: -1 } } }]) {
175
+ assert.throws(() => projectCodexCliUsage(value), CodexCliUsageError);
176
+ }
177
+ });
178
+
179
+ test("command resolution supports native binaries, scripts and Windows npm shims without a shell", () => {
180
+ assert.deepEqual(resolveCodexCliInvocation({ platform: "linux", env: {} }), { command: "codex", args: ["app-server", "--listen", "stdio://"] });
181
+ assert.deepEqual(resolveCodexCliInvocation({ platform: "win32", env: { PI_WEBUI_CODEX_BIN: "C:\\Codex Tools\\codex.exe" } }), { command: "C:\\Codex Tools\\codex.exe", args: ["app-server", "--listen", "stdio://"] });
182
+ const script = "C:\\Node Tools\\node_modules\\@openai\\codex\\bin\\codex.js";
183
+ const exists = new Set(["C:\\Node Tools\\codex.cmd", script].map((value) => value.toLowerCase()));
184
+ const invocation = resolveCodexCliInvocation({ platform: "win32", execPath: "C:\\Node Tools\\node.exe", env: { PATH: "C:\\Node Tools", PATHEXT: ".EXE;.CMD" }, existsSync: (value) => exists.has(value.toLowerCase()) });
185
+ assert.equal(invocation.command, "C:\\Node Tools\\node.exe");
186
+ assert.deepEqual(invocation.args, [script, "app-server", "--listen", "stdio://"]);
187
+ assert.throws(() => resolveCodexCliInvocation({ platform: "win32", env: { PI_WEBUI_CODEX_BIN: "C:\\unknown\\custom.cmd" }, existsSync: () => false }), (error) => error.code === "CODEX_CLI_SHIM");
188
+ assert.equal(resolveCodexCliInvocation({ platform: "linux", env: { PI_WEBUI_CODEX_BIN: "codex;echo hacked" } }).command, "codex;echo hacked");
189
+ });
@@ -1,17 +1,19 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { CODEX_TOKEN_REFRESH_SKEW_MS, resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
3
+ import { readFile } from "node:fs/promises";
4
+ import vm from "node:vm";
5
+ import { CODEX_TOKEN_REFRESH_SKEW_MS, CODEX_USAGE_DIRECT_TOKEN_MESSAGE, codexUsageLoginGuidance, resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
4
6
 
5
- function fakeRuntime(initial, refresh) {
6
- let credential = structuredClone(initial);
7
+ function fakeRuntime(initial, refresh, { providerId = "openai-codex", additionalCredentials = {}, additionalProviders = {} } = {}) {
8
+ const stored = new Map(Object.entries({ ...additionalCredentials, [providerId]: structuredClone(initial) }));
7
9
  let tail = Promise.resolve();
8
10
  const credentials = {
9
- async read() { return structuredClone(credential); },
10
- modify(_providerId, update) {
11
+ async read(id) { return structuredClone(stored.get(id)); },
12
+ modify(id, update) {
11
13
  const operation = tail.then(async () => {
12
- const next = await update(structuredClone(credential));
13
- if (next !== undefined) credential = structuredClone(next);
14
- return structuredClone(credential);
14
+ const next = await update(structuredClone(stored.get(id)));
15
+ if (next !== undefined) stored.set(id, structuredClone(next));
16
+ return structuredClone(stored.get(id));
15
17
  });
16
18
  tail = operation.then(() => undefined, () => undefined);
17
19
  return operation;
@@ -19,7 +21,9 @@ function fakeRuntime(initial, refresh) {
19
21
  };
20
22
  return {
21
23
  credentials,
22
- getProvider() { return { auth: { oauth: { refresh } } }; },
24
+ getProvider(id) {
25
+ return id === providerId ? { auth: { oauth: { refresh, isSubscription: true } } } : additionalProviders[id];
26
+ },
23
27
  async getAuth() { throw new Error("OAuth tests must not use ordinary auth resolution"); },
24
28
  };
25
29
  }
@@ -63,3 +67,158 @@ test("forced refresh never returns the same rejected credential", async () => {
63
67
  /rejected credential/,
64
68
  );
65
69
  });
70
+
71
+ const mustNotRefresh = async () => { throw new Error("unexpired credentials must not refresh"); };
72
+
73
+ test("Codex usage finds ChatGPT OAuth stored under the unified OpenAI provider", async () => {
74
+ const credential = oauth("chatgpt", NOW + 60 * 60 * 1000);
75
+ delete credential.accountId;
76
+ const runtime = fakeRuntime(credential, mustNotRefresh, { providerId: "openai" });
77
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
78
+ assert.equal(result.providerId, "openai");
79
+ assert.equal(result.accessToken, "chatgpt");
80
+ assert.deepEqual(result.credential, credential, "JWT-only account metadata must remain available to the server");
81
+ assert.equal(result.refreshed, false);
82
+ });
83
+
84
+ test("unified OpenAI credentials refresh under their own storage key", async () => {
85
+ let refreshCalls = 0;
86
+ const runtime = fakeRuntime(oauth("near", NOW + CODEX_TOKEN_REFRESH_SKEW_MS - 1), async (current) => {
87
+ refreshCalls += 1;
88
+ return { ...current, access: "replacement", expires: NOW + 60 * 60 * 1000 };
89
+ }, { providerId: "openai" });
90
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
91
+ assert.equal(refreshCalls, 1);
92
+ assert.equal(result.providerId, "openai");
93
+ assert.equal(result.accessToken, "replacement");
94
+ assert.equal(result.refreshed, true);
95
+ assert.equal((await runtime.credentials.read("openai")).access, "replacement");
96
+ assert.equal(await runtime.credentials.read("openai-codex"), undefined, "refresh must not copy or migrate credentials");
97
+ });
98
+
99
+ test("concurrent forced refreshes reuse the newer unified OpenAI credential", async () => {
100
+ let refreshCalls = 0;
101
+ const runtime = fakeRuntime(oauth("rejected", NOW + 60 * 60 * 1000), async (current) => {
102
+ refreshCalls += 1;
103
+ return { ...current, access: "replacement", expires: NOW + 2 * 60 * 60 * 1000 };
104
+ }, { providerId: "openai" });
105
+ const results = await Promise.all([
106
+ resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW, forceRefresh: true }),
107
+ resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW, forceRefresh: true }),
108
+ ]);
109
+ assert.equal(refreshCalls, 1);
110
+ assert.ok(results.every((result) => result.accessToken === "replacement" && result.refreshed));
111
+ });
112
+
113
+ test("unified OpenAI forced refresh rejects an unchanged token", async () => {
114
+ const runtime = fakeRuntime(oauth("rejected", NOW + 60 * 60 * 1000), async (current) => ({ ...current }), { providerId: "openai" });
115
+ await assert.rejects(resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW, forceRefresh: true }), /rejected credential/);
116
+ });
117
+
118
+ test("a usable legacy Codex login keeps precedence when both providers exist", async () => {
119
+ const runtime = fakeRuntime(oauth("legacy", NOW + 60 * 60 * 1000), mustNotRefresh, {
120
+ additionalCredentials: { openai: oauth("unified", NOW + 60 * 60 * 1000) },
121
+ additionalProviders: { openai: { auth: { oauth: { isSubscription: true, refresh: mustNotRefresh } } } },
122
+ });
123
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
124
+ assert.equal(result.providerId, "openai-codex");
125
+ assert.equal(result.accessToken, "legacy");
126
+ });
127
+
128
+ test("an orphaned legacy credential does not hide a usable unified OpenAI login", async () => {
129
+ const runtime = fakeRuntime(oauth("unified", NOW + 60 * 60 * 1000), mustNotRefresh, {
130
+ providerId: "openai",
131
+ additionalCredentials: { "openai-codex": oauth("orphaned", NOW + 60 * 60 * 1000) },
132
+ });
133
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
134
+ assert.equal(result.providerId, "openai");
135
+ assert.equal(result.accessToken, "unified");
136
+ });
137
+
138
+ test("a runtime with both providers can use unified OAuth when legacy login is absent", async () => {
139
+ const runtime = fakeRuntime(undefined, mustNotRefresh, {
140
+ additionalCredentials: { openai: oauth("unified", NOW + 60 * 60 * 1000) },
141
+ additionalProviders: { openai: { auth: { oauth: { isSubscription: true, refresh: mustNotRefresh } } } },
142
+ });
143
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
144
+ assert.equal(result.providerId, "openai");
145
+ assert.equal(result.accessToken, "unified");
146
+ });
147
+
148
+ test("unified OpenAI API keys and environment auth are never resolved for subscription usage", async () => {
149
+ for (const credential of [undefined, { type: "api_key", key: "fake-api-key" }]) {
150
+ const runtime = fakeRuntime(credential, mustNotRefresh, { providerId: "openai" });
151
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
152
+ assert.equal(result.providerId, "openai");
153
+ assert.equal(result.accessToken, undefined);
154
+ assert.deepEqual(result.credential, credential);
155
+ assert.equal(result.refreshed, false);
156
+ }
157
+ });
158
+
159
+ test("older API-key-only OpenAI providers are not treated as subscription OAuth aliases", async () => {
160
+ const runtime = fakeRuntime(undefined, mustNotRefresh, {
161
+ additionalCredentials: { openai: oauth("wrong-provider", NOW + 60 * 60 * 1000) },
162
+ additionalProviders: { openai: { auth: { apiKey: {} } } },
163
+ });
164
+ runtime.getAuth = async (id) => { assert.equal(id, "openai-codex"); return undefined; };
165
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW });
166
+ assert.equal(result.providerId, "openai-codex");
167
+ assert.equal(result.accessToken, undefined);
168
+ });
169
+
170
+ test("login guidance follows the runtime's available subscription provider", () => {
171
+ assert.equal(codexUsageLoginGuidance(fakeRuntime(undefined, mustNotRefresh)), "Run /login and choose ChatGPT Plus/Pro (Codex Subscription).");
172
+ assert.equal(codexUsageLoginGuidance(fakeRuntime(undefined, mustNotRefresh, { providerId: "openai" })), "Run /login, choose OpenAI, then Sign in with ChatGPT.");
173
+ });
174
+
175
+ test("direct ChatGPT logins are recognized but never refreshed or forwarded to Codex usage", async () => {
176
+ for (const providerId of ["openai", "openai-codex"]) {
177
+ for (const forceRefresh of [false, true]) {
178
+ const credential = { ...oauth("direct-access", NOW - 1), clientId: "fake-client", scopes: ["openid", "chatgpt.tokens.use.direct"] };
179
+ delete credential.accountId;
180
+ const runtime = fakeRuntime(credential, mustNotRefresh, { providerId });
181
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW, forceRefresh });
182
+ assert.equal(result.providerId, providerId);
183
+ assert.equal(result.unsupportedReason, "chatgpt-direct-token");
184
+ assert.equal(result.accessToken, undefined);
185
+ assert.equal(result.refreshed, false);
186
+ assert.deepEqual(await runtime.credentials.read(providerId), credential);
187
+ }
188
+ }
189
+ });
190
+
191
+ test("a concurrent switch to direct ChatGPT login is rechecked under the credential lock", async () => {
192
+ const runtime = fakeRuntime(oauth("rejected", NOW - 1), mustNotRefresh, { providerId: "openai" });
193
+ const modify = runtime.credentials.modify;
194
+ runtime.credentials.modify = async (id, update) => {
195
+ await modify(id, () => ({ ...oauth("direct-access", NOW - 1), scopes: ["chatgpt.tokens.use.direct"] }));
196
+ return modify(id, update);
197
+ };
198
+ const result = await resolveCodexUsageAuth(runtime, "openai-codex", { now: NOW, forceRefresh: true });
199
+ assert.equal(result.unsupportedReason, "chatgpt-direct-token");
200
+ assert.equal(result.accessToken, undefined);
201
+ assert.equal(result.refreshed, false);
202
+ });
203
+
204
+ test("the legacy reader reports direct ChatGPT usage as unsupported without calling the Codex backend", async () => {
205
+ const source = await readFile(new URL("../bin/pi-webui.mjs", import.meta.url), "utf8");
206
+ const start = source.indexOf("async function getOpenAICodexUsageCredentials(");
207
+ const end = source.indexOf("const getOpenAICodexUsageStatus = createCodexUsageReader", start);
208
+ assert.ok(start >= 0 && end > start);
209
+ for (const providerId of ["openai", "openai-codex"]) {
210
+ const runtime = fakeRuntime({ ...oauth("direct-access", NOW - 1), scopes: ["chatgpt.tokens.use.direct"] }, mustNotRefresh, { providerId });
211
+ const status = vm.runInNewContext(`${source.slice(start, end)}\ngetLegacyOpenAICodexUsageStatus;`, {
212
+ authContext: async () => ({ modelRuntime: runtime }),
213
+ CODEX_USAGE_DIRECT_TOKEN_MESSAGE,
214
+ codexUsageLoginGuidance,
215
+ resolveCodexUsageAuth,
216
+ OPENAI_CODEX_PROVIDER_ID: "openai-codex",
217
+ makeHttpError: (statusCode, message) => Object.assign(new Error(message), { statusCode }),
218
+ fetch: () => assert.fail("direct ChatGPT credentials must not reach the Codex backend"),
219
+ });
220
+ for (const forceRefresh of [false, true]) {
221
+ await assert.rejects(status({ forceRefresh }), (error) => error.statusCode === 501 && error.message === CODEX_USAGE_DIRECT_TOKEN_MESSAGE);
222
+ }
223
+ }
224
+ });
@@ -0,0 +1,124 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:http";
4
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
10
+
11
+ const packageRoot = fileURLToPath(new URL("../", import.meta.url));
12
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-codex-usage-http-"));
13
+ const children = [];
14
+ const legacyRequests = [];
15
+ const legacy = createServer((req, res) => {
16
+ legacyRequests.push(req.headers.authorization);
17
+ res.writeHead(200, { "content-type": "application/json" });
18
+ res.end(JSON.stringify({ plan_type: "plus", rate_limit: { primary_window: { used_percent: 8, limit_window_seconds: 18000 } }, accountId: "fixture-private-account", accessToken: "fixture-private-token" }));
19
+ });
20
+ await new Promise((resolve) => legacy.listen(0, "127.0.0.1", resolve));
21
+
22
+ async function freePort() {
23
+ const server = createServer();
24
+ await new Promise((resolve, reject) => server.once("error", reject).listen(0, "127.0.0.1", resolve));
25
+ const port = server.address().port;
26
+ await new Promise((resolve) => server.close(resolve));
27
+ return port;
28
+ }
29
+
30
+ async function request(port, pathname, method = "GET") {
31
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, { method, signal: AbortSignal.timeout(10_000) });
32
+ return { status: response.status, body: await response.json() };
33
+ }
34
+
35
+ async function start(name, codex, credentials = {}) {
36
+ const agentDir = path.join(root, name, "agent");
37
+ await mkdir(agentDir, { recursive: true });
38
+ await writeFile(path.join(agentDir, "auth.json"), JSON.stringify(credentials));
39
+ const log = path.join(root, name, "codex.jsonl");
40
+ const port = await freePort();
41
+ // Omit --cwd so this harness needs no Pi child or model turn.
42
+ const child = spawn(process.execPath, [path.join(packageRoot, "bin", "pi-webui.mjs"), "--host", "127.0.0.1", "--port", String(port), "--pi", path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs")], {
43
+ detached: process.platform !== "win32",
44
+ stdio: ["ignore", "pipe", "pipe"],
45
+ env: {
46
+ ...process.env,
47
+ NODE_ENV: "test",
48
+ PI_CODING_AGENT_DIR: agentDir,
49
+ PI_WEBUI_SETTINGS_FILE: path.join(root, name, "settings.json"),
50
+ PI_WEBUI_RPC_SUPERVISOR: "0",
51
+ PI_WEBUI_UPDATE_TEST_HOME: path.join(root, "coordination"),
52
+ PI_WEBUI_CODEX_BIN: codex,
53
+ PI_WEBUI_CODEX_USAGE_URL: `http://127.0.0.1:${legacy.address().port}/usage`,
54
+ FAKE_CODEX_MODE: "success",
55
+ FAKE_CODEX_LOG: log,
56
+ },
57
+ });
58
+ children.push(child);
59
+ let output = "";
60
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (chunk) => { output = (output + chunk.toString()).slice(-65536); });
61
+ let ready = false;
62
+ for (let attempt = 0; attempt < 100 && child.exitCode === null; attempt++) {
63
+ try { if ((await request(port, "/api/health")).status === 200) { ready = true; break; } } catch {}
64
+ await delay(100);
65
+ }
66
+ assert.ok(ready, `isolated WebUI should start\n${output}`);
67
+ return { child, port, log };
68
+ }
69
+
70
+ async function stop(server) {
71
+ if (server.child.exitCode !== null) return;
72
+ try { await request(server.port, "/api/shutdown", "POST"); } catch {}
73
+ for (let attempt = 0; attempt < 100 && server.child.exitCode === null; attempt++) await delay(50);
74
+ terminateProcessTree(server.child, "SIGKILL");
75
+ }
76
+
77
+ async function launches(log) {
78
+ return (await readFile(log, "utf8")).split("\n").filter(Boolean).map(JSON.parse).filter((entry) => entry.kind === "start");
79
+ }
80
+
81
+ try {
82
+ const cli = await start("cli", path.join(packageRoot, "tests", "fixtures", "fake-codex-app-server.mjs"));
83
+ const [first, simultaneous] = await Promise.all([request(cli.port, "/api/codex-usage"), request(cli.port, "/api/codex-usage")]);
84
+ assert.equal(first.status, 200);
85
+ assert.equal(simultaneous.status, 200);
86
+ assert.equal(first.body.data.source, "codex-cli");
87
+ assert.equal(first.body.data.selected.primary.usedPercent, 25);
88
+ assert.equal(first.body.data.selected.secondary.usedPercent, 42);
89
+ assert.doesNotMatch(JSON.stringify(first.body), /private-|fixture-.*secret|email|accessToken|accountId/);
90
+ assert.equal((await launches(cli.log)).length, 1, "concurrent HTTP requests must share one CLI process");
91
+ await request(cli.port, "/api/codex-usage");
92
+ assert.equal((await launches(cli.log)).length, 1, "normal reads use the successful cache");
93
+ assert.equal((await request(cli.port, "/api/codex-usage?refresh=1")).status, 200);
94
+ assert.equal((await launches(cli.log)).length, 2, "explicit refresh bypasses the completed cache");
95
+ assert.equal(legacyRequests.length, 0, "CLI success must not touch the legacy endpoint");
96
+ await stop(cli);
97
+
98
+ const credential = { type: "oauth", access: "fixture-legacy-access", refresh: "fixture-legacy-refresh", expires: Date.now() + 60 * 60 * 1000, accountId: "fixture-legacy-account" };
99
+ const fallback = await start("fallback", path.join(root, "missing-codex.exe"), { "openai-codex": credential });
100
+ const legacyResult = await request(fallback.port, "/api/codex-usage");
101
+ assert.equal(legacyResult.status, 200);
102
+ assert.equal(legacyResult.body.data.source, "chatgpt.com");
103
+ assert.equal(legacyResult.body.data.selected.primary.usedPercent, 8);
104
+ assert.match(legacyResult.body.data.sourceNotice, /legacy Codex login/);
105
+ assert.deepEqual(legacyRequests, ["Bearer fixture-legacy-access"]);
106
+ assert.doesNotMatch(JSON.stringify(legacyResult.body), /fixture-legacy|fixture-private/);
107
+ await stop(fallback);
108
+
109
+ const unavailable = await start("unavailable", path.join(root, "missing-codex.exe"));
110
+ const error = await request(unavailable.port, "/api/codex-usage");
111
+ assert.equal(error.status, 503);
112
+ assert.match(error.body.error, /Codex CLI was not found/);
113
+ assert.match(error.body.error, /legacy Codex usage fallback/);
114
+ assert.doesNotMatch(error.body.error, /stack|fixture-|auth\.json|AppData/);
115
+ await stop(unavailable);
116
+ console.log("codex-usage-http.test.mjs passed");
117
+ } finally {
118
+ for (const child of children) terminateProcessTree(child, "SIGKILL");
119
+ await new Promise((resolve) => legacy.close(resolve));
120
+ for (let attempt = 0; attempt < 20; attempt++) {
121
+ try { await rm(root, { recursive: true, force: true }); break; }
122
+ catch (error) { if (attempt === 19 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error.code)) throw error; await delay(100); }
123
+ }
124
+ }