@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/DEVELOPMENT.md +30 -0
- package/README.md +7 -3
- package/TECHNICAL.md +16 -0
- package/bin/pi-webui.mjs +46 -9
- package/lib/codex-cli-usage.mjs +232 -0
- package/lib/codex-usage-auth.mjs +39 -3
- package/lib/codex-usage-source.mjs +36 -0
- package/package.json +3 -3
- package/public/app.js +8 -0
- package/public/theme-contract.mjs +1 -1
- package/tests/codex-cli-usage.test.mjs +189 -0
- package/tests/codex-usage-auth.test.mjs +168 -9
- package/tests/codex-usage-http.test.mjs +124 -0
- package/tests/codex-usage-source.test.mjs +145 -0
- package/tests/fixtures/fake-codex-app-server.mjs +61 -0
- package/tests/http-endpoints-harness.test.mjs +8 -0
- package/tests/theme-contract.test.mjs +10 -3
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
import { CodexCliUsageError } from "../lib/codex-cli-usage.mjs";
|
|
6
|
+
import { createCodexUsageReader } from "../lib/codex-usage-source.mjs";
|
|
7
|
+
|
|
8
|
+
const unavailable = () => { throw new CodexCliUsageError("CODEX_CLI_NOT_FOUND", "Codex CLI was not found."); };
|
|
9
|
+
|
|
10
|
+
test("CLI usage has precedence and does not touch Pi authentication", async () => {
|
|
11
|
+
const snapshot = { source: "codex-cli", selected: { primary: { usedPercent: 25 } } };
|
|
12
|
+
const reader = createCodexUsageReader({ readCli: async () => snapshot, readLegacy: () => assert.fail("CLI success must not resolve Pi auth") });
|
|
13
|
+
assert.equal(await reader({ forceRefresh: true }), snapshot);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test("a compatible legacy login supplies an explicitly labelled fallback", async () => {
|
|
17
|
+
let received;
|
|
18
|
+
const reader = createCodexUsageReader({ readCli: unavailable, readLegacy: async (options) => { received = options; return { source: "chatgpt.com", selected: {} }; } });
|
|
19
|
+
const result = await reader({ forceRefresh: true });
|
|
20
|
+
assert.deepEqual(received, { forceRefresh: true });
|
|
21
|
+
assert.equal(result.source, "chatgpt.com");
|
|
22
|
+
assert.match(result.sourceNotice, /Pi's legacy Codex login/);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("concurrent polls coalesce and refresh bypasses only the completed cache", async () => {
|
|
26
|
+
let calls = 0;
|
|
27
|
+
let complete;
|
|
28
|
+
const pending = new Promise((resolve) => { complete = resolve; });
|
|
29
|
+
const reader = createCodexUsageReader({ readCli: async () => { calls++; return pending; }, readLegacy: () => assert.fail("must not fall back") });
|
|
30
|
+
const first = reader();
|
|
31
|
+
const second = reader({ forceRefresh: true });
|
|
32
|
+
assert.equal(calls, 1);
|
|
33
|
+
complete({ source: "codex-cli" });
|
|
34
|
+
assert.deepEqual(await first, await second);
|
|
35
|
+
await reader();
|
|
36
|
+
assert.equal(calls, 1);
|
|
37
|
+
await reader({ forceRefresh: true });
|
|
38
|
+
assert.equal(calls, 2);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("successful caches expire, while failures never enter the cache", async () => {
|
|
42
|
+
let now = 100;
|
|
43
|
+
let calls = 0;
|
|
44
|
+
const reader = createCodexUsageReader({ readCli: async () => ({ source: "codex-cli", count: ++calls }), readLegacy: unavailable, cacheMs: 30, now: () => now });
|
|
45
|
+
assert.equal((await reader()).count, 1);
|
|
46
|
+
now = 129;
|
|
47
|
+
assert.equal((await reader()).count, 1);
|
|
48
|
+
now = 130;
|
|
49
|
+
assert.equal((await reader()).count, 2);
|
|
50
|
+
let failures = 0;
|
|
51
|
+
const failing = createCodexUsageReader({ readCli: async () => { failures++; unavailable(); }, readLegacy: async () => { throw new Error("private-token"); } });
|
|
52
|
+
for (let index = 0; index < 2; index++) await assert.rejects(failing(), (error) => error.code === "CODEX_CLI_NOT_FOUND" && !error.message.includes("private-token"));
|
|
53
|
+
assert.equal(failures, 2);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("unexpected CLI errors and legacy exceptions never expose raw diagnostics", async () => {
|
|
57
|
+
const reader = createCodexUsageReader({ readCli: async () => { throw new Error("Bearer private-cli-token"); }, readLegacy: async () => { throw new Error("private-refresh-token"); } });
|
|
58
|
+
await assert.rejects(reader(), (error) => {
|
|
59
|
+
assert.equal(error.statusCode, 503);
|
|
60
|
+
assert.match(error.message, /legacy Codex usage fallback/);
|
|
61
|
+
assert.doesNotMatch(error.message, /private-|Bearer/);
|
|
62
|
+
return true;
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const serverSource = await readFile(new URL("../bin/pi-webui.mjs", import.meta.url), "utf8");
|
|
67
|
+
function serverUsageReader(readCli, fetchLegacy, resolveAuth) {
|
|
68
|
+
const start = serverSource.indexOf("function firstDefined(");
|
|
69
|
+
const end = serverSource.indexOf("const CLAUDE_USAGE_MONTHS", start);
|
|
70
|
+
assert.ok(start >= 0 && end > start);
|
|
71
|
+
return vm.runInNewContext(`${serverSource.slice(start, end)}\ngetOpenAICodexUsageStatus;`, {
|
|
72
|
+
Buffer, AbortController, setTimeout, clearTimeout,
|
|
73
|
+
createCodexUsageReader,
|
|
74
|
+
readCodexCliUsage: readCli,
|
|
75
|
+
fetch: fetchLegacy,
|
|
76
|
+
OPENAI_CODEX_PROVIDER_ID: "openai-codex",
|
|
77
|
+
OPENAI_CODEX_USAGE_ENDPOINT: "https://fixture.invalid/usage",
|
|
78
|
+
CODEX_USAGE_TIMEOUT_MS: 1000,
|
|
79
|
+
CODEX_USAGE_DIRECT_TOKEN_MESSAGE: "Direct ChatGPT login cannot supply legacy usage.",
|
|
80
|
+
codexUsageLoginGuidance: () => "Run /login.",
|
|
81
|
+
authContext: async () => ({ modelRuntime: {} }),
|
|
82
|
+
resolveCodexUsageAuth: resolveAuth,
|
|
83
|
+
makeHttpError: (statusCode, message) => Object.assign(new Error(message), { statusCode }),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
test("the server normalizes CLI weekly-only usage and records its source", async () => {
|
|
88
|
+
const reader = serverUsageReader(async () => ({ planType: "plus", rateLimits: { limitId: "codex", primary: null, secondary: { usedPercent: 42, windowDurationMins: 10080, resetsAt: 2_000_500_000 } } }), () => assert.fail("must not call legacy backend"), () => assert.fail("must not resolve Pi auth"));
|
|
89
|
+
const data = await reader();
|
|
90
|
+
assert.equal(data.source, "codex-cli");
|
|
91
|
+
assert.equal(data.auth.source, "codex-cli");
|
|
92
|
+
assert.equal(data.planType, "plus");
|
|
93
|
+
assert.equal(data.selected.primary, null);
|
|
94
|
+
assert.equal(data.selected.secondary.usedPercent, 42);
|
|
95
|
+
assert.equal(data.snapshots.length, 1);
|
|
96
|
+
assert.equal(data.selected.secondary.resetsAt, new Date(2_000_500_000 * 1000).toISOString());
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("the server retains legacy usage as a fallback with no CLI credentials involved", async () => {
|
|
100
|
+
let legacyCalls = 0;
|
|
101
|
+
const reader = serverUsageReader(unavailable, async (_url, options) => {
|
|
102
|
+
legacyCalls++;
|
|
103
|
+
assert.equal(options.headers.authorization, "Bearer fixture-legacy-token");
|
|
104
|
+
return { ok: true, text: async () => JSON.stringify({ plan_type: "plus", rate_limit: { primary_window: { used_percent: 12, limit_window_seconds: 18000 } } }) };
|
|
105
|
+
}, async () => ({ providerId: "openai-codex", accessToken: "fixture-legacy-token", credential: { type: "oauth", accountId: "fixture-account" } }));
|
|
106
|
+
const data = await reader();
|
|
107
|
+
assert.equal(legacyCalls, 1);
|
|
108
|
+
assert.equal(data.source, "chatgpt.com");
|
|
109
|
+
assert.equal(data.selected.primary.usedPercent, 12);
|
|
110
|
+
assert.match(data.sourceNotice, /legacy Codex login/);
|
|
111
|
+
assert.doesNotMatch(JSON.stringify(data), /fixture-legacy-token|fixture-account/);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("the server gives a sanitized combined error when CLI and direct-flow Pi fallback fail", async () => {
|
|
115
|
+
const reader = serverUsageReader(unavailable, () => assert.fail("direct-flow token must not reach backend"), async () => ({ unsupportedReason: "chatgpt-direct-token" }));
|
|
116
|
+
await assert.rejects(reader(), (error) => error.code === "CODEX_CLI_NOT_FOUND" && /legacy Codex usage fallback/.test(error.message));
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("the browser labels the usage account and redraws when source changes", async () => {
|
|
120
|
+
const source = await readFile(new URL("../public/app.js", import.meta.url), "utf8");
|
|
121
|
+
const signatureStart = source.indexOf("function codexUsageStructureSignature(");
|
|
122
|
+
const signatureEnd = source.indexOf("function updateCodexUsageValues(", signatureStart);
|
|
123
|
+
const renderStart = source.indexOf("function renderCodexUsage(");
|
|
124
|
+
const renderEnd = source.indexOf("async function refreshCodexUsage(", renderStart);
|
|
125
|
+
const nodes = [];
|
|
126
|
+
let rebuilds = 0;
|
|
127
|
+
const box = { replaceChildren: () => { nodes.length = 0; rebuilds++; }, classList: { toggle() {} }, append: (...items) => nodes.push(...items) };
|
|
128
|
+
const context = vm.createContext({
|
|
129
|
+
latestCodexUsage: { source: "codex-cli", planType: "plus" },
|
|
130
|
+
codexUsageLoading: false, codexUsageError: null, codexUsageRenderSignature: "",
|
|
131
|
+
elements: { codexUsageBox: box },
|
|
132
|
+
formatCodexPlanType: (value) => value,
|
|
133
|
+
codexUsageBuckets: () => [],
|
|
134
|
+
updateCodexUsageValues: () => true,
|
|
135
|
+
make: (_tag, _className, text) => ({ text, append() {} }),
|
|
136
|
+
});
|
|
137
|
+
vm.runInContext(`${source.slice(signatureStart, signatureEnd)}\n${source.slice(renderStart, renderEnd)}\nrenderCodexUsage();`, context);
|
|
138
|
+
assert.ok(nodes.some((node) => /Codex CLI account/.test(node.text)));
|
|
139
|
+
assert.ok(nodes.some((node) => /separate from Pi/.test(node.text)));
|
|
140
|
+
context.latestCodexUsage = { source: "chatgpt.com", planType: "plus", sourceNotice: "Showing fallback usage." };
|
|
141
|
+
vm.runInContext("renderCodexUsage()", context);
|
|
142
|
+
assert.equal(rebuilds, 2, "source changes must invalidate the structural cache");
|
|
143
|
+
assert.ok(nodes.some((node) => /Pi's legacy Codex login/.test(node.text)));
|
|
144
|
+
assert.ok(nodes.some((node) => node.text === "Showing fallback usage."));
|
|
145
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { appendFileSync } from "node:fs";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
const mode = process.env.FAKE_CODEX_MODE || "success";
|
|
6
|
+
const log = (entry) => {
|
|
7
|
+
if (process.env.FAKE_CODEX_LOG) appendFileSync(process.env.FAKE_CODEX_LOG, `${JSON.stringify(entry)}\n`);
|
|
8
|
+
};
|
|
9
|
+
log({ kind: "start", pid: process.pid, args: process.argv.slice(2) });
|
|
10
|
+
if (["hang", "stubborn", "tree"].includes(mode)) setInterval(() => {}, 1000);
|
|
11
|
+
if (mode === "tree") {
|
|
12
|
+
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
|
13
|
+
log({ kind: "descendant", pid: child.pid });
|
|
14
|
+
}
|
|
15
|
+
const send = (frame) => {
|
|
16
|
+
const bytes = Buffer.from(`${JSON.stringify(frame)}\n`);
|
|
17
|
+
if (mode === "fragmented") {
|
|
18
|
+
for (let start = 0; start < bytes.length; start += 7) process.stdout.write(bytes.subarray(start, start + 7));
|
|
19
|
+
} else process.stdout.write(bytes);
|
|
20
|
+
};
|
|
21
|
+
const primary = { usedPercent: 25, windowDurationMins: 300, resetsAt: 2_000_000_000 };
|
|
22
|
+
const secondary = { usedPercent: 42, windowDurationMins: 10080, resetsAt: 2_000_500_000 };
|
|
23
|
+
createInterface({ input: process.stdin }).on("line", (line) => {
|
|
24
|
+
const frame = JSON.parse(line);
|
|
25
|
+
log({ kind: "frame", ...frame });
|
|
26
|
+
if (!frame.method || frame.method === "initialized") return;
|
|
27
|
+
if (frame.method === "initialize") {
|
|
28
|
+
if (mode === "hang") return;
|
|
29
|
+
if (mode === "early-exit") { process.exit(7); return; }
|
|
30
|
+
if (mode === "malformed") { process.stdout.write("not JSON\n"); return; }
|
|
31
|
+
if (mode === "oversized") { process.stdout.write("x".repeat(1024 * 1024 + 1)); return; }
|
|
32
|
+
if (mode === "stderr-flood") { process.stderr.write("x".repeat(4 * 1024 * 1024 + 1)); return; }
|
|
33
|
+
send({ id: frame.id, result: { userAgent: "fixture" } });
|
|
34
|
+
if (mode === "server-request") send({ id: "server-auth-request", method: "account/chatgptAuthTokens/refresh", params: { reason: "expired" } });
|
|
35
|
+
send({ method: "account/updated", params: { email: "private-fixture@example.invalid", secret: "fixture-notification-secret" } });
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (frame.method === "account/read") {
|
|
39
|
+
const account = mode === "logged-out" ? null : mode === "api-key" ? { type: "apiKey" } : { type: "chatgpt", planType: "plus", email: "private-fixture@example.invalid", accountId: "private-account", accessToken: "fixture-access-secret" };
|
|
40
|
+
send({ id: frame.id, result: { account, requiresOpenaiAuth: true } });
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (frame.method === "account/rateLimits/read") {
|
|
44
|
+
if (mode === "rpc-error") {
|
|
45
|
+
process.stderr.write("Bearer fixture-stderr-secret\n");
|
|
46
|
+
send({ id: frame.id, error: { code: -32603, message: "upstream 401 Bearer fixture-error-secret", data: { refreshToken: "fixture-refresh-secret" } } });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const limits = mode === "empty" ? {} : { limitId: "codex", limitName: "Codex 漢字", primary: mode === "weekly-only" ? null : primary, secondary, credits: { hasCredits: true, unlimited: false, balance: "12.50", accessToken: "fixture-credit-secret" }, planType: "plus" };
|
|
50
|
+
send({ id: frame.id, result: {
|
|
51
|
+
rateLimits: limits,
|
|
52
|
+
rateLimitsByLimitId: mode === "multi-bucket" ? { codex: limits, extra: { limitId: "extra", primary: { ...primary, usedPercent: 70 } } } : null,
|
|
53
|
+
accountId: "private-account",
|
|
54
|
+
accessToken: "fixture-usage-secret",
|
|
55
|
+
profile: { email: "private-fixture@example.invalid" },
|
|
56
|
+
} });
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
send({ id: frame.id, error: { code: -32601, message: "Unexpected operation" } });
|
|
60
|
+
});
|
|
61
|
+
process.stdin.on("end", () => { if (!["hang", "stubborn", "tree"].includes(mode)) process.exit(0); });
|
|
@@ -159,6 +159,9 @@ await writeFile(artifactManifest, JSON.stringify({ artifact: { schema: "pi.artif
|
|
|
159
159
|
await mkdir(managedThemeDir, { recursive: true });
|
|
160
160
|
await writeFile(path.join(managedThemePackageRoot, "package.json"), JSON.stringify({ name: "@firstpick/pi-themes-bundle", version: "0.0.0-test", pi: { themes: ["./themes"] } }));
|
|
161
161
|
await writeFile(path.join(managedThemeDir, "managed-fixture.json"), serializeTheme(themeFixture("managed-fixture")));
|
|
162
|
+
await writeFile(path.join(managedThemePackageRoot, "webui-backgrounds.json"), JSON.stringify({
|
|
163
|
+
"managed-fixture": { backgroundImage: "url(\"/matrix-background.webp\")", backgroundSize: "cover", pageBg: "#ffffff", arbitrary: "ignored" },
|
|
164
|
+
}));
|
|
162
165
|
await writeFile(path.join(workflowPolicyAgentDir, "trust.json"), `${JSON.stringify({ [cwd]: true }, null, 2)}\n`);
|
|
163
166
|
await chmod(fakePi, 0o755);
|
|
164
167
|
await mkdir(fakeOpenBinDir, { recursive: true });
|
|
@@ -513,6 +516,11 @@ try {
|
|
|
513
516
|
assert.deepEqual(managedThemesResponse.body?.data?.themes?.map(({ name }) => name), ["managed-fixture"], "themes installed only under PI_CODING_AGENT_DIR/npm/node_modules should be exposed to the browser");
|
|
514
517
|
assert.equal(managedThemesResponse.body?.data?.themes?.[0]?.colors?.accent, "#123456");
|
|
515
518
|
assert.equal(managedThemesResponse.body?.data?.themes?.[0]?.scope, "bundled");
|
|
519
|
+
const managedExport = managedThemesResponse.body.data.themes[0].export;
|
|
520
|
+
assert.equal(managedExport.backgroundImage, "url(\"/matrix-background.webp\")", "separate WebUI metadata must preserve bundled backgrounds");
|
|
521
|
+
assert.equal(managedExport.backgroundSize, "cover");
|
|
522
|
+
assert.notEqual(managedExport.pageBg, "#ffffff", "background metadata must not replace native Pi export colors");
|
|
523
|
+
assert.equal(Object.hasOwn(managedExport, "arbitrary"), false, "only supported background fields may enter the catalog");
|
|
516
524
|
|
|
517
525
|
const themeTabs = await request("127.0.0.1", "/api/tabs");
|
|
518
526
|
const themeTabId = themeTabs.body?.data?.tabs?.[0]?.id;
|
|
@@ -4,6 +4,7 @@ import { dirname, join } from "node:path";
|
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import {
|
|
6
6
|
PI_THEME_EXPORT_FIELDS,
|
|
7
|
+
PI_THEME_SCHEMA_URL,
|
|
7
8
|
REQUIRED_THEME_TOKENS,
|
|
8
9
|
THEME_TOKEN_GROUPS,
|
|
9
10
|
ThemeContractError,
|
|
@@ -18,8 +19,9 @@ import {
|
|
|
18
19
|
xterm256ToRgb,
|
|
19
20
|
} from "../public/theme-contract.mjs";
|
|
20
21
|
|
|
21
|
-
const
|
|
22
|
-
const schemaPath = join(
|
|
22
|
+
const piRoot = join(dirname(fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent"))), "..");
|
|
23
|
+
const schemaPath = join(piRoot, "schemas", "theme.schema.json");
|
|
24
|
+
const legacySchemaPath = join(piRoot, "dist", "modes", "interactive", "theme", "theme-schema.json");
|
|
23
25
|
|
|
24
26
|
function fixture(overrides = {}) {
|
|
25
27
|
return {
|
|
@@ -36,7 +38,11 @@ assert.equal(new Set(REQUIRED_THEME_TOKENS).size, 51, "required tokens must be u
|
|
|
36
38
|
assert.equal(THEME_TOKEN_GROUPS.length, 7, "the documented token inventory has seven groups");
|
|
37
39
|
assert.deepEqual(THEME_TOKEN_GROUPS.map(({ tokens }) => tokens.length), [11, 11, 10, 3, 9, 6, 1]);
|
|
38
40
|
|
|
39
|
-
const installedSchema = JSON.parse(await readFile(schemaPath, "utf8"))
|
|
41
|
+
const installedSchema = JSON.parse(await readFile(schemaPath, "utf8").catch((error) => {
|
|
42
|
+
if (error.code !== "ENOENT") throw error;
|
|
43
|
+
return readFile(legacySchemaPath, "utf8");
|
|
44
|
+
}));
|
|
45
|
+
assert.equal(PI_THEME_SCHEMA_URL, "https://pi.dev/schemas/theme.schema.json");
|
|
40
46
|
assert.deepEqual(
|
|
41
47
|
[...REQUIRED_THEME_TOKENS].sort(),
|
|
42
48
|
[...installedSchema.properties.colors.required].sort(),
|
|
@@ -58,6 +64,7 @@ const explicitMax = fixture({ colors: { ...valid.colors, thinkingMax: "primary"
|
|
|
58
64
|
assert.equal(effectiveThemeColors(explicitMax).thinkingMax, "primary");
|
|
59
65
|
|
|
60
66
|
const native = canonicalizeTheme(valid);
|
|
67
|
+
assert.equal(native.$schema, PI_THEME_SCHEMA_URL);
|
|
61
68
|
assert.deepEqual(Object.keys(native.export), ["pageBg", "cardBg", "infoBg"]);
|
|
62
69
|
assert.equal(Object.hasOwn(native.export, "backgroundImage"), false, "WebUI-only export fields must not enter Pi-native files");
|
|
63
70
|
assert.deepEqual(Object.keys(native.colors), REQUIRED_THEME_TOKENS, "canonical colors must retain documented order");
|