@firstpick/pi-package-webui 0.8.1 → 0.8.2
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/README.md +12 -0
- package/bin/pi-webui.mjs +190 -20
- package/lib/component-update-state.mjs +126 -0
- package/lib/trust-boundaries.mjs +1 -0
- package/package.json +1 -1
- package/public/app.js +1454 -101
- package/public/index.html +155 -27
- package/public/service-worker.js +1 -1
- package/public/styles.css +731 -2
- package/tests/boot-failure-diagnostics.test.mjs +63 -5
- package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
- package/tests/browser/interaction-continuity.spec.mjs +158 -0
- package/tests/browser/mobile-foundation.spec.mjs +11 -0
- package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
- package/tests/browser/stats-overlay.spec.mjs +265 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/component-update-api-static.test.mjs +67 -0
- package/tests/component-update-state.test.mjs +80 -0
- package/tests/control-deck-component-updates-static.test.mjs +251 -0
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/fixtures/fake-pi.mjs +129 -5
- package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
- package/tests/interaction-state-stability-static.test.mjs +21 -4
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +6 -4
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +2 -1
- package/tests/native-parity-harness.test.mjs +2 -0
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/side-panel-section-reorder-static.test.mjs +68 -0
- package/tests/sse-backpressure-harness.test.mjs +51 -12
- package/tests/stats-dashboard-static.test.mjs +266 -0
|
@@ -67,7 +67,7 @@ assert.match(html, /id="newTabChooseDirectoryButton" class="terminal-new-tab-men
|
|
|
67
67
|
assert.match(html, /id="newTabWorktreeButton" class="terminal-new-tab-menu-item composer-publish-menu-item"[\s\S]*<span>Branch Worktree…<\/span>/, "new-tab menu should offer branch worktree tabs");
|
|
68
68
|
assert.match(html, /id="closeAllTabsButton"[\s\S]*?>Close all Tabs<\/button>/, "tab header should expose a top-right close-all tabs action");
|
|
69
69
|
assert.match(html, /id="sidePanelBackdrop"/, "mobile side panel needs an overlay/backdrop close target");
|
|
70
|
-
assert.match(html, /<div class="side-panel-heading">[\s\S]*<strong class="side-panel-title">Control Deck<\/strong>[\s\S]*<div class="side-panel-version-row"[\s\S]*<button id="piVersionButton"[\s\S]*aria-controls="piReleaseNotesDialog"[\s\S]*<button id="webuiVersionButton"[\s\S]*aria-controls="
|
|
70
|
+
assert.match(html, /<div class="side-panel-heading">[\s\S]*<strong class="side-panel-title">Control Deck<\/strong>[\s\S]*<div class="side-panel-version-row"[\s\S]*<button id="piVersionButton"[\s\S]*aria-controls="piReleaseNotesDialog"[\s\S]*<button id="webuiVersionButton"[\s\S]*aria-controls="webuiPackageDialog"[\s\S]*id="webuiDevBadge"/, "Control Deck header should keep its title separate from an aligned version and build row");
|
|
71
71
|
assert.match(html, /<div class="side-panel-brand-row">[\s\S]*<span class="side-panel-kicker">Pi Web UI<\/span>[\s\S]*<a class="sponsor-link" href="https:\/\/github\.com\/sponsors\/Firstp1ck" target="_blank" rel="noopener noreferrer" aria-label="Sponsor Firstp1ck on GitHub"[^>]*>♡<\/a>/, "Control Deck brand should expose a subtle, accessible sponsor link beside the Pi Web UI name");
|
|
72
72
|
assert.match(html, /<dialog id="piReleaseNotesDialog"[\s\S]*id="piReleaseNotesTitle"[\s\S]*id="piReleaseNotesStatus"[\s\S]*id="piReleaseNotesBody"[\s\S]*id="piReleaseNotesGithubLink"/, "Pi release notes should use a dedicated accessible dialog");
|
|
73
73
|
assert.doesNotMatch(html, /Safer option|confirmationAlternative/, "shared confirmation dialogs should not render a safer-option row");
|
|
@@ -876,6 +876,7 @@ assert.match(app, /if \(request\.replayed\) addEvent\(`recovered pending \$\{req
|
|
|
876
876
|
assert.match(app, /case "webui_extension_ui_cancelled":/, "frontend should close dialogs cancelled by backend abort handling");
|
|
877
877
|
assert.match(app, /case "webui_extension_ui_resolved":[\s\S]*?removeQueuedDialogRequests\(\[event\.id\]\)/, "frontend should close dialogs resolved by another connected browser");
|
|
878
878
|
assert.match(app, /if \(responseId && activeDialog && String\(activeDialog\.id \|\| ""\) !== responseId\) return;/, "dialog response cleanup should not close the next queued dialog after a resolve-event race");
|
|
879
|
+
assert.match(app, /if \(runIndicatorIsActive\(\)\) \{\s*setRunIndicatorActivity\("Continuing after your response…"\);[\s\S]*?scheduleRefreshState\(120, tabContext\);\s*\}/, "extension UI responses should promptly reconcile canonical state so background release commands cannot leave a stale running indicator");
|
|
879
880
|
assert.match(app, /function parseTodoProgressWidget\(lines\)/, "todo-progress widgets should be parsed from extension widget lines");
|
|
880
881
|
assert.ok(app.includes("const goalLine = cleanLines.find((line) => /^Goal\\s*[::]/i.test(line));"), "todo-progress parser should preserve an optional Goal line from extension widget lines");
|
|
881
882
|
assert.ok(app.includes("if (todo.goal) summary.append(make(\"div\", \"todo-widget-goal\", `Goal: ${todo.goal}`));"), "todo-progress widget should display the goal above the progress header");
|
|
@@ -42,7 +42,9 @@ assert.equal(isLocalRequest(remoteReq), false);
|
|
|
42
42
|
|
|
43
43
|
assert.throws(() => requireLocalhost(remoteReq, "blocked"), (error) => error.statusCode === 403);
|
|
44
44
|
assert.throws(() => requireLocalhostRoute(remoteReq, "/api/update"), (error) => error.statusCode === 403);
|
|
45
|
+
assert.throws(() => requireLocalhostRoute(remoteReq, "/api/component-update"), (error) => error.statusCode === 403);
|
|
45
46
|
assert.doesNotThrow(() => requireLocalhostRoute(localReq, "/api/update"));
|
|
47
|
+
assert.doesNotThrow(() => requireLocalhostRoute(localReq, "/api/component-update"));
|
|
46
48
|
assert.ok(LOCALHOST_ONLY_POST_ROUTES.has("/api/workflow-policy"), "workflow policy mutation must stay in the canonical localhost route registry");
|
|
47
49
|
|
|
48
50
|
for (const pathname of LOCALHOST_ONLY_POST_ROUTES.keys()) {
|
|
@@ -69,7 +69,7 @@ assert.match(server, /"issue-bot-client\.mjs"/, "the static allowlist must serve
|
|
|
69
69
|
assert.match(serviceWorker, /"\/issue-wizard-state\.mjs"/, "the PWA shell must keep caching the pure wizard module");
|
|
70
70
|
assert.match(serviceWorker, /"\/issue-bot-client\.mjs"/, "the PWA shell must cache the browser client module");
|
|
71
71
|
// Intent preserved: changing the public startup graph advances the PWA cache identity.
|
|
72
|
-
assert.match(serviceWorker, /pi-webui-pwa-
|
|
72
|
+
assert.match(serviceWorker, /pi-webui-pwa-v62/, "the PWA cache name must change with browser wiring updates");
|
|
73
73
|
assert.match(packageJson, /node --check public\/issue-wizard-state\.mjs/, "the package check must keep syntax-checking the pure wizard module");
|
|
74
74
|
assert.match(packageJson, /node --check public\/issue-bot-client\.mjs/, "the package check must syntax-check the browser client module");
|
|
75
75
|
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
7
|
+
const [html, app, css, serviceWorker] = await Promise.all([
|
|
8
|
+
readFile(join(root, "public", "index.html"), "utf8"),
|
|
9
|
+
readFile(join(root, "public", "app.js"), "utf8"),
|
|
10
|
+
readFile(join(root, "public", "styles.css"), "utf8"),
|
|
11
|
+
readFile(join(root, "public", "service-worker.js"), "utf8"),
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
assert.match(
|
|
15
|
+
app,
|
|
16
|
+
/const SIDE_PANEL_SECTION_ORDER_STORAGE_KEY = "pi-webui-side-panel-section-order-v1";[\s\S]*const SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX = 6;/,
|
|
17
|
+
"side-panel order should use versioned browser storage and the same six-pixel pointer threshold as model ordering",
|
|
18
|
+
);
|
|
19
|
+
assert.match(
|
|
20
|
+
app,
|
|
21
|
+
/function readStoredSidePanelSectionOrder\(\)[\s\S]*JSON\.parse\(localStorage\.getItem\(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY\)[\s\S]*new Set\([\s\S]*function persistSidePanelSectionOrder\(\)[\s\S]*sidePanelSectionRecords\(\)\.map\(\(\{ id \}\) => id\)/,
|
|
22
|
+
"stored order should be deduplicated and persist the complete current section order",
|
|
23
|
+
);
|
|
24
|
+
assert.match(
|
|
25
|
+
app,
|
|
26
|
+
/function restoreSidePanelSectionOrder\(\)[\s\S]*rank = new Map\([\s\S]*Number\.MAX_SAFE_INTEGER[\s\S]*parent\.append\(section\)/,
|
|
27
|
+
"restore should rank known IDs while appending newly introduced sections in their existing order",
|
|
28
|
+
);
|
|
29
|
+
assert.match(
|
|
30
|
+
app,
|
|
31
|
+
/function moveSidePanelSectionRelative\(fromId, targetRecord, insertBefore\)[\s\S]*parent\.insertBefore\(sourceRecord\.section, targetRecord\.section\)[\s\S]*targetRecord\.section\.nextSibling[\s\S]*persistSidePanelSectionOrder\(\)/,
|
|
32
|
+
"reordering should move the complete section before or after its target and persist immediately",
|
|
33
|
+
);
|
|
34
|
+
assert.match(
|
|
35
|
+
app,
|
|
36
|
+
/function updateSidePanelSectionPointerDrag\(event\)[\s\S]*Math\.hypot[\s\S]*SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX[\s\S]*sidePanelSectionToggleFromPoint[\s\S]*getBoundingClientRect\(\)[\s\S]*moveSidePanelSectionRelative/,
|
|
37
|
+
"pointer dragging should activate only after the threshold and use header midpoint placement",
|
|
38
|
+
);
|
|
39
|
+
assert.match(
|
|
40
|
+
app,
|
|
41
|
+
/function endSidePanelSectionPointerDrag\(event\)[\s\S]*sidePanelSectionSuppressClickUntil = Date\.now\(\) \+ 250[\s\S]*focus\(\{ preventScroll: true \}\)/,
|
|
42
|
+
"a completed drag should suppress the accidental toggle click and restore focus",
|
|
43
|
+
);
|
|
44
|
+
assert.match(
|
|
45
|
+
app,
|
|
46
|
+
/function bindSidePanelSectionToggles\(\)[\s\S]*Date\.now\(\) < sidePanelSectionSuppressClickUntil[\s\S]*event\.altKey[\s\S]*event\.key !== "ArrowUp"[\s\S]*moveSidePanelSectionByOffset[\s\S]*beginSidePanelSectionPointerDrag/,
|
|
47
|
+
"section headers should retain click toggling while supporting Alt+Arrow keyboard and pointer reordering",
|
|
48
|
+
);
|
|
49
|
+
assert.match(
|
|
50
|
+
app,
|
|
51
|
+
/restoreSidePanelSectionOrder\(\);\s*restoreSidePanelSectionVisibility\(\);\s*restoreSidePanelSectionState\(\);/,
|
|
52
|
+
"saved order should restore before visibility and accordion state",
|
|
53
|
+
);
|
|
54
|
+
assert.match(
|
|
55
|
+
app,
|
|
56
|
+
/event\.key === SIDE_PANEL_SECTION_ORDER_STORAGE_KEY\) restoreSidePanelSectionOrder\(\)/,
|
|
57
|
+
"other tabs should apply stored side-panel order changes",
|
|
58
|
+
);
|
|
59
|
+
assert.match(
|
|
60
|
+
css,
|
|
61
|
+
/\.side-panel-section-toggle\[data-side-panel-section-toggle\][\s\S]*cursor: grab[\s\S]*touch-action: none[\s\S]*\.side-panel-section\.dragging[\s\S]*cursor: grabbing[\s\S]*\.drag-over-before[\s\S]*\.drag-over-after/,
|
|
62
|
+
"section headers should expose model-picker-style grab, dragging, and insertion-marker affordances",
|
|
63
|
+
);
|
|
64
|
+
assert.match(html, /styles\.css\?v=93/, "changed side-panel styles should advance the stylesheet revision");
|
|
65
|
+
assert.match(html, /app\.js\?v=104/, "changed side-panel behavior should advance the app revision");
|
|
66
|
+
assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v62"/, "changed browser assets should advance the PWA cache identity");
|
|
67
|
+
|
|
68
|
+
console.log("side-panel-section-reorder-static.test.mjs passed");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { createServer } from "node:net";
|
|
3
|
+
import { connect, createServer } from "node:net";
|
|
4
4
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import path from "node:path";
|
|
@@ -63,31 +63,70 @@ try {
|
|
|
63
63
|
const tabId = tabs.body?.data?.tabs?.[0]?.id;
|
|
64
64
|
assert.ok(tabId, "fixture server should expose an initial tab");
|
|
65
65
|
|
|
66
|
-
//
|
|
67
|
-
//
|
|
68
|
-
//
|
|
69
|
-
const
|
|
70
|
-
assert.equal(
|
|
71
|
-
const
|
|
72
|
-
assert.equal(
|
|
66
|
+
// Undici continues draining the transport even when application code has not
|
|
67
|
+
// consumed response.body. A >2MiB burst must therefore survive transient
|
|
68
|
+
// ServerResponse backpressure instead of being mistaken for a dead client.
|
|
69
|
+
const flowing = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: AbortSignal.timeout(15_000) });
|
|
70
|
+
assert.equal(flowing.status, 200);
|
|
71
|
+
const flowingFlood = await json("/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture sse flood" } });
|
|
72
|
+
assert.equal(flowingFlood.status, 200, "flood fixture should dispatch through the real server");
|
|
73
|
+
await delay(500);
|
|
74
|
+
const flowingTabs = await json("/api/tabs");
|
|
75
|
+
assert.equal(flowingTabs.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount, 1, "a transport-draining SSE client must survive transient backpressure");
|
|
76
|
+
await flowing.body?.cancel();
|
|
73
77
|
|
|
74
|
-
let evicted = false;
|
|
75
78
|
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
79
|
+
const refreshed = await json("/api/tabs");
|
|
80
|
+
if (refreshed.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount === 0) break;
|
|
81
|
+
await delay(50);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// A paused raw socket does not drain the HTTP transport. It must be evicted
|
|
85
|
+
// within the bounded queue/timeout policy, but with a complete final chunk so
|
|
86
|
+
// Chromium does not surface ERR_INCOMPLETE_CHUNKED_ENCODING on reconnection.
|
|
87
|
+
const stalled = connect({ host: "127.0.0.1", port });
|
|
88
|
+
let stalledResponse = "";
|
|
89
|
+
stalled.on("data", (chunk) => { stalledResponse += String(chunk); });
|
|
90
|
+
stalled.pause();
|
|
91
|
+
await new Promise((resolve, reject) => {
|
|
92
|
+
stalled.once("connect", resolve);
|
|
93
|
+
stalled.once("error", reject);
|
|
94
|
+
});
|
|
95
|
+
stalled.write(`GET /api/events?tab=${encodeURIComponent(tabId)} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: keep-alive\r\n\r\n`);
|
|
96
|
+
|
|
97
|
+
let connected = false;
|
|
98
|
+
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
99
|
+
const refreshed = await json("/api/tabs");
|
|
100
|
+
if (refreshed.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount === 1) {
|
|
101
|
+
connected = true;
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
await delay(50);
|
|
105
|
+
}
|
|
106
|
+
assert.equal(connected, true, "the paused raw SSE client should connect before the flood");
|
|
107
|
+
const stalledFlood = await json("/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture sse stall flood" } });
|
|
108
|
+
assert.equal(stalledFlood.status, 200, "stalled-client flood should dispatch through the real server");
|
|
109
|
+
|
|
110
|
+
let evicted = false;
|
|
111
|
+
for (let attempt = 0; attempt < 240; attempt += 1) {
|
|
76
112
|
const refreshed = await json("/api/tabs");
|
|
77
113
|
const clientCount = refreshed.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount;
|
|
78
114
|
if (clientCount === 0) {
|
|
79
115
|
evicted = true;
|
|
80
116
|
break;
|
|
81
117
|
}
|
|
82
|
-
await delay(
|
|
118
|
+
await delay(50);
|
|
83
119
|
}
|
|
84
|
-
assert.equal(evicted, true, "
|
|
120
|
+
assert.equal(evicted, true, "a transport-stalled SSE client must be evicted instead of accumulating an unbounded semantic-event queue");
|
|
121
|
+
stalled.resume();
|
|
122
|
+
for (let attempt = 0; attempt < 100 && !stalledResponse.includes("\r\n0\r\n\r\n"); attempt += 1) await delay(50);
|
|
123
|
+
assert.match(stalledResponse, /\r\n0\r\n\r\n/, "backpressure eviction must complete the chunked SSE response without truncating it");
|
|
124
|
+
stalled.destroy();
|
|
85
125
|
|
|
86
126
|
const reconnected = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: AbortSignal.timeout(5_000) });
|
|
87
127
|
const firstFrame = await reconnected.body.getReader().read();
|
|
88
128
|
assert.equal(firstFrame.done, false, "a client can reconnect after slow-client eviction");
|
|
89
129
|
assert.match(new TextDecoder().decode(firstFrame.value), /webui_connected/, "reconnection should receive an authoritative connection snapshot");
|
|
90
|
-
await stalled.body?.cancel().catch(() => {});
|
|
91
130
|
await reconnected.body?.cancel().catch(() => {});
|
|
92
131
|
} finally {
|
|
93
132
|
child.kill("SIGTERM");
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import vm from "node:vm";
|
|
4
|
+
|
|
5
|
+
const [app, css, html] = await Promise.all([
|
|
6
|
+
readFile(new URL("../public/app.js", import.meta.url), "utf8"),
|
|
7
|
+
readFile(new URL("../public/styles.css", import.meta.url), "utf8"),
|
|
8
|
+
readFile(new URL("../public/index.html", import.meta.url), "utf8"),
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
const between = (source, start, end) => {
|
|
12
|
+
const startIndex = source.indexOf(start);
|
|
13
|
+
assert.notEqual(startIndex, -1, `missing section start: ${start}`);
|
|
14
|
+
const endIndex = source.indexOf(end, startIndex + start.length);
|
|
15
|
+
assert.notEqual(endIndex, -1, `missing section end: ${end}`);
|
|
16
|
+
return source.slice(startIndex, endIndex);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const helpers = between(app, "function formatStatsPercent", "function parseStatsWebuiPayloadRaw");
|
|
20
|
+
const charts = between(app, "const STATS_CHART_POINT_LIMIT", "function renderStatsOverview");
|
|
21
|
+
const overview = between(app, "function renderStatsOverview", "function renderStatsDaily");
|
|
22
|
+
const daily = between(app, "function renderStatsDaily", "function renderStatsModels");
|
|
23
|
+
const models = between(app, "function renderStatsModels", "function renderStatsSessions");
|
|
24
|
+
const sessions = between(app, "function renderStatsSessions", "function renderStatsCostCache");
|
|
25
|
+
const costCache = between(app, "function renderStatsCostCache", "function statsCalibrationButton");
|
|
26
|
+
const promptUi = between(app, "const STATS_PROMPT_SOURCE_LIMIT", "function renderStatsOverlayPane");
|
|
27
|
+
const promptInitial = between(app, "function renderStatsPromptInitial", "function statsPromptInventoryDetails");
|
|
28
|
+
const promptSnapshot = between(app, "function renderStatsPromptSnapshot", "function renderStatsPromptCurrent");
|
|
29
|
+
const promptCurrent = between(app, "function renderStatsPromptCurrent", "function renderStatsPrompt(payload)");
|
|
30
|
+
const promptDispatch = between(app, "function renderStatsPrompt(payload)", "function statsCommandOutputSection");
|
|
31
|
+
const rawOutput = between(app, "function renderStatsRaw", "function renderStatsOverlayPane");
|
|
32
|
+
const overlay = between(app, "function activateStatsOverlayTab", "function scheduleStatsRefreshAfterCalibration");
|
|
33
|
+
|
|
34
|
+
// Accurate cache terminology: no request-level "cache hit" label or savings claim in the stats UI.
|
|
35
|
+
const statsUi = helpers + charts + overview + daily + models + sessions + costCache + overlay;
|
|
36
|
+
assert.doesNotMatch(statsUi, /"Cache hit"/, "stats UI must not label any metric as a request-level cache hit");
|
|
37
|
+
assert.doesNotMatch(statsUi, /cache savings|estimated savings/i, "stats UI must not claim ungrounded monetary cache savings");
|
|
38
|
+
assert.match(statsUi, /Cached-input share/, "cached-input share label should be present");
|
|
39
|
+
assert.match(overview, /statsCachedInputShare\(summary, totals\)/, "overview should use the accurately named cached-input share");
|
|
40
|
+
assert.match(costCache, /statsCachedInputShare\(summary, totals\)/, "cost & cache should use the accurately named cached-input share");
|
|
41
|
+
|
|
42
|
+
// Legacy v1 fallbacks: absent fields are computed client-side, explicit null renders as n/a (never fake zeroes).
|
|
43
|
+
assert.match(helpers, /key in summary/, "fallback resolvers should distinguish absent fields from explicit nulls");
|
|
44
|
+
assert.match(helpers, /cachedInputShare[\s\S]*statsNumber\(totals\?\.input\) \+ statsNumber\(totals\?\.cacheRead\) \+ statsNumber\(totals\?\.cacheWrite\)/, "legacy cached-input share fallback should use the prompt-side denominator");
|
|
45
|
+
assert.match(helpers, /effectiveCostPerMillionTokens[\s\S]*1_000_000/, "legacy effective-cost fallback should compute cost per million total tokens");
|
|
46
|
+
assert.match(helpers, /return number === null \? "n\/a"/, "nullable percentages should render n/a rather than a fake zero");
|
|
47
|
+
assert.match(helpers, /function formatStatsNullableTokens\(value\) \{\s*const number = statsNullableNumber\(value\);\s*return number === null \? "n\/a" : `\$\{formatStatsTokens\(number\)\} tok`;/, "nullable token averages should render n/a rather than a fake zero");
|
|
48
|
+
assert.match(costCache, /formatStatsNullableTokens\(statsAverageTokensPerSession\(summary, payload\)\)/, "average tokens per session should stay nullable in the UI");
|
|
49
|
+
assert.doesNotMatch(app, /Cache hit rate|estimated savings/i, "raw command-output descriptions must not promise request-level hit rates or savings estimates");
|
|
50
|
+
assert.match(helpers, /statsNullableNumber\(payload\?\.sessionCount\)/, "scoped session count should fall back to the legacy session-file count");
|
|
51
|
+
assert.match(overview, /sessions in range[\s\S]*session files/, "overview should label scoped sessions and legacy session files deliberately");
|
|
52
|
+
assert.match(costCache, /requires the latest stats extension/, "missing spend comparison should be disclosed rather than faked");
|
|
53
|
+
|
|
54
|
+
// Safe collection coercion for malformed payloads.
|
|
55
|
+
assert.match(helpers, /function statsArray\(value\) \{\s*return Array\.isArray\(value\) \? value : \[\];/, "statsArray should coerce malformed collections to an empty list");
|
|
56
|
+
for (const [name, section] of [["daily", daily], ["models", models], ["sessions", sessions]]) {
|
|
57
|
+
assert.match(section, /statsArray\(payload\?\./, `${name} view should coerce payload collections defensively`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Chart clamping, caps, and independent scales.
|
|
61
|
+
assert.match(charts, /const STATS_CHART_POINT_LIMIT = 31;/, "long charts should be capped at the latest 31 points");
|
|
62
|
+
assert.match(charts, /slice\(-STATS_CHART_POINT_LIMIT\)/, "chart windowing should keep the latest points");
|
|
63
|
+
assert.match(charts, /latest \$\{STATS_CHART_POINT_LIMIT\} of \$\{total\}/, "the point cap should be disclosed");
|
|
64
|
+
assert.match(charts, /Math\.min\(100, Math\.max\(statsNumber\(row\.total\) > 0 \? 1\.5 : 0, \(statsNumber\(row\.total\) \/ maxTokens\) \* 100\)\)/, "token bars should be clamped without drawing a false non-zero sliver");
|
|
65
|
+
assert.match(charts, /Math\.min\(100, Math\.max\(statsNumber\(row\.cost\) > 0 \? 1\.5 : 0, \(statsNumber\(row\.cost\) \/ maxCost\) \* 100\)\)/, "cost bars should be clamped on their own scale while keeping non-zero spend visible");
|
|
66
|
+
assert.match(charts, /Daily tab lists every recorded day/, "truncated charts should direct users to the actual full-data view");
|
|
67
|
+
assert.match(charts, /statsChartWindowNote\(windowed, "active days"\)/, "daily usage chart should disclose that its cap counts active days");
|
|
68
|
+
assert.match(charts, /token and cost bars use independent scales/, "the independent token/cost scales should be disclosed in the legend");
|
|
69
|
+
assert.match(charts, /Math\.min\(100, Math\.max\(row\.cost > 0 \? 3 : 0, \(row\.cost \/ maxCost\) \* 100\)\)/, "spend bars should clamp heights and keep non-zero spend visible");
|
|
70
|
+
assert.match(charts, /Math\.min\(100, Math\.max\(0, \(segment\.value \/ total\) \* 100\)\)/, "composition segments should clamp widths");
|
|
71
|
+
assert.match(charts, /total <= 0/, "zero-usage composition and spend data should short-circuit safely");
|
|
72
|
+
assert.match(charts, /aria-label[\s\S]*Total \$\{formatStatsCost\(total\)\}; peak/, "spend chart should expose an accessible text summary");
|
|
73
|
+
assert.match(charts, /Token composition: \$\{segments/, "composition should expose an accessible text summary");
|
|
74
|
+
assert.match(charts, /stats-overlay-chart-caption/, "charts should carry visible captions with values");
|
|
75
|
+
|
|
76
|
+
// Cost & cache replaces raw command-output blocks with structured visuals.
|
|
77
|
+
assert.doesNotMatch(costCache, /statsLineBlock/, "cost & cache should no longer render raw command-output blocks");
|
|
78
|
+
assert.match(costCache, /renderStatsSpendChart\(payload\?\.daily\)/, "cost & cache should render the daily spend chart");
|
|
79
|
+
assert.match(costCache, /renderStatsComposition\(totals\)/, "cost & cache should render the token/cache composition");
|
|
80
|
+
assert.match(costCache, /renderStatsTopDrivers\(payload\)/, "cost & cache should render ranked cost drivers");
|
|
81
|
+
assert.match(costCache, /blended rate, not provider list pricing/, "effective cost should be labeled as blended rather than list pricing");
|
|
82
|
+
assert.match(costCache, /vs prior \$\{comparison\.windowDays\}d/, "spend comparison should disclose its equal window length");
|
|
83
|
+
|
|
84
|
+
// Visual ranks for models and sessions.
|
|
85
|
+
assert.match(models, /renderStatsDriverList\(statsModelDriverEntries\(payload\)/, "models view should include visual spend ranks");
|
|
86
|
+
assert.match(sessions, /renderStatsDriverList\(statsSessionDriverEntries\(payload\)/, "sessions view should include visual spend ranks");
|
|
87
|
+
assert.match(helpers + charts, /statsCostShareOf[\s\S]*total > 0 \? \(statsNumber\(cost\) \/ total\) \* 100 : null/, "driver shares should be nullable when total cost is zero");
|
|
88
|
+
|
|
89
|
+
// Prompt/context native rendering is isolated from legacy line blocks; only fallback and raw output use them.
|
|
90
|
+
for (const [name, section] of [["initial", promptInitial], ["snapshot", promptSnapshot], ["current", promptCurrent]]) {
|
|
91
|
+
assert.doesNotMatch(section, /statsLineBlock/, `${name} native Prompt/context rendering must not render raw command lines`);
|
|
92
|
+
}
|
|
93
|
+
assert.match(promptDispatch, /initialPrompt \? renderStatsPromptInitial\(initialPrompt\) : statsPromptLegacyFallback\("Initial prompt composition", payload\?\.lines\?\.promptInjection\)/, "initial prompt should fall back only to promptInjection lines");
|
|
94
|
+
assert.match(promptDispatch, /snapshot \? renderStatsPromptSnapshot\(snapshot\) : statsPromptLegacyFallback\("Prompt inventory", payload\?\.lines\?\.promptDetailed\)/, "snapshot should fall back only to promptDetailed lines");
|
|
95
|
+
assert.match(promptDispatch, /currentContext \? renderStatsPromptCurrent\(currentContext\) : statsPromptLegacyFallback\("Current context", payload\?\.lines\?\.tokenBreakdown\)/, "current context should fall back only to tokenBreakdown lines");
|
|
96
|
+
assert.match(rawOutput, /\[\.\.\.\(payload\?\.lines\?\.promptInjection \|\| \[\]\), "", \.\.\.\(payload\?\.lines\?\.promptDetailed \|\| \[\]\)\]/, "Command outputs should retain raw prompt injection and detailed lines");
|
|
97
|
+
assert.doesNotMatch(promptUi, /innerHTML|insertAdjacentHTML/, "Prompt/context payload labels must stay on text-safe DOM construction paths");
|
|
98
|
+
|
|
99
|
+
class FakeNode {
|
|
100
|
+
constructor(tagName, className = "", text = "") {
|
|
101
|
+
this.tagName = tagName;
|
|
102
|
+
this.className = className || "";
|
|
103
|
+
this.textContent = text === undefined ? "" : String(text);
|
|
104
|
+
this.children = [];
|
|
105
|
+
this.attributes = new Map();
|
|
106
|
+
this.dataset = {};
|
|
107
|
+
this.style = {};
|
|
108
|
+
}
|
|
109
|
+
append(...children) { this.children.push(...children); }
|
|
110
|
+
setAttribute(name, value) { this.attributes.set(name, String(value)); }
|
|
111
|
+
get lastElementChild() { return this.children.at(-1); }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function fakeNodesWithClass(root, className) {
|
|
115
|
+
const matches = [];
|
|
116
|
+
const visit = (node) => {
|
|
117
|
+
if (!(node instanceof FakeNode)) return;
|
|
118
|
+
if (node.className.split(/\s+/).includes(className)) matches.push(node);
|
|
119
|
+
node.children.forEach(visit);
|
|
120
|
+
};
|
|
121
|
+
visit(root);
|
|
122
|
+
return matches;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const promptContext = {
|
|
126
|
+
console,
|
|
127
|
+
make: (tagName, className, text) => new FakeNode(tagName, className, text),
|
|
128
|
+
formatStatsTokens: (value) => Number(value).toLocaleString(),
|
|
129
|
+
statsPromptEstimateSourceLabel: (estimate = {}) => estimate.source === "export-html" ? "export-backed" : estimate.source || "estimate",
|
|
130
|
+
renderStatsCalibrationPanel: () => new FakeNode("section", "fixture-calibration"),
|
|
131
|
+
statsMetricCard: (label, value, detail = "", tone = "") => {
|
|
132
|
+
const card = new FakeNode("div", `stats-overlay-card ${tone}`.trim());
|
|
133
|
+
card.append(new FakeNode("span", "stats-overlay-card-label", label), new FakeNode("strong", "", value));
|
|
134
|
+
if (detail) card.append(new FakeNode("span", "stats-overlay-card-detail", detail));
|
|
135
|
+
return card;
|
|
136
|
+
},
|
|
137
|
+
statsLineBlock: (lines = []) => new FakeNode("pre", "stats-overlay-lines", (Array.isArray(lines) ? lines : []).join("\n") || "No data."),
|
|
138
|
+
};
|
|
139
|
+
promptContext.statsCommandOutputSection = (_title, _command, _description, lines) => {
|
|
140
|
+
const section = new FakeNode("section", "fixture-command-output");
|
|
141
|
+
section.append(promptContext.statsLineBlock(lines));
|
|
142
|
+
return section;
|
|
143
|
+
};
|
|
144
|
+
vm.runInNewContext(`${promptUi}\n;globalThis.promptTestApi = { normalizeStatsPromptInitial, normalizeStatsPromptSnapshot, normalizeStatsPromptCurrent, renderStatsPrompt, renderStatsRaw };`, promptContext);
|
|
145
|
+
|
|
146
|
+
const hostileLabel = `<img src=x onerror="globalThis.fixturePwned=true"> & "quoted"`;
|
|
147
|
+
const structuredPromptPayload = {
|
|
148
|
+
promptContext: {
|
|
149
|
+
initialPrompt: {
|
|
150
|
+
totalTokens: 100, lowTokens: 90, highTokens: 110, confidence: "fixture", source: "export-html", warning: null,
|
|
151
|
+
estimateMethod: "weighted-character-estimate", components: [
|
|
152
|
+
{ id: "system-1", kind: "system-prompt", label: hostileLabel, chars: null, uncalibratedTokens: 100, tokens: 100, percent: 100 },
|
|
153
|
+
{ id: "framing-1", kind: "framing", label: "Zero", chars: 0, uncalibratedTokens: 0, tokens: 0, percent: 0 },
|
|
154
|
+
],
|
|
155
|
+
},
|
|
156
|
+
snapshot: {
|
|
157
|
+
source: "export-html", settled: true, attempts: 0, warning: null, systemPromptChars: 0,
|
|
158
|
+
estimateComponents: { promptText: 0, toolSchemas: 0, framing: 0, calibration: { multiplier: 1, samples: 0 } },
|
|
159
|
+
metadata: { currentDate: null, cwdDisplay: null, extraGuidelineCount: 0 },
|
|
160
|
+
tools: { totalCount: 0, omittedCount: 0, items: [] },
|
|
161
|
+
toolPromptEntries: { totalCount: 0, omittedCount: 0, names: [] },
|
|
162
|
+
skills: { totalCount: 0, omittedCount: 0, items: [] },
|
|
163
|
+
contextFiles: { totalCount: 1, omittedCount: 0, items: [{ displayPath: "zero.md", chars: 0 }] },
|
|
164
|
+
},
|
|
165
|
+
currentContext: {
|
|
166
|
+
usage: { tokens: 0, contextWindow: null, percent: 0 },
|
|
167
|
+
breakdown: {
|
|
168
|
+
estimateMethod: "weighted-character-estimate", reconstruction: "complete", estimatedTotalTokens: 0, actualMinusEstimatedTokens: 0,
|
|
169
|
+
sources: [{ id: "user-1", kind: "user-messages", label: "Zero context", chars: 0, estimatedTokens: 0, percent: 0 }],
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
lines: {
|
|
174
|
+
promptInjection: ["RAW_PROMPT_INJECTION <keep>& exact"],
|
|
175
|
+
promptDetailed: ["RAW_PROMPT_DETAILED </pre> exact"],
|
|
176
|
+
tokenBreakdown: ["RAW_CONTEXT_BREAKDOWN <raw> exact"],
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const normalizedInitial = promptContext.promptTestApi.normalizeStatsPromptInitial(structuredPromptPayload.promptContext.initialPrompt);
|
|
181
|
+
const normalizedSnapshot = promptContext.promptTestApi.normalizeStatsPromptSnapshot(structuredPromptPayload.promptContext.snapshot);
|
|
182
|
+
const normalizedCurrent = promptContext.promptTestApi.normalizeStatsPromptCurrent(structuredPromptPayload.promptContext.currentContext);
|
|
183
|
+
assert.equal(normalizedInitial.components[0].label, hostileLabel, "hostile-looking labels should remain literal text values");
|
|
184
|
+
assert.equal(normalizedInitial.components[1].tokens, 0, "real zero component tokens should survive normalization");
|
|
185
|
+
assert.equal(normalizedInitial.components[0].chars, null, "explicit null component chars should survive normalization");
|
|
186
|
+
assert.equal(normalizedSnapshot.systemPromptChars, 0, "real zero snapshot metrics should survive normalization");
|
|
187
|
+
assert.equal(normalizedSnapshot.metadata.currentDate, null, "explicit null metadata should survive normalization");
|
|
188
|
+
assert.equal(normalizedSnapshot.contextFiles.items[0].chars, 0, "real zero context-file chars should survive normalization");
|
|
189
|
+
assert.deepEqual({ ...normalizedCurrent.usage }, { tokens: 0, contextWindow: null, percent: 0 }, "current usage should preserve zero separately from null");
|
|
190
|
+
assert.equal(promptContext.promptTestApi.normalizeStatsPromptSnapshot({ ...structuredPromptPayload.promptContext.snapshot, systemPromptChars: "0" }), null, "numeric strings should reject only the malformed snapshot subsection");
|
|
191
|
+
|
|
192
|
+
const nativePrompt = promptContext.promptTestApi.renderStatsPrompt(structuredPromptPayload);
|
|
193
|
+
assert.equal(fakeNodesWithClass(nativePrompt, "stats-overlay-lines").length, 0, "fully valid structured Prompt/context must render no raw line blocks");
|
|
194
|
+
assert.equal(fakeNodesWithClass(nativePrompt, "stats-prompt-initial").length, 1);
|
|
195
|
+
assert.equal(fakeNodesWithClass(nativePrompt, "stats-prompt-snapshot").length, 1);
|
|
196
|
+
assert.equal(fakeNodesWithClass(nativePrompt, "stats-prompt-current").length, 1);
|
|
197
|
+
|
|
198
|
+
for (const [sectionName, expectedRaw] of [
|
|
199
|
+
["initialPrompt", "RAW_PROMPT_INJECTION <keep>& exact"],
|
|
200
|
+
["snapshot", "RAW_PROMPT_DETAILED </pre> exact"],
|
|
201
|
+
["currentContext", "RAW_CONTEXT_BREAKDOWN <raw> exact"],
|
|
202
|
+
]) {
|
|
203
|
+
const payload = structuredClone(structuredPromptPayload);
|
|
204
|
+
payload.promptContext[sectionName] = { malformed: true };
|
|
205
|
+
const rendered = promptContext.promptTestApi.renderStatsPrompt(payload);
|
|
206
|
+
const rawLines = fakeNodesWithClass(rendered, "stats-overlay-lines");
|
|
207
|
+
assert.equal(rawLines.length, 1, `${sectionName} should fall back independently`);
|
|
208
|
+
assert.equal(rawLines[0].textContent, expectedRaw, `${sectionName} should map to its matching legacy lines`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const rawPane = promptContext.promptTestApi.renderStatsRaw(structuredPromptPayload);
|
|
212
|
+
const rawText = fakeNodesWithClass(rawPane, "stats-overlay-lines").map((node) => node.textContent).join("\n");
|
|
213
|
+
assert.match(rawText, /RAW_PROMPT_INJECTION <keep>& exact\n\nRAW_PROMPT_DETAILED <\/pre> exact/, "raw Command outputs should preserve prompt/detail content byte-for-byte");
|
|
214
|
+
assert.match(rawText, /RAW_CONTEXT_BREAKDOWN <raw> exact/, "raw Command outputs should preserve the current context breakdown");
|
|
215
|
+
|
|
216
|
+
// Tab/tabpanel relationships and keyboard navigation.
|
|
217
|
+
assert.match(overlay, /button\.id = `statsOverlayTab-\$\{tab\.id\}`;/, "tabs should have stable ids");
|
|
218
|
+
assert.match(overlay, /setAttribute\("aria-controls", "statsOverlayBody"\)/, "tabs should control the shared tabpanel");
|
|
219
|
+
assert.match(overlay, /button\.tabIndex = active \? 0 : -1;/, "tabs should use a roving tabindex");
|
|
220
|
+
assert.match(overlay, /button\.addEventListener\("click", \(\) => activateStatsOverlayTab\(tab\.id, \{ focus: true \}\)\)/, "click and keyboard activation should restore focus after the tablist rerenders");
|
|
221
|
+
assert.match(overlay, /setAttribute\("aria-labelledby", `statsOverlayTab-\$\{statsOverlayActiveTab\}`\)/, "tabpanel should be labelled by the active tab");
|
|
222
|
+
assert.match(app, /elements\.statsOverlayTabs\?\.addEventListener\("keydown"[\s\S]*ArrowRight[\s\S]*Home[\s\S]*End[\s\S]*activateStatsOverlayTab\(STATS_OVERLAY_TABS\[nextIndex\]\.id, \{ focus: true \}\)/, "tablist should support arrow/Home/End keyboard navigation with focus follow");
|
|
223
|
+
assert.match(html, /<div id="statsOverlayTabs" class="stats-overlay-tabs" role="tablist"/, "tablist role should remain in markup");
|
|
224
|
+
assert.match(html, /<div id="statsOverlayBody" class="stats-overlay-body" role="tabpanel" tabindex="0">/, "tabpanel semantics should be in markup");
|
|
225
|
+
|
|
226
|
+
// Table captions and header scopes.
|
|
227
|
+
assert.match(app, /if \(caption\) table\.append\(make\("caption", "stats-overlay-table-caption", caption\)\);/, "stats tables should support captions");
|
|
228
|
+
assert.match(app, /th\.scope = "col";/, "stats table headers should declare column scope");
|
|
229
|
+
assert.match(daily, /"Daily tokens and cost by UTC day"/, "daily table should have a caption");
|
|
230
|
+
assert.match(models, /"Model token and cost comparison"/, "models table should have a caption");
|
|
231
|
+
assert.match(sessions, /"Most expensive sessions in the selected range"/, "sessions table should have a caption");
|
|
232
|
+
|
|
233
|
+
// Catppuccin styles for the new visuals and responsive behavior.
|
|
234
|
+
for (const selector of [
|
|
235
|
+
".stats-overlay-spend-chart",
|
|
236
|
+
".stats-overlay-spend-bar",
|
|
237
|
+
".stats-overlay-composition-track",
|
|
238
|
+
".stats-overlay-composition-segment.seg-cache-read",
|
|
239
|
+
".stats-overlay-driver-row",
|
|
240
|
+
".stats-overlay-driver-bar-fill",
|
|
241
|
+
".stats-overlay-legend-swatch",
|
|
242
|
+
".stats-overlay-chart-caption",
|
|
243
|
+
".stats-overlay-bar-lane",
|
|
244
|
+
".stats-overlay-bar-fill.cost",
|
|
245
|
+
".stats-overlay-table-caption",
|
|
246
|
+
]) {
|
|
247
|
+
assert.ok(css.includes(selector), `styles.css should define ${selector}`);
|
|
248
|
+
}
|
|
249
|
+
assert.match(css, /\.stats-overlay-bar-fill\.cost \{[^}]*var\(--ctp-green\)/s, "cost lane should use a distinct Catppuccin scale from tokens");
|
|
250
|
+
assert.match(css, /\.stats-overlay-spend-bar \{[^}]*var\(--ctp-green\)/s, "spend bars should use the Catppuccin palette");
|
|
251
|
+
|
|
252
|
+
const responsive = between(css, ".extension-dialog.stats-overlay-dialog {\n inset:", ".extension-dialog.release-dialog form {");
|
|
253
|
+
assert.match(responsive, /\.stats-overlay-drivers \{ grid-template-columns: 1fr; \}/, "narrow screens should stack driver sections");
|
|
254
|
+
assert.match(responsive, /\.stats-overlay-driver-row \.stats-overlay-driver-bar \{ grid-column: 1 \/ -1; \}/, "narrow screens should wrap driver bars");
|
|
255
|
+
assert.match(responsive, /\.stats-overlay-spend-chart \{ height: 5\.5rem; \}/, "narrow screens should shrink the spend chart");
|
|
256
|
+
assert.match(responsive, /\.stats-prompt-inventory \{\s*grid-template-columns: minmax\(0, 1fr\);\s*\}/, "narrow screens should stack Prompt/context inventory groups");
|
|
257
|
+
assert.match(responsive, /\.stats-prompt-table,[\s\S]*\.stats-prompt-table td \{\s*display: block;\s*width: 100%;\s*\}/, "narrow Prompt/context tables should become row cards rather than nested scrollers");
|
|
258
|
+
assert.match(responsive, /\.stats-prompt-table td::before \{\s*content: attr\(data-label\);/, "responsive Prompt/context row cards should retain visible column labels");
|
|
259
|
+
assert.match(css, /\.stats-prompt-table-wrap \{\s*overflow: visible;\s*\}/, "Prompt/context tables should not create a nested horizontal scroller");
|
|
260
|
+
assert.match(css, /\.stats-prompt-file-list li span:first-child \{[^}]*white-space: normal;/s, "long context paths should wrap");
|
|
261
|
+
|
|
262
|
+
// No chart dependency, canvas, or remote asset introduced by the stats section.
|
|
263
|
+
assert.doesNotMatch(statsUi, /canvas|new Image\(|https?:\/\//i, "stats visuals must stay dependency-free DOM/CSS");
|
|
264
|
+
assert.match(css, /\.stats-overlay-card\.tone-sky/, "tone-sky card style should exist for the overview effective-cost card");
|
|
265
|
+
|
|
266
|
+
console.log("stats-dashboard-static: all assertions passed");
|