@firstpick/pi-package-webui 0.8.0 → 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.
Files changed (63) hide show
  1. package/README.md +34 -5
  2. package/bin/pi-webui.mjs +606 -102
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/npm-command.mjs +81 -0
  5. package/lib/queue-mutation.mjs +6 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/workspace-files-live-watcher.mjs +138 -0
  8. package/package.json +8 -3
  9. package/public/app.js +4231 -376
  10. package/public/index.html +265 -52
  11. package/public/mobile-shell-state.mjs +166 -0
  12. package/public/service-worker.js +60 -13
  13. package/public/styles.css +1790 -383
  14. package/public/subagent-gate-visibility.mjs +16 -0
  15. package/public/subagent-launch-slot-state.mjs +16 -0
  16. package/public/transcript-renderer.mjs +433 -0
  17. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  18. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  19. package/tests/browser/interaction-continuity.spec.mjs +897 -0
  20. package/tests/browser/mobile-foundation.spec.mjs +363 -0
  21. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  22. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  23. package/tests/browser/stats-overlay.spec.mjs +265 -0
  24. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  25. package/tests/codex-fast-mode-static.test.mjs +8 -5
  26. package/tests/compact-sections-static.test.mjs +20 -2
  27. package/tests/compaction-mutation-contract.test.mjs +18 -4
  28. package/tests/compaction-static.test.mjs +1 -0
  29. package/tests/completion-signal-contract.test.mjs +13 -2
  30. package/tests/component-update-api-static.test.mjs +67 -0
  31. package/tests/component-update-state.test.mjs +80 -0
  32. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  33. package/tests/fast-mode-client-static.test.mjs +7 -4
  34. package/tests/fixtures/fake-pi.mjs +305 -2
  35. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  36. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  37. package/tests/http-endpoints-harness.test.mjs +228 -2
  38. package/tests/interaction-state-stability-static.test.mjs +271 -0
  39. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  40. package/tests/mobile-foundation-static.test.mjs +71 -0
  41. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  42. package/tests/mobile-shell-state.test.mjs +69 -0
  43. package/tests/mobile-static.test.mjs +246 -39
  44. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  45. package/tests/native-parity-harness.test.mjs +2 -0
  46. package/tests/npm-command.test.mjs +64 -1
  47. package/tests/open-issue-wizard-static.test.mjs +2 -1
  48. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  49. package/tests/queue-mutation-contract.test.mjs +22 -0
  50. package/tests/service-worker-lifecycle.test.mjs +120 -0
  51. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  52. package/tests/sse-backpressure-harness.test.mjs +137 -0
  53. package/tests/stats-dashboard-static.test.mjs +266 -0
  54. package/tests/streaming-ui-coupling.test.mjs +7 -1
  55. package/tests/subagent-gate-visibility.test.mjs +18 -2
  56. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  57. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  58. package/tests/subagents-helper.test.mjs +90 -0
  59. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  60. package/tests/update-commands.test.mjs +4 -0
  61. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  62. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  63. package/webui-rpc-helper.mjs +175 -3
@@ -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");
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
 
6
6
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
7
  const app = await readFile(join(root, "public", "app.js"), "utf8");
8
+ const transcriptRenderer = await readFile(join(root, "public", "transcript-renderer.mjs"), "utf8");
8
9
 
9
10
  const SELF_CONTAINED_THEORY_TITLES = new Map([
10
11
  [0, "Live todo-progress widget rebuild"],
@@ -155,7 +156,12 @@ futureInvariant("theory #2: streaming assistant render must not derive all views
155
156
  });
156
157
 
157
158
  futureInvariant("theory #3: streaming markdown must not full-rebuild when earlier derived text changes", () => {
158
- assert.doesNotMatch(renderStreamingMarkdown, /!text\.startsWith\(state\.stableText\)[\s\S]*?block\.replaceChildren\(\)/, "retroactive todo/thinking rewrites should be confined to an unstable tail, not block.replaceChildren()");
159
+ const reconcileMarkdownSurface = findFunctionBody(transcriptRenderer, "reconcileMarkdownSurface");
160
+ assert.match(renderStreamingMarkdown, /transcriptRenderer\.reconcileMarkdownSurface\(\{[\s\S]*?stableBoundary: streamingMarkdownStableBoundary[\s\S]*?renderInto: renderMarkdownInto/, "streaming markdown must route through the coordinator's committed-block/mutable-tail reconciler");
161
+ assert.doesNotMatch(renderStreamingMarkdown, /block\.replaceChildren\(\)/, "streaming markdown must not replace the whole block directly");
162
+ assert.match(reconcileMarkdownSurface, /!value\.startsWith\(state\.stableText\)[\s\S]*?invalidateSelection: diverged/, "retroactive todo/thinking rewrites must be explicit invalidations, not silent full rebuilds");
163
+ assert.match(reconcileMarkdownSurface, /if \(boundary > state\.stableText\.length\)/, "committed blocks must stay mounted for append-only updates");
164
+ assert.match(reconcileMarkdownSurface, /for \(const node of state\.tailNodes\) node\.remove\(\)/, "only the mutable tail may be re-parsed per delta batch");
159
165
  });
160
166
 
161
167
  futureInvariant("theory #4: run-indicator activity changes must not render/scroll synchronously from token paths", () => {
@@ -7,6 +7,8 @@ import {
7
7
  pruneDismissedSubagentGateKeys,
8
8
  subagentGateIsTerminal,
9
9
  subagentGateKey,
10
+ subagentGateRunIds,
11
+ ungatedSubagentRuns,
10
12
  visibleSubagentGates,
11
13
  } from "../public/subagent-gate-visibility.mjs";
12
14
 
@@ -28,6 +30,20 @@ assert.equal(subagentGateKey("", "gate-a"), "");
28
30
  assert.equal(subagentGateIsTerminal({ status: "running" }), false);
29
31
  assert.equal(subagentGateIsTerminal({ status: "failed" }), true);
30
32
 
33
+ const mixedRunsTab = {
34
+ runs: [
35
+ { id: "direct-run", agents: [{ name: "scout" }] },
36
+ { id: "gate-run-1", agents: [{ name: "reviewer" }] },
37
+ { id: "gate-run-2", agents: [{ name: "planner" }] },
38
+ ],
39
+ gates: [
40
+ { attempts: [{ runId: "gate-run-1" }, { runId: " gate-run-2 " }, { runId: "" }] },
41
+ ],
42
+ };
43
+ assert.deepEqual([...subagentGateRunIds(mixedRunsTab)], ["gate-run-1", "gate-run-2"], "retry gates should identify every spawned run they own");
44
+ assert.deepEqual(ungatedSubagentRuns(mixedRunsTab).map((run) => run.id), ["direct-run"], "retry-gated runs should be omitted while direct subagent spawns remain visible");
45
+ assert.deepEqual(ungatedSubagentRuns({ runs: mixedRunsTab.runs, gates: [] }).map((run) => run.id), ["direct-run", "gate-run-1", "gate-run-2"], "ordinary spawns should remain visible when no retry gate owns them");
46
+
31
47
  assert.deepEqual(
32
48
  visibleSubagentGates(tab, new Set(), now).map((gate) => gate.id),
33
49
  ["running", "fresh", "updated", "untimed"],
@@ -55,10 +71,10 @@ const [app, css, serviceWorker, server, pkgRaw] = await Promise.all([
55
71
  const pkg = JSON.parse(pkgRaw);
56
72
 
57
73
  assert.match(app, /from "\.\/subagent-gate-visibility\.mjs"/, "the browser should load the retry-gate visibility policy");
58
- assert.match(app, /function subagentTabsWithRunningAgents\(\)[\s\S]*latestSubagents\?\.updatedAt[\s\S]*visibleSubagentGates\(tab, dismissedSubagentGateKeys, now\)/, "the side panel should use server time and filter expired or dismissed gates before deriving counts");
74
+ assert.match(app, /function subagentTabsWithRunningAgents\(\)[\s\S]*latestSubagents\?\.updatedAt[\s\S]*visibleSubagentGates\(tab, dismissedSubagentGateKeys, now\)[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*displayRuns/, "the side panel should filter retry-gated runs while retaining the gate attempts as their only rows");
59
75
  assert.match(app, /function renderSubagentGate\(tab, gate\)[\s\S]*subagentGateIsTerminal\(gate\)[\s\S]*Hide finished retry gate[\s\S]*dismissedSubagentGateKeys\.add\(key\)[\s\S]*renderSubagents\(\)[\s\S]*event\.detail === 0[\s\S]*focusTarget\?\.focus/, "terminal gate cards should expose an accessible hide button and preserve keyboard focus after rerendering");
60
76
  assert.match(app, /pruneDismissedSubagentGateKeys\(latestSubagents\?\.tabs, dismissedSubagentGateKeys\)/, "polling should prune stale dismissal keys");
61
- assert.match(css, /\.subagent-gate-actions[\s\S]*\.subagent-gate-close[\s\S]*min-width:\s*1\.75rem[\s\S]*\.subagent-gate-close:hover,[\s\S]*\.subagent-gate-close:focus-visible/, "the close control should remain compact and keyboard-visible");
77
+ assert.match(css, /\.subagent-gate-actions[\s\S]*\.subagent-gate-close[\s\S]*min-width:\s*1\.45rem[\s\S]*background:\s*transparent[\s\S]*\.subagent-gate-close:hover,[\s\S]*\.subagent-gate-close:focus-visible/, "the close control should remain minimal, compact, and keyboard-visible");
62
78
  assert.match(serviceWorker, /"\/subagent-gate-visibility\.mjs"/, "the PWA app shell should cache the visibility module");
63
79
  assert.match(server, /"subagent-gate-visibility\.mjs"/, "the server static allowlist should serve the visibility module");
64
80
  assert.match(pkg.scripts.check, /node --check public\/subagent-gate-visibility\.mjs/, "the package check should syntax-check the visibility module");
@@ -4,9 +4,41 @@ import {
4
4
  cloneLaunchSlotRoles,
5
5
  launchSlotRolesEqual,
6
6
  removeLaunchSlot,
7
+ subagentLaunchSlotSaveState,
7
8
  updateLaunchSlot,
8
9
  } from "../public/subagent-launch-slot-state.mjs";
9
10
 
11
+ assert.deepEqual(
12
+ subagentLaunchSlotSaveState({ hasConfig: true, hasDraft: true, dirty: true, activeConfigTab: true }),
13
+ { disabled: false, reason: "Ready to save." },
14
+ "a dirty draft owned by the active tab should be saveable",
15
+ );
16
+ assert.deepEqual(
17
+ subagentLaunchSlotSaveState({ hasConfig: true, hasDraft: true, dirty: true, activeConfigTab: false }),
18
+ { disabled: true, reason: "Switch back to the tab where these changes were made to save them." },
19
+ "a dirty draft should explain that its owning tab must be active",
20
+ );
21
+ assert.deepEqual(
22
+ subagentLaunchSlotSaveState({ hasConfig: true, hasDraft: true, dirty: true, loading: true, activeConfigTab: true }),
23
+ { disabled: true, reason: "Wait for agent models to finish loading." },
24
+ "loading should temporarily block saving with an explanation",
25
+ );
26
+ assert.deepEqual(
27
+ subagentLaunchSlotSaveState({ hasConfig: true, hasDraft: true, dirty: true, saving: true, activeConfigTab: true }),
28
+ { disabled: true, reason: "Saving agent models…" },
29
+ "saving should remain disabled while the request is in progress",
30
+ );
31
+ assert.deepEqual(
32
+ subagentLaunchSlotSaveState({ hasConfig: true, hasDraft: true, activeConfigTab: true }),
33
+ { disabled: true, reason: "Change a model or thinking preset to enable saving." },
34
+ "a clean draft should explain how saving becomes available",
35
+ );
36
+ assert.deepEqual(
37
+ subagentLaunchSlotSaveState(),
38
+ { disabled: true, reason: "Agent model configuration is not available for this tab." },
39
+ "missing configuration should explain why saving is unavailable",
40
+ );
41
+
10
42
  const initial = {
11
43
  reviewer: [{ id: "reviewer:base", model: "anthropic/reviewer", thinking: "high" }],
12
44
  worker: [{ id: "worker:base", model: null, thinking: null }],
@@ -16,15 +16,21 @@ const [html, app, css, server, serviceWorker, pkg] = await Promise.all([
16
16
  assert.match(html, /<details id="subagentLaunchSlots" class="subagent-launch-slots">[\s\S]*<summary class="subagent-launch-slots-summary">[\s\S]*id="subagentLaunchSlotsTitle">Agent models<[\s\S]*id="subagentLaunchSlotRoles"[\s\S]*id="subagentsStatus"[\s\S]*id="subagentsBox"/, "launch-slot configuration should be a native collapsible surface separate from the live monitor");
17
17
  assert.doesNotMatch(html, /<details id="subagentLaunchSlots"[^>]*\sopen(?:\s|>)/, "Agent models should start collapsed to keep the Subagents panel compact");
18
18
  assert.match(html, /id="subagentLaunchSlotScope"[^>]*aria-describedby="subagentLaunchSlotScopeStatus"/, "scope selection should use stable accessible help");
19
+ assert.match(html, /id="subagentLaunchSlotsSave"[^>]*aria-describedby="subagentLaunchSlotsDirty"[^>]*disabled[\s\S]*id="subagentLaunchSlotsDirty"[^>]*role="status"[^>]*aria-live="polite"/, "save availability explanations should be visible and associated with the disabled control");
19
20
  assert.match(html, /id="subagentLaunchSlotsAnnouncer"[^>]*aria-live="polite"[^>]*aria-atomic="true"/, "slot changes should be announced accessibly");
20
21
  assert.match(app, /from "\.\/subagent-launch-slot-state\.mjs"/, "the browser should use the pure launch-slot state helper");
21
22
  assert.match(app, /const subagentLaunchSlotReloadTabs = new Set\(\)[\s\S]*subagentLaunchSlotReloadTabs\.add\(activeTabId\)[\s\S]*subagentLaunchSlotReloadTabs\.delete\(activeTabId\)/, "reload reminders should be tracked per tab until reload");
22
23
  assert.match(app, /subagentLaunchSlotsSummaryStatus\.textContent[\s\S]*"Unsaved changes"[\s\S]*"Saved · reload this tab"[\s\S]*subagentLaunchSlots\.open = true/, "the collapsed summary should surface state and reopen for errors or required reloads");
24
+ assert.match(app, /const saveState = subagentLaunchSlotSaveState\([\s\S]*subagentLaunchSlotsSave\.disabled = saveState\.disabled[\s\S]*`Unsaved changes · \$\{saveState\.reason\}`/, "save eligibility and its adjacent explanation should come from one canonical state");
23
25
  assert.doesNotMatch(app, /`(?:Model|Thinking) · \$\{slotLabel\}`/, "visible field labels should stay compact while aria-labels retain slot context");
26
+ assert.doesNotMatch(app, /make\("(?:p|span)", "subagent-launch-slot-(?:meta|id)"/, "redundant assignment summaries and internal slot IDs should stay out of the compact editor");
27
+ assert.match(app, /if \(slots\.length > 1\)[\s\S]*`Slot \$\{ordinal\}`/, "slot headings should appear only when a role has multiple slots");
24
28
  assert.match(app, /api\(`\/api\/subagents\/config\?\$\{query\}`/, "the editor should load configuration through the tab-scoped API");
25
29
  assert.match(app, /api\("\/api\/subagents\/config", \{ method: "POST", body, scoped: false \}\)/, "the editor should save through the localhost-scoped configuration API");
26
- assert.match(css, /\.subagent-launch-slots \{[\s\S]*container: subagent-launch-slots \/ inline-size[\s\S]*@container subagent-launch-slots \(max-width: 30rem\)[\s\S]*\.subagent-launch-slot-controls \{ grid-template-columns: minmax\(0, 1fr\); \}/, "launch-slot controls should respond to the narrow side-panel container rather than only the viewport");
27
- assert.match(css, /\.subagent-launch-slot-controls \{[\s\S]*grid-column: 1 \/ -1/, "model and thinking controls should own the full slot-row width before responsive stacking");
30
+ assert.match(css, /\.subagent-launch-slots \{[\s\S]*container: subagent-launch-slots \/ inline-size[\s\S]*@container subagent-launch-slots \(max-width: 22rem\)[\s\S]*\.subagent-launch-slot-controls \{ grid-template-columns: minmax\(0, 1fr\); \}/, "launch-slot controls should stack only in genuinely narrow side-panel containers");
31
+ assert.match(css, /\.subagent-launch-slots-summary \{[^}]*min-height: 2\.35rem/, "the summary should retain the compact density contract");
32
+ assert.match(css, /\.subagent-launch-slot-role \{[^}]*padding: 0\.34rem/, "role surfaces should retain the compact density contract");
33
+ assert.match(css, /\.subagent-launch-slot-controls \{[\s\S]*grid-column: 1 \/ -1[\s\S]*grid-template-columns: repeat\(2, minmax\(0, 1fr\)\)/, "model and thinking controls should remain paired where side-panel space permits");
28
34
  assert.match(css, /\.sr-only \{[\s\S]*clip-path: inset\(50%\)[\s\S]*white-space: nowrap/, "screen-reader announcements should stay visually hidden without leaving the accessibility tree");
29
35
  assert.match(css, /\.subagent-launch-slot-remove \{[^}]*color: var\(--ctp-red\)/, "destructive slot removal should have a textual control and warning color");
30
36
  assert.match(server, /"subagent-launch-slot-state\.mjs"/, "the pure browser module should be on the static allowlist");
@@ -55,6 +55,14 @@ const ctx = {
55
55
  mode: "rpc",
56
56
  hasUI: true,
57
57
  cwd: "/tmp/subagent-helper-test",
58
+ modelRegistry: {
59
+ getAvailable() {
60
+ return [
61
+ { provider: "anthropic", id: "claude-opus-4-8", contextWindow: 200_000 },
62
+ { provider: "openai-codex", id: "gpt-5.6-terra", contextWindow: 128_000 },
63
+ ];
64
+ },
65
+ },
58
66
  sessionManager: {
59
67
  getBranch() { return branchEntries; },
60
68
  },
@@ -89,8 +97,11 @@ await writeFile(settingsFile, `${JSON.stringify({
89
97
  process.env.PI_WEBUI_SETTINGS_FILE = settingsFile;
90
98
  const asyncSessionFile = path.join(asyncRunDir, "reviewer-session.jsonl");
91
99
  await writeFile(asyncSessionFile, [
100
+ JSON.stringify({ type: "custom", customType: "stats_initial_prompt_estimate", timestamp: "2026-07-19T11:59:59.000Z", data: { actualInjectedTokens: 1234, privatePrompt: "must not leave the child session" } }),
92
101
  JSON.stringify({ type: "message", timestamp: "2026-07-19T12:00:00.000Z", message: { role: "assistant", content: [{ type: "thinking", thinking: "Checking structured transcript extraction" }, { type: "text", text: "REVIEWER STREAM 1 OF 18" }, { type: "toolCall", id: "review-call", name: "bash", arguments: { command: "sleep 5" } }, { type: "text", text: "Review complete." }] } }),
93
102
  JSON.stringify({ type: "message", timestamp: "2026-07-19T12:00:01.000Z", message: { role: "toolResult", toolCallId: "review-call", toolName: "bash", isError: false, content: [{ type: "text", text: "(no output)\nreviewer tool output line" }] } }),
103
+ JSON.stringify({ type: "message", timestamp: "2026-07-19T12:00:02.000Z", message: { role: "assistant", timestamp: "2026-07-19T12:00:00.000Z", provider: "anthropic", model: "claude-opus-4-8", usage: { input: 100, output: 40, cacheRead: 20, cacheWrite: 5 }, content: [] } }),
104
+ JSON.stringify({ type: "message", timestamp: "2026-07-19T12:00:06.000Z", message: { role: "assistant", timestamp: "2026-07-19T12:00:03.000Z", provider: "anthropic", model: "claude-opus-4-8", usage: { input: 200, output: 60, cacheRead: 30, cacheWrite: 10 }, content: [] } }),
94
105
  "",
95
106
  ].join("\n"));
96
107
  const asyncStatusFile = path.join(asyncRunDir, "status.json");
@@ -281,6 +292,16 @@ assert.deepEqual(workflowOutputResponse.data, {
281
292
  status: "running",
282
293
  activityState: "stdout",
283
294
  model: "openai-codex/gpt-5.6-terra:xhigh",
295
+ telemetry: {
296
+ promptInjectionTokens: null,
297
+ inputTokens: null,
298
+ outputTokens: null,
299
+ tokenSpeed: null,
300
+ contextTokens: null,
301
+ contextWindow: null,
302
+ model: null,
303
+ effort: null,
304
+ },
284
305
  recentTools: [],
285
306
  recentOutput: ["Inspecting helper contract", "Implementing local output route"],
286
307
  transcript: [],
@@ -302,6 +323,17 @@ const asyncOutputResponse = JSON.parse(asyncOutputNotice.message.slice("__PI_WEB
302
323
  assert.equal(asyncOutputResponse.ok, true);
303
324
  assert.equal(asyncOutputResponse.data.agent.model, "anthropic/claude-opus-4-8:high");
304
325
  assert.equal(asyncOutputResponse.data.agent.thinking, "high");
326
+ assert.deepEqual(asyncOutputResponse.data.agent.telemetry, {
327
+ promptInjectionTokens: 1234,
328
+ inputTokens: 300,
329
+ outputTokens: 100,
330
+ tokenSpeed: 20,
331
+ contextTokens: 240,
332
+ contextWindow: 200_000,
333
+ model: "anthropic/claude-opus-4-8:high",
334
+ effort: "high",
335
+ }, "ordinary live output should expose only derived bounded child-session telemetry");
336
+ assert.doesNotMatch(JSON.stringify(asyncOutputResponse.data.agent.telemetry), /must not leave the child session/, "selected telemetry must not leak custom-entry payloads");
305
337
  assert.deepEqual(asyncOutputResponse.data.agent.recentOutput, [
306
338
  "REVIEWER STREAM 1 OF 18",
307
339
  "▶ bash {\"command\":\"sleep 5\"}",
@@ -385,6 +417,53 @@ assert.deepEqual(incompleteToolResponse.data.agent.transcript, [{
385
417
  content: [{ type: "toolCall", id: "tail-call", name: "read", arguments: "{\"path\":\"README.md\"}" }],
386
418
  }], "a live or truncated session tail should retain an unpaired tool call for a pending tool card");
387
419
 
420
+ const malformedTelemetrySessionFile = path.join(asyncRunDir, "malformed-telemetry-session.jsonl");
421
+ await writeFile(malformedTelemetrySessionFile, [
422
+ "{not json}",
423
+ JSON.stringify({ type: "custom", customType: "stats_initial_prompt_estimate", data: { actualInjectedTokens: "invalid", privatePrompt: "malformed custom payload" } }),
424
+ JSON.stringify({ type: "message", timestamp: "2026-07-19T12:03:01.000Z", message: { role: "assistant", timestamp: "2026-07-19T12:03:00.000Z", usage: { input: -1, output: Number.MAX_VALUE }, content: [] } }),
425
+ ].join("\n"));
426
+ await writeFile(asyncStatusFile, JSON.stringify({
427
+ runId: "run-a",
428
+ mode: "parallel",
429
+ state: "running",
430
+ startedAt: Date.now() - 1000,
431
+ lastUpdate: Date.now(),
432
+ steps: [{ agent: "reviewer", status: "running", sessionFile: malformedTelemetrySessionFile, model: "anthropic/claude-opus-4-8:high", thinking: "high" }],
433
+ }));
434
+ await helperCommand.handler(JSON.stringify({
435
+ requestId: "malformed-telemetry-subagent-output-test",
436
+ action: "subagent-output",
437
+ payload: { runId: "run-a", agentId: "run-a:step:0:reviewer" },
438
+ }), ctx);
439
+ const malformedTelemetryResponse = helperResponse("malformed-telemetry-subagent-output-test");
440
+ assert.deepEqual(malformedTelemetryResponse.data.agent.telemetry, {
441
+ promptInjectionTokens: null,
442
+ inputTokens: null,
443
+ outputTokens: null,
444
+ tokenSpeed: null,
445
+ contextTokens: null,
446
+ contextWindow: 200_000,
447
+ model: "anthropic/claude-opus-4-8:high",
448
+ effort: "high",
449
+ }, "malformed child-session telemetry should fail closed while preserving authoritative model metadata");
450
+ assert.doesNotMatch(JSON.stringify(malformedTelemetryResponse.data.agent.telemetry), /malformed custom payload/, "malformed custom-entry payloads must not reach selected output");
451
+
452
+ await writeFile(asyncStatusFile, JSON.stringify({
453
+ runId: "run-a",
454
+ mode: "parallel",
455
+ state: "running",
456
+ startedAt: Date.now() - 1000,
457
+ lastUpdate: Date.now(),
458
+ steps: [{ agent: "reviewer", status: "running", sessionFile: asyncSessionFile, recentOutput: [], currentTool: "bash", currentToolArgs: "sleep 5", model: "anthropic/claude-opus-4-8:high", thinking: "high" }],
459
+ }));
460
+ await helperCommand.handler(JSON.stringify({
461
+ requestId: "restored-telemetry-subagent-output-test",
462
+ action: "subagent-output",
463
+ payload: { runId: "run-a", agentId: "run-a:step:0:reviewer" },
464
+ }), ctx);
465
+ assert.equal(helperResponse("restored-telemetry-subagent-output-test").data.agent.telemetry.inputTokens, 300, "a valid retained locator should replace an earlier malformed live locator");
466
+
388
467
  for (const handler of extensionHandlers.get("tool_execution_start") || []) {
389
468
  handler({
390
469
  type: "tool_execution_start",
@@ -449,6 +528,16 @@ assert.equal(outputResponse.data.agent.currentTool, "bash");
449
528
  assert.equal(outputResponse.data.agent.currentToolArgs, "npm test");
450
529
  assert.equal(outputResponse.data.agent.model, "openai-codex/gpt-5.6-terra:xhigh");
451
530
  assert.equal(outputResponse.data.agent.thinking, "xhigh");
531
+ assert.deepEqual(outputResponse.data.agent.telemetry, {
532
+ promptInjectionTokens: null,
533
+ inputTokens: null,
534
+ outputTokens: null,
535
+ tokenSpeed: null,
536
+ contextTokens: null,
537
+ contextWindow: 128_000,
538
+ model: "openai-codex/gpt-5.6-terra:xhigh",
539
+ effort: "xhigh",
540
+ }, "foreground snapshots without child-session locators should retain explicit unknown measurements");
452
541
  assert.deepEqual(outputResponse.data.agent.recentOutput, ["Running focused tests", "12 assertions passed"]);
453
542
  assert.deepEqual(outputResponse.data.agent.transcript, [], "foreground snapshots without a child session transcript should retain the recentOutput-only fallback");
454
543
  assert.deepEqual(outputResponse.data.agent.recentTools, [{ tool: "read", args: "package.json", endMs: 1000 }]);
@@ -674,6 +763,7 @@ await helperCommand.handler(JSON.stringify({
674
763
  const restoredOutput = helperResponse("restored-async-output");
675
764
  assert.equal(restoredOutput.ok, true, "retained async output should remain accessible after a parent-session resume");
676
765
  assert.equal(restoredOutput.data.agent.status, "cancelled");
766
+ assert.equal(restoredOutput.data.agent.telemetry.inputTokens, 300, "retained runs should re-read bounded telemetry from a still-available child session locator");
677
767
 
678
768
  const retainedParentBranch = branchEntries;
679
769
  branchEntries = [];
@@ -88,7 +88,7 @@ assert.match(results.group, /^Tooltip group · 2 tabs\nWorkspaces: projects\/pi-
88
88
  assert.match(results.group, /Click to switch · Drop tabs here to add$/, "group hover summary should preserve the drop-target affordance");
89
89
  assert.doesNotMatch(terminalTabMetaSource, /\bpid\b/i, "compact tab metadata should not expose the process PID");
90
90
  assert.equal(app.match(/applyStyledTooltip\(button, terminalTabTooltip\(tab\)/g)?.length, 2, "single and grouped-item tabs should share one tooltip formatter");
91
- assert.match(renderTerminalTabGroupSource, /applyStyledTooltip\(button, terminalTabGroupTooltip\(group, groupTitle\), \{ ariaLabel: false, description: true, placement: "right", variant: "workspace" \}\)/, "group hover disclosure should use the shared floating tooltip layer to the right of its trigger");
91
+ assert.match(renderTerminalTabGroupSource, /applyStyledTooltip\(button, terminalTabGroupTooltip\(group, groupTitle\), \{ ariaLabel: false, description: true, placement: "right", variant: "workspace", targetKey: `terminal-group:\$\{group\.key\}:switch` \}\)/, "group hover disclosure should use the shared floating tooltip layer with stable semantic identity to the right of its trigger");
92
92
  assert.doesNotMatch(renderTerminalTabGroupSource, /terminal-tab-group-summary|menu\.append\(summary\)/, "group hover disclosure should not render an in-flow summary that shifts group menu items");
93
93
  assert.match(app, /footerTooltipNode\.setAttribute\("role", "tooltip"\)/, "the shared visual tooltip should expose tooltip semantics");
94
94
  assert.match(app, /document\.addEventListener\("keydown", \(event\) => \{[\s\S]*event\.key === "Escape" && footerTooltipTarget[\s\S]*hideFooterTooltip\(footerTooltipTarget\)[\s\S]*\}, true\)/, "Escape should dismiss both hover- and focus-triggered tooltips from the document capture phase");
@@ -37,6 +37,10 @@ const [server, app, readme] = await Promise.all([
37
37
  assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*piUpdateHelpSupportsAll/, "server should inspect update help from the selected Pi command");
38
38
  assert.match(server, /resolveCommand\(\["update", "--help"\]\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should plan commands from the capability result");
39
39
  assert.match(server, /const piTasks = await resolvePiUpdateCommands\(\{ all \}\)/, "all-mode task resolution should preserve the selected Pi update plan");
40
+ assert.match(server, /function resolveSelectedPiCommand\(piArgs\)[\s\S]*resolvePiCommandInvocation\(options\.piBin, piArgs\)/, "selected Windows Pi shims should be normalized to an executable Node and CLI invocation");
41
+ assert.match(server, /resolveCommandDirectory\(options\.piBin\)[\s\S]*piInstallDirectory[\s\S]*env: piInstallDirectory \? prependedPathEnvironment\(piInstallDirectory\)/, "Pi update tasks should put the selected Pi installation first on PATH");
42
+ assert.match(server, /preferredDirectories: \[\.\.\.new Set\(piTasks\.map\(\(task\) => task\.piInstallDirectory\)/, "package-root updates should prefer npm from the selected Pi installation");
43
+ assert.match(server, /async function runUpdateTask\(task\)[\s\S]*env: task\.env/, "update task execution should apply its install-aware environment");
40
44
  assert.match(server, /allCommand: piUpdateCommandText\(\{ all: true, supportsAll: true \}\)[\s\S]*allFallbackCommand: piUpdateCommandText\(\{ all: true \}\)/, "update status should expose preferred and fallback command text");
41
45
  assert.match(app, /"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"/, "update confirmation should describe capability selection and fallback");
42
46
  assert.match(readme, /first checks the selected Pi executable's `pi update --help`[\s\S]*uses `pi update --all` when advertised[\s\S]*otherwise falls back/, "documentation should explain the checked fallback behavior");