@firstpick/pi-package-webui 0.8.4 → 0.8.6

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 (50) hide show
  1. package/README.md +24 -2
  2. package/bin/pi-webui.mjs +383 -31
  3. package/index.ts +8 -1
  4. package/lib/git-workflow-preferences.mjs +3 -0
  5. package/lib/session-summary-core.mjs +4 -3
  6. package/lib/trust-boundaries.mjs +13 -0
  7. package/lib/workspace-session-summaries.mjs +400 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1242 -267
  10. package/public/index.html +77 -4
  11. package/public/service-worker.js +3 -1
  12. package/public/stream-output-controller.mjs +327 -0
  13. package/public/styles.css +249 -70
  14. package/public/theme-contract.mjs +244 -0
  15. package/session-summary.ts +164 -4
  16. package/tests/aur-review-widget-static.test.mjs +2 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  18. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  19. package/tests/browser/session-summary.spec.mjs +131 -3
  20. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  21. package/tests/codex-fast-mode-static.test.mjs +2 -2
  22. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  23. package/tests/fast-mode-client-static.test.mjs +3 -2
  24. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  25. package/tests/fixtures/fake-pi.mjs +203 -2
  26. package/tests/git-workflow-preferences.test.mjs +7 -1
  27. package/tests/guided-git-aur-review.test.mjs +4 -3
  28. package/tests/http-endpoints-harness.test.mjs +224 -13
  29. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  30. package/tests/mobile-foundation-static.test.mjs +3 -4
  31. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  32. package/tests/mobile-static.test.mjs +63 -29
  33. package/tests/native-parity.test.mjs +1 -1
  34. package/tests/open-issue-wizard-static.test.mjs +2 -3
  35. package/tests/optional-feature-migration-frontend.test.mjs +3 -0
  36. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  37. package/tests/questionnaire-dialog.test.mjs +2 -2
  38. package/tests/remote-auth-settings-harness.test.mjs +9 -0
  39. package/tests/session-summary-core.test.mjs +183 -1
  40. package/tests/side-panel-section-reorder-static.test.mjs +2 -2
  41. package/tests/stream-lifecycle-core.test.mjs +134 -0
  42. package/tests/stream-output-controller.test.mjs +252 -0
  43. package/tests/stream-output-isolation-static.test.mjs +89 -0
  44. package/tests/streaming-ui-coupling.test.mjs +50 -0
  45. package/tests/subagent-gate-visibility.test.mjs +1 -1
  46. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  47. package/tests/theme-contract.test.mjs +104 -0
  48. package/tests/theme-customizer-static.test.mjs +82 -0
  49. package/tests/theme-scheme-mode.test.mjs +15 -0
  50. package/tests/workspace-session-summaries.test.mjs +288 -0
@@ -0,0 +1,89 @@
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 app = await readFile(join(root, "public", "app.js"), "utf8");
8
+ const controller = await readFile(join(root, "public", "stream-output-controller.mjs"), "utf8");
9
+
10
+ function functionBody(source, name) {
11
+ const match = new RegExp(`function\\s+${name}\\s*\\(`).exec(source);
12
+ assert.ok(match, `${name} should be defined`);
13
+ let parens = 0;
14
+ let open = -1;
15
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
16
+ if (source[index] === "(") parens += 1;
17
+ else if (source[index] === ")") parens -= 1;
18
+ else if (source[index] === "{" && parens === 0) {
19
+ open = index;
20
+ break;
21
+ }
22
+ }
23
+ assert.notEqual(open, -1, `${name} should open`);
24
+ let depth = 0;
25
+ for (let index = open; index < source.length; index += 1) {
26
+ if (source[index] === "{") depth += 1;
27
+ else if (source[index] === "}" && --depth === 0) return source.slice(open + 1, index);
28
+ }
29
+ assert.fail(`${name} should close`);
30
+ }
31
+
32
+ const forbiddenSinks = [
33
+ "renderWidgets", "renderFooter", "renderTabs", "renderStatus",
34
+ "renderWorkspaceDashboard", "renderContextMeter", "renderFeedbackTray",
35
+ "scheduleRefreshState", "scheduleRefreshFooter", "requestGitFooterWebuiPayload",
36
+ "trackSkillsFromEvent", "addEvent", "scheduleComposerModeButtons",
37
+ ".focus(", "scrollIntoView", "fetch(", "api(",
38
+ ];
39
+
40
+ assert.match(app, /import \{ createStreamOutputController \} from "\.\/stream-output-controller\.mjs";/);
41
+ assert.match(controller, /export function classifyTranscriptStreamEvent/);
42
+ assert.match(controller, /export function createStreamOutputController/);
43
+ assert.match(controller, /let frameHandle = null;[\s\S]*?let pending = \[\];[\s\S]*?let pendingBytes = 0;/, "controller should retain one cancellable bounded queue");
44
+ assert.match(controller, /if \(classification\.barrier\) \{[\s\S]*?flush\(\);/, "recognized raw end/error barriers should flush synchronously");
45
+ assert.match(controller, /COALESCIBLE_DELTA_TYPES[\s\S]*?function mergedAdjacentEntry[\s\S]*?previousKey !== entryCoalesceKey\(incoming\)/, "adjacent compatible stream deltas should coalesce before rendering");
46
+ assert.match(controller, /pending\.length >= entryLimit|pendingBytes \+ entry\.bytes > byteLimit/, "pending count and bytes should have explicit bounds");
47
+ assert.match(controller, /reason: "oversize-event"[\s\S]*?applyOversize\(entry\)/, "single oversize events should be applied directly rather than dropped");
48
+ assert.match(controller, /if \(!ownerIsCurrent\(owner\)\)[\s\S]*?reportStale/, "stale owners should fail closed");
49
+
50
+ for (const sink of forbiddenSinks) {
51
+ assert.equal(controller.includes(sink), false, `dependency-free controller must not reference forbidden sink ${sink}`);
52
+ }
53
+
54
+ const dispatch = functionBody(app, "dispatchTranscriptStreamEvent");
55
+ const rawMessageHandler = functionBody(app, "handleMessageUpdate");
56
+ const handleEvent = functionBody(app, "handleEvent");
57
+ const toolUpdate = functionBody(app, "applyTranscriptToolExecutionUpdate");
58
+ const dispatchIndex = handleEvent.indexOf("dispatchTranscriptStreamEvent(event)");
59
+ const tabActivityIndex = handleEvent.indexOf("ingestEventTabActivity(event)");
60
+ const skillTrackingIndex = handleEvent.indexOf("trackSkillsFromEvent(event)");
61
+ assert.ok(dispatchIndex >= 0 && dispatchIndex < tabActivityIndex && dispatchIndex < skillTrackingIndex, "raw dispatch must run before global tab/activity/skill processing");
62
+ assert.match(handleEvent, /if \(dispatchTranscriptStreamEvent\(event\)\) return;/, "consumed raw events must bypass the lifecycle switch");
63
+ assert.match(dispatch, /streamOutputController\.dispatch\(event,[\s\S]*?owner: transcriptStreamOwner/, "dispatch should bind updates to the current tab generation owner");
64
+
65
+ for (const sink of forbiddenSinks) {
66
+ assert.equal(dispatch.includes(sink), false, `raw dispatch seam must not reach forbidden sink ${sink}`);
67
+ assert.equal(rawMessageHandler.includes(sink), false, `message-update transcript sink must not reach forbidden sink ${sink}`);
68
+ }
69
+ assert.doesNotMatch(rawMessageHandler, /setRunIndicatorActivity|scheduleLiveTodoProgressWidgetSync|scheduleStreamingAssistantTextRender|scheduleChatFollowScroll/, "raw message deltas must bypass composer activity, widgets, and parallel schedulers");
70
+ assert.match(rawMessageHandler, /compactOutputActive\(\) && handleCompactMessageUpdate\(event\)/, "normal and compact modes should share the isolated controller sink");
71
+ assert.match(toolUpdate, /renderLiveToolRun\(run, \{ scroll: false \}\)/, "isolated tool updates should render in the controller frame rather than queue another tool frame");
72
+ assert.doesNotMatch(toolUpdate, /scheduleLiveToolRunRender/, "isolated tool updates must not create a parallel render queue");
73
+ assert.match(app, /applyToolExecutionUpdate: \(event\) => \{\s+if \(!compactOutputActive\(\)\) applyTranscriptToolExecutionUpdate\(event\);/, "raw tool execution updates should use only the transcript sink");
74
+ assert.doesNotMatch(app.slice(app.indexOf("const streamOutputController"), app.indexOf("let assistantErrorSurfacedThisRun")), /renderWidgets|renderFooter|renderTabs|renderStatus|renderFeedbackTray|setRunIndicatorActivity|scheduleLiveTodoProgressWidgetSync|addEvent|fetch\(|api\(/, "controller integration must inject transcript-only sinks");
75
+ const connectEvents = functionBody(app, "connectEvents");
76
+ assert.match(connectEvents, /streamOutputController\.cancel\(\);[\s\S]*?resetCompactLiveOutput\(\);/, "reconnect and tab switches should cancel retained raw frames before resetting live output");
77
+ assert.match(connectEvents, /source\.onerror = \(\) => \{[\s\S]*?streamOutputController\.flush\(\);[\s\S]*?streamOutputController\.cancel\(\);/, "an actual EventSource disconnect must flush and cancel retained transcript work before browser retry");
78
+ const barrier = functionBody(app, "flushTranscriptStreamBarrier");
79
+ const abort = functionBody(app, "abortActiveRun");
80
+ assert.match(barrier, /streamOutputController\.barrier\(event\.type\)/, "semantic lifecycle boundaries should flush raw output first");
81
+ assert.match(app, /"auto_retry_start",\s+"auto_retry_end",/, "retry start/end should be explicit stream barriers");
82
+ assert.ok(abort.indexOf('streamOutputController.barrier("user-abort")') < abort.indexOf("abortRequestInFlight = true"), "accepted user abort must flush transcript output before chrome/RPC transitions");
83
+ assert.doesNotMatch(handleEvent, /case "message_update"|case "tool_execution_update"/, "raw event switch cases consumed by the controller must be removed");
84
+ assert.doesNotMatch(app, /function scheduleStreamingAssistantTextRender|function handleToolExecutionUpdate|scheduleLiveToolRunRender/, "superseded raw render schedulers must be removed");
85
+ assert.match(app, /onUnknownStreamEvent: preserveUnknownTranscriptEvidence/, "unknown transcript-shaped events should retain transcript-only evidence");
86
+ assert.match(app, /reconcileUnknownTranscriptEvidenceAtBarrier\(event\)/, "unknown evidence should request authoritative reconciliation only at a semantic barrier");
87
+ assert.match(app, /streamIsolationDebug[\s\S]*?__piStreamIsolationDebug/, "the opt-in test diagnostic ledger should be exposed only behind the explicit debug flag");
88
+
89
+ console.log("stream-output-isolation-static.test.mjs passed");
@@ -201,6 +201,56 @@ assert.match(requestGitFooterWebuiPayload, /currentState\?\.isStreaming \|\| cur
201
201
  assert.match(findCaseBody(handleEvent, "agent_settled"), /currentState\) currentState = \{ \.\.\.currentState, isStreaming: false \};[\s\S]*?requestGitFooterWebuiPayload\(tabContext, \{ force: true \}\)/, "theory #8: forced git-footer refresh should only happen after agent settlement clears streaming state");
202
202
  assert.doesNotMatch(findCaseBody(handleEvent, "agent_end"), /isStreaming: false|requestGitFooterWebuiPayload/, "theory #8: low-level agent_end must not expose an idle window before retry or continuation");
203
203
 
204
+ // --- WS2a: lifecycle / chrome / todo ownership separation ---
205
+ // These are hard invariants, not future theories: raw stream output may not own
206
+ // lifecycle chrome, and lifecycle chrome may not be driven by token cadence.
207
+
208
+ const renderMessages = findFunctionBody(app, "renderMessages");
209
+ const refreshMessages = findFunctionBody(app, "refreshMessages");
210
+ const setRunIndicatorActivityBody = findFunctionBody(app, "setRunIndicatorActivity");
211
+ const startRunIndicatorTicker = findFunctionBody(app, "startRunIndicatorTicker");
212
+ const startLifecycleStateWatchdog = findFunctionBody(app, "startLifecycleStateWatchdog");
213
+ const reconcileTodoProgressFromMessages = findFunctionBody(app, "reconcileTodoProgressFromMessages");
214
+ const eventMayAffectSkillUsage = findFunctionBody(app, "eventMayAffectSkillUsage");
215
+ const flushSemanticReconcile = findFunctionBody(app, "flushSemanticReconcile");
216
+
217
+ // (1) Transcript rendering is transcript-only; chrome belongs to the reconciler.
218
+ assert.doesNotMatch(renderMessages, /renderFooter\(\)|renderFeedbackTray\(\)|renderWidgets\(\)|renderStatus\(\)/, "WS2a: renderMessages must be transcript-only and must not render footer/feedback/widget/status chrome");
219
+ assert.match(renderMessages, /renderAllMessages\(\)/, "WS2a: renderMessages must still own transcript rendering");
220
+
221
+ // (2) Todo progress derives from authoritative content, never token cadence.
222
+ assert.doesNotMatch(app, /function scheduleLiveTodoProgressWidgetSync/, "WS2a: the token-driven todo-progress scheduler must be removed");
223
+ assert.doesNotMatch(app, /scheduleLiveTodoProgressWidgetSync\(/, "WS2a: nothing may schedule token-driven todo-progress syncs");
224
+ assert.match(reconcileTodoProgressFromMessages, /authoritativeTodoProgressSourceText\([\s\S]*?syncLiveTodoProgressWidgetFromText\(/, "WS2a: todo progress must be derived from authoritative assistant content");
225
+ assert.match(refreshMessages, /reconcileTodoProgressFromMessages\(latestMessages, tabContext\.tabId\)/, "WS2a: todo progress must be derived once at authoritative message reconciliation");
226
+ assert.match(findFunctionBody(app, "syncLiveTodoProgressWidgetFromText"), /todoProgressSignatureByTab\.get\(tabId\) === signature\) return false/, "WS2a: the todo widget record may change only when its semantic value changes");
227
+
228
+ // (3) Activity wording is transcript-owned; composer/Stop changes on transitions.
229
+ assert.doesNotMatch(setRunIndicatorActivityBody, /^\s*scheduleComposerModeButtonsUpdate\(\);/m, "WS2a: activity wording must not unconditionally reconcile composer chrome");
230
+ assert.match(setRunIndicatorActivityBody, /syncLifecycleComposerState\(\)/, "WS2a: composer/Stop reconciliation must be gated on a lifecycle signature change");
231
+ assert.match(findFunctionBody(app, "syncLifecycleComposerState"), /signature === lifecycleComposerSignature\) return false/, "WS2a: an unchanged lifecycle signature must not schedule composer work");
232
+ assert.match(app, /runIndicatorBubble\.dataset\.streamOwned = "run-indicator"/, "WS2a: the live activity root must be a stable transcript-owned node");
233
+
234
+ // (4) The transcript ticker must not perform lifecycle/network reconciliation.
235
+ assert.doesNotMatch(startRunIndicatorTicker, /maybeRefreshRunIndicatorState\(\)/, "WS2a: the transcript-owned ticker must only repaint its own node");
236
+ assert.match(startLifecycleStateWatchdog, /maybeRefreshRunIndicatorState\(\)/, "WS2a: canonical state rechecks belong to the lifecycle watchdog");
237
+
238
+ // (5) Skills and event-log records happen once at semantic tool boundaries.
239
+ assert.doesNotMatch(eventMayAffectSkillUsage, /tool_execution_update|toolcall_start/, "WS2a: skill tracking must not be reachable from tool update/argument cadence");
240
+ assert.match(eventMayAffectSkillUsage, /"tool_execution_start", "tool_execution_end"/, "WS2a: skill tracking must run at semantic tool boundaries");
241
+ assert.match(trackSkillsFromEvent, /recordedToolBoundaryKeys\.has\(key\)[\s\S]*?trackSkillsFromToolInvocation[\s\S]*?if \(tracked && key\) rememberToolBoundaryRecordKey\(key\)/, "WS2a: usable tool skill records must be deduplicated without consuming a missing-args fallback");
242
+ assert.match(findCaseBody(handleEvent, "tool_execution_start"), /claimToolBoundaryRecord\(event, "log:start"\)\) addEvent\(/, "WS2a: tool start event-log records must be deduplicated by tool boundary");
243
+ assert.match(findCaseBody(handleEvent, "tool_execution_end"), /claimToolBoundaryRecord\(event, "log:end"\)\) addEvent\(/, "WS2a: tool end event-log records must be deduplicated by tool boundary");
244
+
245
+ // (6) Lifecycle boundaries reconcile chrome through one coalesced scheduler.
246
+ assert.match(findFunctionBody(app, "scheduleSemanticReconcile"), /mergeSemanticReconcileRequest\(semanticReconcilePending, dirty, tabContext\)[\s\S]*?semanticReconcileFrame !== null\) return;/, "WS2a: semantic reconciliation must coalesce partitioned requests to one pending flush");
247
+ assert.match(findFunctionBody(app, "mergeSemanticReconcileRequest"), /semanticReconcileContextKey\(tabContext\)[\s\S]*?pendingByContext\.set\(key, request\)/, "WS2a: semantic dirty flags must remain partitioned by tab generation");
248
+ assert.match(flushSemanticReconcile, /if \(dirty\.workflow\) reconcileGitWorkflowContinuation\(tabContext\.tabId\);[\s\S]*?if \(!isCurrentTabContext\(tabContext\)\) continue;/, "WS2a: originating workflow settlement must run before stale active-DOM work no-ops");
249
+ for (const [caseLabel, flag] of [["agent_start", "state: true"], ["agent_end", "messages: true"], ["message_end", "messages: true"], ["agent_settled", "messages: true"]]) {
250
+ assert.match(findCaseBody(handleEvent, caseLabel), new RegExp(`scheduleSemanticReconcile\\(\\{[\\s\\S]*?${flag}`), `WS2a: ${caseLabel} must reconcile chrome through the coalesced semantic scheduler`);
251
+ }
252
+ assert.match(findCaseBody(handleEvent, "agent_settled"), /usage: true,[\s\S]*?workflow: true,/, "WS2a: settlement must own the coalesced post-turn usage/workflow reconciliation");
253
+
204
254
  if (futureFailures.length) {
205
255
  assert.fail(`streaming/UI coupling invariants still failing (${futureFailures.length}):\n\n${futureFailures.map((failure, index) => `${index + 1}. ${failure}`).join("\n\n")}`);
206
256
  }
@@ -76,7 +76,7 @@ assert.match(app, /function renderSubagentGate\(tab, gate\)[\s\S]*subagentGateIs
76
76
  assert.match(app, /pruneDismissedSubagentGateKeys\(latestSubagents\?\.tabs, dismissedSubagentGateKeys\)/, "polling should prune stale dismissal keys");
77
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");
78
78
  assert.match(serviceWorker, /"\/subagent-gate-visibility\.mjs"/, "the PWA app shell should cache the visibility module");
79
- assert.match(server, /"subagent-gate-visibility\.mjs"/, "the server static allowlist should serve the visibility module");
79
+ assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "the server should serve typed visibility modules from the public asset boundary");
80
80
  assert.match(pkg.scripts.check, /node --check public\/subagent-gate-visibility\.mjs/, "the package check should syntax-check the visibility module");
81
81
 
82
82
  console.log("subagent gate visibility tests passed");
@@ -33,7 +33,7 @@ assert.match(css, /\.subagent-launch-slot-role \{[^}]*padding: 0\.34rem/, "role
33
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");
34
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");
35
35
  assert.match(css, /\.subagent-launch-slot-remove \{[^}]*color: var\(--ctp-red\)/, "destructive slot removal should have a textual control and warning color");
36
- assert.match(server, /"subagent-launch-slot-state\.mjs"/, "the pure browser module should be on the static allowlist");
36
+ assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "the server should serve typed browser modules from the public asset boundary");
37
37
  assert.match(serviceWorker, /pi-webui-pwa-v\d+[\s\S]*"\/subagent-launch-slot-state\.mjs"/, "the refreshed PWA cache should include the browser module");
38
38
  assert.match(pkg, /node --check public\/subagent-launch-slot-state\.mjs/, "package checks should syntax-check the browser state module");
39
39
 
@@ -0,0 +1,104 @@
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
+ import {
6
+ PI_THEME_EXPORT_FIELDS,
7
+ REQUIRED_THEME_TOKENS,
8
+ THEME_TOKEN_GROUPS,
9
+ ThemeContractError,
10
+ canonicalizeTheme,
11
+ effectiveThemeColors,
12
+ normalizeThemeFileName,
13
+ resolveThemeColor,
14
+ serializeTheme,
15
+ themeColorToRgb,
16
+ themeNameFromFileName,
17
+ validateTheme,
18
+ xterm256ToRgb,
19
+ } from "../public/theme-contract.mjs";
20
+
21
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
22
+ const schemaPath = join(root, "node_modules", "@earendil-works", "pi-coding-agent", "dist", "modes", "interactive", "theme", "theme-schema.json");
23
+
24
+ function fixture(overrides = {}) {
25
+ return {
26
+ name: "contract-fixture",
27
+ vars: { primary: "#123456", nested: "primary", neutral: 244 },
28
+ colors: Object.fromEntries(REQUIRED_THEME_TOKENS.map((token, index) => [token, index % 3 === 0 ? "nested" : index % 3 === 1 ? 39 : ""])),
29
+ export: { pageBg: "primary", cardBg: 235, infoBg: "", backgroundImage: "url(/fixture.png)" },
30
+ ...overrides,
31
+ };
32
+ }
33
+
34
+ assert.equal(REQUIRED_THEME_TOKENS.length, 51, "the browser contract must expose exactly 51 required tokens");
35
+ assert.equal(new Set(REQUIRED_THEME_TOKENS).size, 51, "required tokens must be unique");
36
+ assert.equal(THEME_TOKEN_GROUPS.length, 7, "the documented token inventory has seven groups");
37
+ assert.deepEqual(THEME_TOKEN_GROUPS.map(({ tokens }) => tokens.length), [11, 11, 10, 3, 9, 6, 1]);
38
+
39
+ const installedSchema = JSON.parse(await readFile(schemaPath, "utf8"));
40
+ assert.deepEqual(
41
+ [...REQUIRED_THEME_TOKENS].sort(),
42
+ [...installedSchema.properties.colors.required].sort(),
43
+ "the shared contract must stay in exact parity with the installed Pi schema",
44
+ );
45
+ assert.deepEqual(
46
+ [...PI_THEME_EXPORT_FIELDS].sort(),
47
+ Object.keys(installedSchema.properties.export.properties).sort(),
48
+ "Pi-native export fields must match the installed schema",
49
+ );
50
+
51
+ const valid = fixture();
52
+ assert.deepEqual(validateTheme(valid), { ok: true, issues: [] });
53
+ assert.equal(validateTheme(fixture({ name: "Pi Theme 1" })).ok, true, "theme names must retain installed Pi schema compatibility");
54
+ assert.equal(resolveThemeColor("nested", valid.vars), "#123456");
55
+ assert.equal(themeColorToRgb("neutral", valid.vars), "#808080");
56
+ assert.equal(effectiveThemeColors(valid).thinkingMax, valid.colors.thinkingXhigh, "thinkingMax must fall back to thinkingXhigh");
57
+ const explicitMax = fixture({ colors: { ...valid.colors, thinkingMax: "primary" } });
58
+ assert.equal(effectiveThemeColors(explicitMax).thinkingMax, "primary");
59
+
60
+ const native = canonicalizeTheme(valid);
61
+ assert.deepEqual(Object.keys(native.export), ["pageBg", "cardBg", "infoBg"]);
62
+ assert.equal(Object.hasOwn(native.export, "backgroundImage"), false, "WebUI-only export fields must not enter Pi-native files");
63
+ assert.deepEqual(Object.keys(native.colors), REQUIRED_THEME_TOKENS, "canonical colors must retain documented order");
64
+ assert.deepEqual(Object.keys(native.vars), ["nested", "neutral", "primary"], "variables must serialize deterministically");
65
+ const serialized = serializeTheme(valid);
66
+ assert.equal(serialized.endsWith("\n"), true, "canonical JSON must have one trailing newline");
67
+ assert.equal(serialized, `${JSON.stringify(native, null, 2)}\n`);
68
+ assert.deepEqual(JSON.parse(serialized), native);
69
+
70
+ for (const [label, theme, expectedPath] of [
71
+ ["unknown root", { ...valid, secret: true }, "secret"],
72
+ ["unknown color", { ...valid, colors: { ...valid.colors, madeUp: "" } }, "colors.madeUp"],
73
+ ["missing required", { ...valid, colors: Object.fromEntries(Object.entries(valid.colors).filter(([key]) => key !== "accent")) }, "colors.accent"],
74
+ ["float", { ...valid, colors: { ...valid.colors, accent: 1.5 } }, "colors.accent"],
75
+ ["range", { ...valid, colors: { ...valid.colors, accent: 256 } }, "colors.accent"],
76
+ ["short hex", { ...valid, colors: { ...valid.colors, accent: "#fff" } }, "colors.accent"],
77
+ ["missing variable", { ...valid, colors: { ...valid.colors, accent: "absent" } }, "colors.accent"],
78
+ ["unknown export", { ...valid, export: { ...valid.export, arbitrary: "value" } }, "export.arbitrary"],
79
+ ["circular variable", { ...valid, vars: { first: "second", second: "first" } }, "vars.first"],
80
+ ]) {
81
+ const result = validateTheme(theme);
82
+ assert.equal(result.ok, false, `${label} must be rejected`);
83
+ assert.ok(result.issues.some(({ path }) => path === expectedPath), `${label} must identify ${expectedPath}`);
84
+ }
85
+ assert.equal(validateTheme(valid, { allowWebuiExport: false }).ok, false, "Pi-only validation must reject WebUI export fields");
86
+ assert.throws(() => canonicalizeTheme({ ...valid, unexpected: true }), ThemeContractError);
87
+
88
+ assert.equal(normalizeThemeFileName("my-theme.json"), "my-theme.json");
89
+ assert.equal(themeNameFromFileName("my-theme.json"), "my-theme");
90
+ for (const invalid of ["", ".json", "../theme.json", "nested/theme.json", "theme.txt", "space theme.json", `x${"y".repeat(75)}.json`]) {
91
+ assert.throws(() => normalizeThemeFileName(invalid), ThemeContractError, `${JSON.stringify(invalid)} must not be a save basename`);
92
+ }
93
+
94
+ assert.equal(xterm256ToRgb(0), "#000000");
95
+ assert.equal(xterm256ToRgb(15), "#ffffff");
96
+ assert.equal(xterm256ToRgb(16), "#000000");
97
+ assert.equal(xterm256ToRgb(21), "#0000ff");
98
+ assert.equal(xterm256ToRgb(39), "#00afff");
99
+ assert.equal(xterm256ToRgb(232), "#080808");
100
+ assert.equal(xterm256ToRgb(255), "#eeeeee");
101
+ assert.throws(() => xterm256ToRgb(-1), RangeError);
102
+ assert.throws(() => xterm256ToRgb(1.5), RangeError);
103
+
104
+ console.log("theme-contract: ok");
@@ -0,0 +1,82 @@
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
+ import { REQUIRED_THEME_TOKENS, THEME_TOKEN_GROUPS } from "../public/theme-contract.mjs";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, html, css, serviceWorker, pkg, readme] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "index.html"), "utf8"),
11
+ readFile(join(root, "public", "styles.css"), "utf8"),
12
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
13
+ readFile(join(root, "package.json"), "utf8"),
14
+ readFile(join(root, "README.md"), "utf8"),
15
+ ]);
16
+
17
+ assert.equal(THEME_TOKEN_GROUPS.length, 7, "customizer contract should expose seven labelled groups");
18
+ assert.equal(REQUIRED_THEME_TOKENS.length, 51, "customizer contract should expose exactly 51 required tokens");
19
+ assert.equal(new Set(REQUIRED_THEME_TOKENS).size, 51, "required customizer tokens should be unique");
20
+
21
+ assert.match(html, /id="themeCustomizeButton"[^>]*aria-haspopup="dialog"[^>]*aria-controls="themeCustomizerDialog"/, "theme controls should expose an accessible Customize dialog launcher");
22
+ assert.match(html, /<dialog id="themeCustomizerDialog"[^>]*aria-labelledby="themeCustomizerTitle"[^>]*aria-describedby="themeCustomizerDescription"/, "customizer should use a labelled native dialog");
23
+ for (const id of [
24
+ "themeCustomizerName", "themeCustomizerScope", "themeCustomizerVisualFields", "themeCustomizerThinkingMax",
25
+ "themeCustomizerVars", "themeCustomizerExportFields", "themeCustomizerJson", "themeCustomizerPreview",
26
+ "themeCustomizerStatus", "themeCustomizerCancelButton", "themeCustomizerResetButton", "themeCustomizerSaveButton",
27
+ "themeCustomizerOverwrite", "themeCustomizerOverwriteButton",
28
+ ]) {
29
+ assert.match(html, new RegExp(`id="${id}"`), `customizer should expose #${id}`);
30
+ }
31
+ assert.match(html, /<option id="themeCustomizerProjectOption" value="project">This project<\/option>[\s\S]*<option value="global">Global themes<\/option>/, "save destination should offer project and global scopes");
32
+ assert.match(html, /role="status" aria-live="polite" aria-atomic="true"/, "customizer should expose an atomic polite validation surface");
33
+ assert.match(html, /role="alert" hidden>[\s\S]*Replace this exact target\?/, "overwrite should use a hidden-until-needed alert naming the target");
34
+
35
+ assert.match(app, /from "\.\/theme-contract\.mjs"/, "frontend should consume the shared browser-safe theme contract");
36
+ assert.match(serviceWorker, /"\/theme-contract\.mjs"/, "the PWA app shell should cache the startup-critical theme contract");
37
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
38
+ assert.match(pkg, /node --check public\/theme-contract\.mjs/, "the package check should syntax-check the startup-critical theme contract");
39
+ assert.match(app, /function themeDraftFromCatalog\(theme, name = theme\?\.name\)[\s\S]*colors: cloneThemeDraft\(theme\?\.colors \|\| \{\}\)/, "catalog metadata should be projected into a schema-only editable draft");
40
+ assert.match(app, /for \(const \{ name, label \} of group\.tokens\)/, "visual controls should render from the exact shared token inventory");
41
+ assert.match(app, /row\.dataset\.themeToken = name/, "every required token should receive a stable visual row");
42
+ assert.match(app, /swatch\.type = "color"[\s\S]*value\.type = "text"/, "each visual row should pair a color picker with a raw Pi value control");
43
+ assert.match(app, /const direct = \/\^#\[0-9a-f\]\{6\}\$\/i\.test\(raw\)[\s\S]*swatch\.disabled = !direct[\s\S]*Terminal default; edit the value to replace it/, "variable and terminal-default values should not be silently flattened by the color picker");
44
+ assert.match(app, /validateTheme\(candidate, \{ allowWebuiExport: true \}\)/, "client feedback should validate through the shared contract");
45
+ assert.match(app, /Advanced JSON is invalid:[\s\S]*last valid preview remains active/, "invalid JSON should stay editable without replacing the valid preview");
46
+ assert.match(app, /acceptThemeCustomizerDraft\(candidate, \{ syncJson: false, syncControls: true \}\)/, "valid JSON should synchronize back to visual and optional controls");
47
+ assert.match(app, /elements\.themeCustomizerJson\.value = serializeTheme\(canonical/, "valid visual changes should synchronize canonical advanced JSON");
48
+ assert.match(app, /applyTheme\(canonical, \{ persist: false \}\)/, "live preview must use the non-persisting apply path");
49
+ assert.match(app, /themeColorToRgb\(value, theme\?\.vars \|\| \{\}, fallback\)/, "WebUI preview should convert integer xterm colors through the shared contract");
50
+
51
+ assert.match(app, /function restoreThemeCustomizerOpeningState\(generation\)[\s\S]*state\.generation !== generation[\s\S]*applyTheme\(state\.opening\.theme, \{ persist: false \}\)[\s\S]*setCustomBackgroundRecord\(state\.opening\.background\)[\s\S]*applyCustomBackgroundOverride\(\)/, "cancel should generation-guard restoration of theme, meta/scheme presentation, and custom background");
52
+ assert.match(app, /themeCustomizerDialog\?\.addEventListener\("cancel"[\s\S]*closeThemeCustomizer\(\{ restore: true \}\)/, "Escape should restore and close through the same cancel path");
53
+ assert.match(app, /async function switchTab\(tabId\)[\s\S]*if \(themeCustomizerState\) closeThemeCustomizer\(\{ restore: true \}\)[\s\S]*refreshThemeCatalog\(tabContext\)/, "tab switches should restore an open preview and refresh project-bound catalog metadata");
54
+ assert.doesNotMatch(app.slice(app.indexOf("function themeScopeLabel("), app.indexOf("function renderThemeSelect(")), /localStorage\.(?:setItem|removeItem)/, "customizer preview/save workflow must not mutate browser theme storage directly");
55
+
56
+ assert.match(app, /api\("\/api\/themes\/custom", \{[\s\S]*tabId: state\.tabContext\.tabId[\s\S]*scope,[\s\S]*fileName: `\$\{name\}\.json`[\s\S]*overwrite,[\s\S]*expectedMtimeMs:/, "save should bind the server-derived target to the opening active tab and explicit scope");
57
+ assert.match(app, /state\.overwrite = \{ signature: themeCustomizerDraftSignature\(state\), scope, fileName, mtimeMs: details\.mtimeMs \}/, "overwrite confirmation should bind target, draft signature, and server mtime");
58
+ assert.match(app, /invalidateThemeCustomizerOverwrite\(\);[\s\S]*Any draft, name, or destination change cancels this confirmation/, "editing should invalidate overwrite confirmation");
59
+ assert.match(app, /code === "THEME_CHANGED"[\s\S]*was not overwritten[\s\S]*fresh target-bound confirmation/, "stale overwrite should stop and require fresh confirmation");
60
+ assert.match(app, /themeCustomizerCancelButton\.disabled = !!state\?\.saving[\s\S]*themeCustomizerResetButton\.disabled = !!state\?\.saving/, "cancel and reset should be disabled while a theme save is in flight");
61
+ assert.match(app, /function closeThemeCustomizer[\s\S]*if \(state\.saving\)[\s\S]*Wait for the theme save to finish/, "closing should not imply an in-flight filesystem save was cancelled");
62
+ assert.match(app, /function setThemeCustomizerStatus[\s\S]*urgent \? "alert" : "status"[\s\S]*urgent \? "assertive" : "polite"/, "blocking customizer errors should use assertive alert semantics");
63
+ assert.match(app, /code === "THEME_EXISTS"\) showThemeCustomizerOverwrite/, "same-target conflicts should enter explicit overwrite UI");
64
+ assert.match(app, /theme\.custom[\s\S]*theme-scope-badge/, "custom search results should receive scope badges");
65
+ assert.match(app, /Saved \$\{response\.data\?\.fileName[\s\S]*run \/reload or restart[\s\S]*No Pi or browser theme setting was changed/, "save guidance should truthfully describe manual TUI reload and non-mutation");
66
+
67
+ assert.match(css, /\.theme-customizer-dialog \{[\s\S]*height: min\(92dvh, 58rem\)[\s\S]*overflow: hidden/, "desktop customizer should be viewport-bounded and internally scrollable");
68
+ assert.match(css, /\.theme-customizer-scroll \{[\s\S]*overflow-y: auto[\s\S]*overscroll-behavior: contain/, "long token controls should scroll inside the dialog");
69
+ assert.match(css, /\.theme-token-grid \{[\s\S]*grid-template-columns: repeat\(auto-fit, minmax\(min\(100%, 25rem\), 1fr\)\)/, "token columns should collapse based on their container before labels and inputs overlap");
70
+ assert.match(css, /\.theme-token-swatch-note \{[^}]*min-width: 0[^}]*overflow-wrap: anywhere/, "token helper text should wrap inside narrow rows");
71
+ assert.match(css, /\.theme-customizer-optional-fields fieldset \{[^}]*min-width: 0/, "optional field cards should be allowed to shrink inside the dialog");
72
+ assert.match(css, /\.theme-customizer-export-fields \{[\s\S]*grid-template-columns: repeat\(auto-fit, minmax\(min\(100%, 12rem\), 1fr\)\)/, "export color fields should wrap before their cards overflow");
73
+ assert.match(css, /\.theme-customizer-export-fields input \{[^}]*width: 100%[^}]*min-width: 0/, "export color inputs should stay within their grid tracks");
74
+ assert.match(css, /@media \(max-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*\.theme-customizer-dialog[\s\S]*width: 100vw[\s\S]*\.theme-token-grid,[\s\S]*grid-template-columns: minmax\(0, 1fr\)/, "phone/coarse layouts should become a safe one-column full-height editor");
75
+ assert.match(css, /\.extension-dialog\.theme-customizer-dialog \{[\s\S]*inset: 0;[\s\S]*height: var\(--visual-viewport-height, 100dvh\);[\s\S]*max-height: var\(--visual-viewport-height, 100dvh\);[\s\S]*overflow: hidden;[\s\S]*border-radius: 0;/, "the later generic mobile dialog rule must not override full-height customizer geometry");
76
+ assert.match(css, /\.theme-token-swatch \{[^}]*width: 44px[^}]*height: 44px/, "visual color targets should remain at least 44px");
77
+ assert.match(css, /env\(safe-area-inset-bottom\)/, "dialog actions should honor mobile safe-area insets");
78
+
79
+ assert.match(readme, /### Custom themes[\s\S]*exact 51 required theme tokens[\s\S]*last valid preview[\s\S]*This project[\s\S]*Global themes/, "README should document controls, validation, and both scopes");
80
+ assert.match(readme, /does not select the theme or mutate Pi\/browser settings[\s\S]*run `\/reload` or restart Pi/, "README should document non-persistence and truthful TUI activation");
81
+
82
+ console.log("theme-customizer-static: all assertions passed");
@@ -96,6 +96,21 @@ assert.match(
96
96
  /async function applySchemeTheme\(options = \{\}\) \{\s*await setThemeByName\(effectiveThemeName\(\), \{ \.\.\.options, persist: false \}\);\s*\}/,
97
97
  "applySchemeTheme must never persist",
98
98
  );
99
+ assert.match(
100
+ app,
101
+ /function acceptThemeCustomizerDraft\([\s\S]*?applyTheme\(canonical, \{ persist: false \}\)/,
102
+ "custom theme live preview must use a non-persisting apply path",
103
+ );
104
+ assert.match(
105
+ app,
106
+ /function restoreThemeCustomizerOpeningState\(generation\)[\s\S]*?applyTheme\(state\.opening\.theme, \{ persist: false \}\)/,
107
+ "customizer cancel must restore presentation without persisting a selection",
108
+ );
109
+ assert.doesNotMatch(
110
+ app.slice(app.indexOf("function themeScopeLabel("), app.indexOf("function renderThemeSelect(")),
111
+ /storeTheme(?:Name|Mode)|storeSchemeTheme|setThemeByName\([^;]*persist: true/,
112
+ "customizer internals must not bypass chooseTheme or mutate Light/Dark/Auto persistence",
113
+ );
99
114
 
100
115
  // Auto mode also works on MediaQueryList implementations without addEventListener
101
116
  // (legacy addListener API), matching the mobileViewMedia wiring.