@firstpick/pi-package-webui 0.10.9 → 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.
Files changed (52) hide show
  1. package/DEVELOPMENT.md +42 -2
  2. package/README.md +9 -3
  3. package/TECHNICAL.md +23 -1
  4. package/bin/pi-webui.mjs +72 -25
  5. package/lib/codex-cli-usage.mjs +232 -0
  6. package/lib/codex-usage-auth.mjs +39 -3
  7. package/lib/codex-usage-source.mjs +36 -0
  8. package/package.json +14 -8
  9. package/public/app.js +56 -24
  10. package/public/codex-speed-mode.mjs +36 -0
  11. package/public/index.html +6 -5
  12. package/public/service-worker.js +2 -1
  13. package/public/theme-contract.mjs +1 -1
  14. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  15. package/tests/codex-cli-usage.test.mjs +189 -0
  16. package/tests/codex-fast-mode-static.test.mjs +12 -11
  17. package/tests/codex-speed-mode-browser-state.test.mjs +149 -0
  18. package/tests/codex-speed-mode.test.mjs +36 -0
  19. package/tests/codex-usage-auth.test.mjs +168 -9
  20. package/tests/codex-usage-http.test.mjs +124 -0
  21. package/tests/codex-usage-source.test.mjs +145 -0
  22. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  23. package/tests/control-visibility-static.test.mjs +2 -2
  24. package/tests/controls-layout-static.test.mjs +2 -2
  25. package/tests/events-tree-context-menu-static.test.mjs +2 -2
  26. package/tests/fast-mode-client-static.test.mjs +1 -1
  27. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  28. package/tests/file-viewer-image-static.test.mjs +2 -2
  29. package/tests/fixtures/fake-codex-app-server.mjs +61 -0
  30. package/tests/fixtures/fake-pi.mjs +18 -8
  31. package/tests/guided-git-activation-static.test.mjs +2 -2
  32. package/tests/guided-git-fallback-ui-static.test.mjs +2 -2
  33. package/tests/host-peer-dependencies.test.mjs +24 -0
  34. package/tests/http-endpoints-harness.test.mjs +60 -0
  35. package/tests/intercom-conversation-viewer-static.test.mjs +2 -2
  36. package/tests/main-output-loading-static.test.mjs +2 -2
  37. package/tests/middle-button-drag-scroll-static.test.mjs +2 -2
  38. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  39. package/tests/mobile-foundation-static.test.mjs +2 -2
  40. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  41. package/tests/open-issue-wizard-static.test.mjs +1 -1
  42. package/tests/optional-feature-prompt-impact-static.test.mjs +2 -2
  43. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  44. package/tests/prompt-input-vertical-scroll-static.test.mjs +2 -2
  45. package/tests/questionnaire-dialog.test.mjs +2 -2
  46. package/tests/session-sampling-ui-static.test.mjs +2 -2
  47. package/tests/side-panel-section-height-removal-static.test.mjs +2 -2
  48. package/tests/subagent-observability-static.test.mjs +2 -2
  49. package/tests/syntax-highlighting-static.test.mjs +2 -2
  50. package/tests/theme-contract.test.mjs +10 -3
  51. package/tests/theme-customizer-static.test.mjs +1 -1
  52. package/tests/windows-drive-cwd-picker-static.test.mjs +2 -2
@@ -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
+ });
@@ -28,34 +28,35 @@ assert.match(optionalFeatureCatalog, /\["codexFastMode", "@firstpick\/pi-extensi
28
28
 
29
29
  assert.match(server, /const OPTIONAL_FEATURE_PACKAGES = new Map\(OPTIONAL_FEATURE_CATALOG/, "server should derive Fast-mode installation from the shared Optional Features catalog");
30
30
  assert.match(server, /CODEX_FAST_MODE_STATUS_KEY = "codex-fast-mode"[\s\S]*?CODEX_FAST_MODE_COMMAND_NAME = "fast-mode"/, "server should use the extension-owned status and command contracts");
31
- assert.match(server, /function codexFastModeStatusState\(statusText\)[\s\S]*?text !== "on" && text !== "off"[\s\S]*?known: true, enabled: text === "on"/, "server should accept only exact published on/off states");
31
+ assert.match(server, /function codexFastModeStatusState\(statusText\)[\s\S]*?codexSpeedModeFromStatus\(stripAnsi\(statusText\)\)/, "server should use the tested exact status parser");
32
32
  assert.match(server, /function codexFastModeSnapshot\(tab, patch = \{\}\)[\s\S]*?extensionStatusMap\(tab\)\.get\(CODEX_FAST_MODE_STATUS_KEY\)/, "server snapshots should come from remembered extension status");
33
- assert.match(server, /async function codexFastModeFeatureData[\s\S]*?codexFastModeSnapshot\(tab\)[\s\S]*?tabHasActiveOutput\(tab\)[\s\S]*?CODEX_FAST_MODE_CREDIT_NOTICE/, "GET state should be tab-scoped, extension-owned, busy-aware, and disclose credit use");
34
- assert.match(server, /async function waitForCodexFastModeStatus\(tab, desired\)[\s\S]*?snapshot\.statusKnown && snapshot\.enabled === desired[\s\S]*?makeHttpError\(409,[\s\S]*?did not confirm/, "server should require bounded authoritative status confirmation");
35
- assert.match(server, /async function setCodexFastMode[\s\S]*?typeof body\?\.enabled !== "boolean"[\s\S]*?feature\.busy[\s\S]*?type: "prompt", message: `\/\$\{feature\.commandName\} \$\{desired \? "on" : "off"\}`[\s\S]*?waitForCodexFastModeStatus\(tab, desired\)[\s\S]*?requested: desired/, "PUT should require explicit intent, reject busy tabs, invoke the extension, and return only confirmed state");
33
+ assert.match(server, /async function codexFastModeFeatureData[\s\S]*?codexFastModeSnapshot\(tab\)[\s\S]*?tabHasActiveOutput\(tab\)[\s\S]*?ultrafastModelEligible:[\s\S]*?CODEX_FAST_MODE_CREDIT_NOTICE/, "GET state should be tab-scoped, extension-owned, busy-aware, model-gated, and disclose credit use");
34
+ assert.match(server, /async function waitForCodexFastModeStatus\(tab, desired\)[\s\S]*?snapshot\.statusKnown && snapshot\.mode === desired[\s\S]*?makeHttpError\(409,[\s\S]*?did not confirm/, "server should require bounded exact-mode confirmation");
35
+ assert.match(server, /async function setCodexFastMode[\s\S]*?codexSpeedModeFromIntent\(body\)[\s\S]*?feature\.busy[\s\S]*?desired === "ultrafast" && !feature\.ultrafastModelEligible[\s\S]*?type: "prompt", message: `\/\$\{feature\.commandName\} \$\{argument\}`[\s\S]*?waitForCodexFastModeStatus\(tab, desired\)/, "PUT should validate intent, reject busy or ineligible tabs, invoke the extension, and require exact confirmed state");
36
36
  assert.doesNotMatch(server, /codexFastModeSnapshot\(tab, \{ enabled: desired/, "server must not infer effective Fast state from RPC success");
37
37
  assert.match(server, /url\.pathname === "\/api\/codex-fast-mode" && req\.method === "GET"[\s\S]*?url\.pathname === "\/api\/codex-fast-mode" && req\.method === "PUT"/, "server should expose GET and PUT routes");
38
38
 
39
39
  assert.match(html, /<label for="fastOutputModeSelect">Compact mode \(Experimental\)<\/label>[\s\S]*?<option value="compact-v1">Compact<\/option>/, "legacy output processing should be presented as Compact mode while retaining compact-v1");
40
40
  assert.doesNotMatch(html, /<label for="fastOutputModeSelect">Fast mode/, "legacy output processing should no longer be presented as Fast mode");
41
- assert.match(html, /data-side-panel-section="codex-usage"[\s\S]*?id="codexUsageBox"[\s\S]*?class="control-field codex-fast-mode-control"[\s\S]*?class="codex-fast-mode-row"[\s\S]*?id="codexFastModeLabel"[\s\S]*?id="codexFastModeSelect"[\s\S]*?<option value="normal">Normal<\/option>[\s\S]*?<option value="fast">Fast<\/option>[\s\S]*?id="setCodexFastModeButton"[\s\S]*?id="codexFastModeStatus"/, "Codex Usage should render before the compact session Fast-mode row");
41
+ assert.match(html, /data-side-panel-section="codex-usage"[\s\S]*?id="codexUsageBox"[\s\S]*?class="control-field codex-fast-mode-control"[\s\S]*?class="codex-fast-mode-row"[\s\S]*?id="codexFastModeLabel"[\s\S]*?id="codexFastModeSelect"[\s\S]*?<option value="normal">Normal<\/option>[\s\S]*?<option value="fast">Fast<\/option>[\s\S]*?<option value="ultrafast" disabled>Ultrafast<\/option>[\s\S]*?id="setCodexFastModeButton"[\s\S]*?id="codexFastModeStatus"/, "Codex Usage should render before the compact session Fast-mode row");
42
42
  assert.match(styles, /\.codex-fast-mode-control \{[\s\S]*?margin-top: 0\.58rem[\s\S]*?padding: 0\.48rem 0\.55rem[\s\S]*?\.codex-fast-mode-row \{[\s\S]*?grid-template-columns: minmax\(0, 1fr\) minmax\(6\.5rem, 8rem\) auto/, "Codex Fast mode should use a compact horizontal control surface");
43
- assert.match(app, /function codexFastModeStatusText\(\)[\s\S]*?return `\$\{codexFastModeState\.enabled \? "Fast" : "Normal"\} · This tab`;/, "ordinary Fast-mode status should stay concise");
43
+ assert.match(app, /function codexFastModeStatusText\(\)[\s\S]*?codexSpeedModeLabel\(codexFastModeState\.mode\)[\s\S]*?return `\$\{label\} · This tab`;/, "mode status should distinguish all three preferences concisely");
44
44
 
45
45
  assert.match(app, /id: "codexFastMode"[\s\S]*?packageName: "@firstpick\/pi-extension-codex-fast-mode"[\s\S]*?capabilityLabel: "\/fast-mode"/, "browser Optional Features should catalog Fast mode");
46
46
  assert.match(app, /OPTIONAL_FEATURE_DISABLE_PREREQUISITES = new Map\([\s\S]*?\["codexFastMode", \(\) => disableCodexFastModeIntegration\(\)\]/, "browser should register disable-off-first behavior");
47
47
  assert.match(app, /if \(disabled\) \{[\s\S]*?OPTIONAL_FEATURE_DISABLE_PREREQUISITES\.get\(feature\.id\)[\s\S]*?await turnOff\(\)[\s\S]*?setOptionalFeatureDisabled\(feature\.id, disabled\)/, "Optional Features Disable should abort before hiding integration if turn-off fails");
48
- assert.match(app, /function applyCodexFastModeStatus\(statusText\)[\s\S]*?status !== "on" && status !== "off"[\s\S]*?enabled: status === "on"[\s\S]*?statusKnown: true/, "browser should consume only exact extension status values");
48
+ assert.match(app, /function applyCodexFastModeStatus\(statusText\)[\s\S]*?codexSpeedModeFromStatus\(statusText\)[\s\S]*?if \(mode === null\) return false[\s\S]*?enabled: mode !== "normal"[\s\S]*?statusKnown: true/, "browser should consume only exact extension status values");
49
49
  assert.match(app, /async function refreshCodexFastMode\(tabContext = activeTabContext\(\)\)[\s\S]*?api\("\/api\/codex-fast-mode", \{ tabId: tabContext\.tabId \}\)[\s\S]*?!featureEnabled && data\.available[\s\S]*?enabled: false[\s\S]*?isCurrentTabContext\(tabContext\)/, "browser status refresh should stay tab-scoped and disarm restored branches while the feature is hidden");
50
- assert.match(app, /async function applyCodexFastMode\(\)[\s\S]*?body: \{ enabled \}, tabId: tabContext\.tabId[\s\S]*?1\.5x faster[\s\S]*?may spend 2x credits[\s\S]*?2\.5x/, "browser should apply explicit state and disclose conditional speed/credit multipliers");
50
+ assert.match(app, /async function applyCodexFastMode\(\)[\s\S]*?await appConfirm\([\s\S]*?8x Standard included usage[\s\S]*?6x purchased-credit[\s\S]*?if \(!confirmed[\s\S]*?body: \{ mode \}, tabId: tabContext\.tabId/, "browser should confirm Ultrafast costs before applying explicit mode intent");
51
51
  assert.match(app, /async function disableCodexFastModeIntegration\(\)[\s\S]*?tabs\.filter[\s\S]*?Promise\.all\(tabIds\.map[\s\S]*?data\.busy[\s\S]*?enabled: false[\s\S]*?codexFastModeConfirmedOff\(response\.data\)/, "browser-global Disable should preflight every live tab and require each mutation to confirm off");
52
52
  assert.match(app, /refreshNaturalConversationMode\(tabContext\),[\s\S]*?refreshCodexFastMode\(tabContext\),/, "tab refreshes should reload branch-scoped Fast-mode state");
53
53
  assert.match(app, /statusKey === CODEX_FAST_MODE_STATUS_KEY[\s\S]*?applyCodexFastModeStatus\(request\.statusText\)/, "extension status events should refresh the active-tab selector");
54
54
 
55
55
  assert.match(technical, /## Normal and compact output[\s\S]*?select \*\*Compact\*\*[\s\S]*?`compact-v1`/, "technical reference should document Compact mode with the stable identifier");
56
- assert.match(development, /### Codex subscription Fast mode[\s\S]*?service_tier: "priority"[\s\S]*?1\.5× faster[\s\S]*?2× Standard credits[\s\S]*?2\.5×/, "development guide should document Fast-mode integration and cost semantics");
56
+ assert.match(development, /### Codex subscription Fast mode[\s\S]*?service_tier: "priority"[\s\S]*?service_tier: "ultrafast"[\s\S]*?8× Standard included usage[\s\S]*?6×/, "development guide should document both tiers and cost semantics");
57
+ assert.match(technical, /Normal \/ Fast \/ Ultrafast[\s\S]*?Pro \$500/, "technical reference should document the third mode and subscription eligibility");
57
58
  // Intent preserved: browser-asset changes must advance the coherent cache tuple.
58
- assert.match(serviceWorker, /pi-webui-pwa-v155/, "PWA cache identity should be bumped for changed browser assets");
59
- assert.match(html, /data-app-src="\/app\.js\?v=184"/, "browser module URL should be cache-busted for Fast-mode wiring");
59
+ assert.match(serviceWorker, /pi-webui-pwa-v156[\s\S]*?"\/codex-speed-mode\.mjs"/, "PWA should refresh and cache the shared mode helper");
60
+ assert.match(html, /data-app-src="\/app\.js\?v=185"/, "browser module URL should be cache-busted for speed-mode wiring");
60
61
 
61
62
  console.log("codex-fast-mode-static.test.mjs passed");
@@ -0,0 +1,149 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import vm from "node:vm";
4
+ import * as modes from "../public/codex-speed-mode.mjs";
5
+
6
+ const source = await readFile(new URL("../public/app.js", import.meta.url), "utf8");
7
+ const start = source.indexOf("// Codex subscription Fast mode is owned");
8
+ const end = source.indexOf("function scheduleRefreshCodexUsage", start);
9
+ assert.ok(start >= 0 && end > start, "execute the actual browser speed-control implementation");
10
+ const controlSource = source.slice(start, end);
11
+
12
+ function harness({ confirm = true, eligible = true, enabledFeature = true } = {}) {
13
+ const calls = [];
14
+ const confirmations = [];
15
+ const events = [];
16
+ const ultrafastOption = { disabled: true };
17
+ const select = { value: "normal", disabled: true, querySelector: () => ultrafastOption };
18
+ let currentTab = "tab-one";
19
+ const data = (mode) => ({
20
+ available: true, statusKnown: true, enabled: mode !== "normal", mode, busy: false,
21
+ model: { provider: "openai-codex", id: eligible ? "gpt-6-astra" : "gpt-6-sol" },
22
+ modelEligible: true, ultrafastModelEligible: eligible, creditNotice: "Higher usage applies.",
23
+ });
24
+ const tabModes = new Map([["tab-one", "normal"], ["tab-two", "normal"]]);
25
+ const context = vm.createContext({
26
+ ...modes,
27
+ elements: { codexFastModeSelect: select, setCodexFastModeButton: {}, codexFastModeStatus: { classList: { toggle() {} } } },
28
+ isOptionalFeatureEnabled: () => enabledFeature,
29
+ optionalFeatureUnavailableMessage: () => "Disabled",
30
+ optionalFeatureAvailability: {},
31
+ activeTabContext: () => ({ tabId: currentTab }),
32
+ isCurrentTabContext: (tab) => tab.tabId === currentTab,
33
+ tabs: [{ id: "tab-one", running: true }, { id: "tab-two", running: true }],
34
+ activeTabId: "tab-one",
35
+ currentState: { model: { provider: "openai-codex", id: "gpt-6-sol" } },
36
+ normalizeSelectedModel: (model) => model,
37
+ modelStateKey: (model) => `${model?.provider}/${model?.id}`,
38
+ renderStatus() {},
39
+ requestGitFooterWebuiPayload() {},
40
+ queueMicrotask,
41
+ async appConfirm(options) {
42
+ confirmations.push(options);
43
+ return typeof confirm === "function" ? confirm(() => { currentTab = "tab-two"; }) : confirm;
44
+ },
45
+ async api(path, options) {
46
+ calls.push({ path, options });
47
+ if (options.method === "PUT") tabModes.set(options.tabId, modes.codexSpeedModeFromIntent(options.body));
48
+ return { data: data(tabModes.get(options.tabId)) };
49
+ },
50
+ addEvent(message, level) { events.push({ message, level }); },
51
+ });
52
+ vm.runInContext(controlSource, context);
53
+ const modelStart = source.indexOf("function applyOptimisticModelSelection(");
54
+ const modelEnd = source.indexOf("function applyOptimisticThinkingSelection(", modelStart);
55
+ assert.ok(modelStart >= 0 && modelEnd > modelStart);
56
+ vm.runInContext(source.slice(modelStart, modelEnd), context);
57
+ context.applyCodexFastModeData(data("normal"));
58
+ vm.runInContext("codexFastModeLoaded = true", context);
59
+ context.renderCodexFastModeControl();
60
+ return { context, calls, confirmations, events, select, tabModes, ultrafastOption, data, setEligible(value) { eligible = value; } };
61
+ }
62
+
63
+ {
64
+ const h = harness();
65
+ assert.equal(h.context.applyCodexFastModeStatus("ultrafast"), true);
66
+ assert.equal(h.select.value, "ultrafast");
67
+ assert.equal(h.context.codexFastModeStatusText(), "Ultrafast · This tab");
68
+ assert.equal(h.context.applyCodexFastModeStatus("ultrafast now"), false);
69
+ assert.equal(h.select.value, "ultrafast");
70
+ assert.equal(h.context.codexFastModeConfirmedOff({ statusKnown: true, mode: "ultrafast", enabled: false }), false);
71
+ assert.equal(h.context.codexFastModeConfirmedOff({ statusKnown: true, enabled: false }), true);
72
+ }
73
+ {
74
+ const h = harness({ confirm: false });
75
+ h.select.value = "ultrafast";
76
+ await h.context.applyCodexFastMode();
77
+ assert.equal(h.confirmations.length, 1);
78
+ assert.match(h.confirmations[0].summary, /8x.*6x/);
79
+ assert.equal(h.calls.length, 0, "cancelled cost confirmation must not mutate the extension");
80
+ assert.equal(h.select.value, "normal");
81
+ }
82
+ {
83
+ const h = harness();
84
+ h.select.value = "ultrafast";
85
+ await h.context.applyCodexFastMode();
86
+ assert.equal(h.confirmations.length, 1);
87
+ assert.equal(h.calls.length, 1);
88
+ assert.equal(h.calls[0].options.body.mode, "ultrafast");
89
+ assert.equal(h.select.value, "ultrafast");
90
+ h.select.value = "fast";
91
+ await h.context.applyCodexFastMode();
92
+ assert.equal(h.confirmations.length, 1, "ordinary Fast selection does not require the Ultrafast prompt");
93
+ assert.equal(h.calls[1].options.body.mode, "fast");
94
+ assert.equal(h.select.value, "fast");
95
+ }
96
+ {
97
+ const h = harness({ confirm: (switchTab) => { switchTab(); return true; } });
98
+ h.select.value = "ultrafast";
99
+ await h.context.applyCodexFastMode();
100
+ assert.equal(h.calls.length, 0, "changing tabs during cost confirmation must cancel the mutation");
101
+ }
102
+ {
103
+ const h = harness({ eligible: false });
104
+ assert.equal(h.ultrafastOption.disabled, true);
105
+ h.select.value = "ultrafast";
106
+ await h.context.applyCodexFastMode();
107
+ assert.equal(h.calls.length, 0);
108
+ assert.equal(h.confirmations.length, 0);
109
+ h.context.applyCodexFastModeData(h.data("ultrafast"));
110
+ assert.equal(h.context.codexFastModeStatusText(), "Ultrafast · Inactive for current model");
111
+ h.select.value = "normal";
112
+ await h.context.applyCodexFastMode();
113
+ assert.equal(h.calls[0].options.body.mode, "normal", "inactive Ultrafast must remain disarmable");
114
+ }
115
+ {
116
+ const h = harness();
117
+ h.tabModes.set("tab-one", "ultrafast");
118
+ h.tabModes.set("tab-two", "fast");
119
+ await h.context.disableCodexFastModeIntegration();
120
+ const mutations = h.calls.filter((call) => call.options.method === "PUT");
121
+ assert.equal(mutations.length, 2);
122
+ assert.ok(mutations.every((call) => call.options.body.enabled === false));
123
+ assert.equal(h.tabModes.get("tab-one"), "normal");
124
+ assert.equal(h.tabModes.get("tab-two"), "normal");
125
+ }
126
+ for (const options of [{ enabledFeature: false }, {}]) {
127
+ const h = harness(options);
128
+ if (options.enabledFeature !== false) h.context.applyCodexFastModeData({ ...h.data("normal"), busy: true });
129
+ h.select.value = "ultrafast";
130
+ await h.context.applyCodexFastMode();
131
+ assert.equal(h.calls.length, 0, "hidden or busy controls must not request a mode change");
132
+ }
133
+ {
134
+ const h = harness({ eligible: false });
135
+ assert.equal(h.ultrafastOption.disabled, true);
136
+ h.setEligible(true);
137
+ const refresh = h.context.refreshCodexFastMode;
138
+ let refreshed;
139
+ h.context.refreshCodexFastMode = (...args) => {
140
+ refreshed = refresh(...args);
141
+ return refreshed;
142
+ };
143
+ h.context.applyOptimisticModelSelection({ provider: "openai-codex", id: "gpt-6-astra" });
144
+ assert.ok(refreshed, "model selection must schedule the speed-eligibility refresh");
145
+ await refreshed;
146
+ assert.equal(h.ultrafastOption.disabled, false, "selecting Astra should refresh Ultrafast eligibility without reloading the tab");
147
+ assert.equal(h.calls.at(-1).path, "/api/codex-fast-mode");
148
+ }
149
+ console.log("codex-speed-mode-browser-state.test.mjs passed");
@@ -0,0 +1,36 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ codexSpeedModeFromData,
4
+ codexSpeedModeFromIntent,
5
+ codexSpeedModeFromStatus,
6
+ codexSpeedModeLabel,
7
+ isCodexSpeedMode,
8
+ } from "../public/codex-speed-mode.mjs";
9
+
10
+ for (const [status, mode] of [["off", "normal"], ["on", "fast"], ["ultrafast", "ultrafast"]]) {
11
+ assert.equal(codexSpeedModeFromStatus(status), mode);
12
+ assert.equal(codexSpeedModeFromStatus(` ${status.toUpperCase()} `), mode);
13
+ assert.equal(codexSpeedModeFromIntent({ mode }), mode);
14
+ assert.equal(codexSpeedModeFromIntent({ mode, enabled: mode !== "normal" }), mode);
15
+ assert.equal(codexSpeedModeFromData({ mode, enabled: mode !== "normal", statusKnown: true }), mode);
16
+ assert.equal(isCodexSpeedMode(mode), true);
17
+ }
18
+ for (const value of [undefined, null, "", "fast", "normal", "Fast mode: on", "on now", "ultra-fast", {}, 1]) {
19
+ assert.equal(codexSpeedModeFromStatus(value), null);
20
+ }
21
+ assert.equal(codexSpeedModeFromIntent({ enabled: true }), "fast");
22
+ assert.equal(codexSpeedModeFromIntent({ enabled: false }), "normal");
23
+ for (const body of [{}, undefined, null, { enabled: "yes" }, { mode: "turbo" }, { mode: null, enabled: true },
24
+ { mode: "ultrafast", enabled: false }, { mode: "normal", enabled: true }, { mode: "fast", enabled: "yes" }]) {
25
+ assert.throws(() => codexSpeedModeFromIntent(body), TypeError);
26
+ }
27
+ assert.equal(codexSpeedModeFromData({ enabled: true, statusKnown: true }), "fast");
28
+ assert.equal(codexSpeedModeFromData({ enabled: false, statusKnown: true }), "normal");
29
+ assert.equal(codexSpeedModeFromData({ enabled: true, statusKnown: false }), null);
30
+ assert.equal(codexSpeedModeFromData({ mode: "turbo", enabled: true, statusKnown: true }), null);
31
+ assert.equal(codexSpeedModeFromData(undefined), null);
32
+ assert.equal(codexSpeedModeLabel("normal"), "Normal");
33
+ assert.equal(codexSpeedModeLabel("fast"), "Fast");
34
+ assert.equal(codexSpeedModeLabel("ultrafast"), "Ultrafast");
35
+ assert.equal(codexSpeedModeLabel(null), "Unknown");
36
+ console.log("codex-speed-mode.test.mjs passed");
@@ -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
+ });