@firstpick/pi-package-webui 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +76 -19
  2. package/bin/pi-webui.mjs +864 -140
  3. package/lib/WEBUI_TUI_NATIVE_PARITY.json +26 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/optional-feature-catalog.mjs +29 -0
  6. package/lib/optional-feature-migration.mjs +410 -0
  7. package/lib/session-summary-core.mjs +320 -0
  8. package/lib/session-summary-preferences.mjs +267 -0
  9. package/lib/thinking-stream-recovery.mjs +156 -0
  10. package/lib/ui-layout-settings.mjs +254 -0
  11. package/package.json +5 -40
  12. package/public/app.js +2898 -92
  13. package/public/index.html +77 -14
  14. package/public/service-worker.js +1 -1
  15. package/public/styles.css +669 -2
  16. package/session-summary.ts +403 -0
  17. package/tests/aur-review-widget-static.test.mjs +3 -2
  18. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  19. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  20. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  21. package/tests/browser/interaction-continuity.spec.mjs +29 -0
  22. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  23. package/tests/browser/session-summary.spec.mjs +271 -0
  24. package/tests/codex-fast-mode-static.test.mjs +10 -9
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/fast-mode-client-static.test.mjs +2 -2
  27. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  28. package/tests/fixtures/fake-pi.mjs +51 -1
  29. package/tests/git-workflow-preferences.test.mjs +4 -2
  30. package/tests/http-endpoints-harness.test.mjs +507 -4
  31. package/tests/interaction-state-stability-static.test.mjs +3 -0
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +118 -103
  36. package/tests/native-parity-harness.test.mjs +9 -1
  37. package/tests/native-parity.test.mjs +23 -1
  38. package/tests/open-issue-wizard-static.test.mjs +1 -1
  39. package/tests/optional-feature-migration-frontend.test.mjs +72 -0
  40. package/tests/optional-feature-migration.test.mjs +142 -0
  41. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  42. package/tests/questionnaire-dialog.test.mjs +511 -0
  43. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  44. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  45. package/tests/session-summary-core.test.mjs +491 -0
  46. package/tests/session-summary-preferences.test.mjs +103 -0
  47. package/tests/side-panel-resize-static.test.mjs +1 -0
  48. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  49. package/tests/subagent-launch-slots.test.mjs +1 -1
  50. package/tests/thinking-stream-recovery.test.mjs +88 -0
  51. package/tests/ui-layout-settings.test.mjs +92 -0
  52. package/tests/webui-settings-locking.test.mjs +159 -0
@@ -56,6 +56,8 @@ const requiredNativeCommands = [
56
56
  "safety-guard-setup",
57
57
  "git-workflow-setup",
58
58
  "workflow-setup",
59
+ "summary",
60
+ "summary-setup",
59
61
  "model",
60
62
  "theme",
61
63
  "scoped-models",
@@ -94,6 +96,14 @@ assert.equal(workflowSetupSurface.webStatus, "implemented", "/workflow-setup bro
94
96
  assert.equal(workflowSetupSurface.sensitive, true, "/workflow-setup should be tracked as a sensitive policy mutation");
95
97
  assert.deepEqual(workflowSetupSurface.guards, ["localhost", "confirmation"], "/workflow-setup should require both localhost and explicit confirmation guards");
96
98
 
99
+ for (const id of ["/summary", "/summary-setup"]) {
100
+ const surface = slashSurfaces.find((item) => item.id === id);
101
+ assert.ok(surface, `${id} should be represented in the native parity matrix`);
102
+ assert.equal(surface.webStatus, "implemented", `${id} browser-native support should be implemented`);
103
+ assert.equal(surface.sensitive, true, `${id} sends or configures provider-bound session data`);
104
+ assert.deepEqual(surface.guards, ["confirmation"], `${id} should use explicit setup/disclosure confirmation without a localhost-only restriction`);
105
+ }
106
+
97
107
  const selectorMatch = app.match(/const NATIVE_SELECTOR_COMMANDS = new Set\(\[(.*?)\]\)/s);
98
108
  assert.ok(selectorMatch, "frontend native selector command set should be discoverable");
99
109
  const frontendSelectorCommands = [...selectorMatch[1].matchAll(/"([^"]+)"/g)].map((match) => match[1]);
@@ -141,7 +151,19 @@ assert.match(server, /url\.pathname === "\/api\/auth-providers" && req\.method =
141
151
  assert.match(server, /url\.pathname === "\/api\/auth-logout" && req\.method === "POST"/, "server should expose localhost-only POST /api/auth-logout");
142
152
  assert.match(server, /url\.pathname === "\/api\/workflow-policy" && req\.method === "GET"[\s\S]*requireLocalhost\(req, "Workflow policy setup is only allowed from localhost\."\)/, "workflow policy reads should be localhost-only");
143
153
  assert.match(server, /url\.pathname === "\/api\/workflow-policy" && req\.method === "POST"[\s\S]*requireLocalhostRoute\(req, url\.pathname\)[\s\S]*requireWorkflowPolicyJsonRequest\(req\)[\s\S]*expectedRevision: body\.expectedRevision/, "workflow policy saves should be registry-guarded, same-origin JSON, and revision protected");
144
- assert.match(app, /name === "workflow-setup" && !hasLoadedRpcCommand\(name\)[\s\S]*case "workflow-setup":[\s\S]*openNativeWorkflowSetupDialog\(\)/, "frontend should gate exact /workflow-setup native routing on the active tab's loaded extension catalog");
154
+ assert.match(app, /\(name === "workflow-setup" \|\| name === "summary" \|\| name === "summary-setup"\) && !hasLoadedRpcCommand\(name\)[\s\S]*case "workflow-setup":[\s\S]*openNativeWorkflowSetupDialog\(\)/, "frontend should gate exact summary and setup commands on the active Pi tab's loaded extension catalog");
155
+ assert.ok(app.includes('const summaryMatch = String(message || "").trim().match(/^\\/summary(?:\\s+(refresh))?$/i);'), "frontend should intercept only exact /summary and /summary refresh command forms");
156
+ assert.match(app, /case "summary":[\s\S]*openSessionSummaryForTab\(activeTabId, \{ refresh: summaryMatch\?\.\[1\][\s\S]*case "summary-setup":[\s\S]*openNativeSessionSummarySetupDialog\(\)/, "frontend should route exact summary commands to the non-blocking overlay without normal prompt dispatch");
157
+ assert.match(app, /async function openSessionSummaryForTab\(tabId = activeTabId, \{ refresh = false \} = \{\}\)[\s\S]*hasAvailableCommand\("summary", \{ tabId \}\)[\s\S]*preferences\?\.configured[\s\S]*openNativeSessionSummarySetupDialog[\s\S]*openSessionSummaryOverlay[\s\S]*requestSessionSummaryGeneration\(tabId, \{ refresh \}\)/, "frontend /summary action should remain catalog-gated, open setup when needed, and force exact refresh requests");
158
+ assert.match(app, /function normalizeSessionSummaryClientState\(value, previous = null, \{ resetProjection = false \} = \{\}\)[\s\S]*sessionChanged[\s\S]*resetProjection \|\| sessionChanged \? null : previous[\s\S]*function handleSessionSummaryEvent\(event\)[\s\S]*resetProjection: event\?\.kind === "state"/, "client projection should clear across session IDs and active-branch state events while preserving ordinary failure state");
159
+ assert.match(app, /title: "Save session summary setup\?"[\s\S]*if \(!reviewed\) return;[\s\S]*confirmed: true[\s\S]*requestSessionSummaryGeneration/, "summary setup should require explicit privacy/cost confirmation before persistence and immediate first generation");
160
+ assert.match(server, /args\.includes\(sessionSummaryExtensionPath\)[\s\S]*args\.push\("--extension", sessionSummaryExtensionPath\)/, "each WebUI child should explicitly receive the package-owned summary extension");
161
+ assert.match(server, /url\.pathname === "\/api\/session-summary\/preferences" && req\.method === "GET"[\s\S]*url\.pathname === "\/api\/session-summary\/preferences" && req\.method === "PUT"[\s\S]*url\.pathname === "\/api\/session-summary\/generate" && req\.method === "POST"/, "server should expose authenticated tab-scoped preferences and generation routes");
162
+ assert.match(server, /function requireSessionSummaryJsonRequest\(req\)[\s\S]*application\/json[\s\S]*same-origin/, "summary mutations should fail closed on cross-origin-simple request shapes");
163
+ assert.match(server, /function publicSessionSummaryPreferences\(value\)[\s\S]*scope: "text-and-tool-names"[\s\S]*preferences: publicSessionSummaryPreferences\(storedPreferences\)/, "summary preference responses should project only approved bounded fields instead of exposing preserved unknown keys");
164
+ assert.match(server, /tab\.titleSource === "default" \|\| tab\.titleSource === "auto"[\s\S]*renameTab\(tab, details\.title, \{ source: "auto"/, "summary title bridge should preserve explicit tab names");
165
+ assert.match(server, /filterSessionSummaryTranscriptMessages[\s\S]*SESSION_SUMMARY_RPC_TYPE[\s\S]*SESSION_SUMMARY_DISPLAY_TYPE/, "summary control and display messages should remain outside the normal WebUI transcript");
166
+ assert.match(server, /const SESSION_SUMMARY_GENERATE_TIMEOUT_MS = 105 \* 1000[\s\S]*async function triggerSessionSummary[\s\S]*SESSION_SUMMARY_GENERATE_TIMEOUT_MS[\s\S]*status: "failure"[\s\S]*broadcastSessionSummaryState\(tab, "failure"\)[\s\S]*throw error/, "summary RPC dispatch should use the extension-scale timeout and broadcast bounded terminal failure before rethrowing");
145
167
  assert.match(app, /title: "Save reviewed workflow permission ceiling\?"[\s\S]*if \(!reviewed\) return;[\s\S]*body: \{ policy: policyToSave, expectedRevision: data\.revision \?\? null \}/, "frontend should explicitly confirm the normalized workflow policy before revision-protected save");
146
168
  assert.match(server, /url\.pathname === "\/api\/native-parity" && req\.method === "GET"/, "server should expose the native parity matrix for clients/tests");
147
169
  assert.match(server, /const NATIVE_DOWNLOAD_TOKEN_TTL_MS = 10 \* 60 \* 1000/, "native downloads should use short-lived tokens");
@@ -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-v62/, "the PWA cache name must change with browser wiring updates");
72
+ assert.match(serviceWorker, /pi-webui-pwa-v71/, "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,72 @@
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, html, css, readme] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "index.html"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "README.md"), "utf8"),
12
+ ]);
13
+
14
+ function sourceBetween(startMarker, endMarker) {
15
+ const start = app.indexOf(startMarker);
16
+ const end = app.indexOf(endMarker, start + startMarker.length);
17
+ assert.ok(start >= 0 && end > start, `expected ${startMarker} before ${endMarker}`);
18
+ return app.slice(start, end);
19
+ }
20
+
21
+ assert.match(html, /id="optionalFeatureMigrationSurface"[^>]*role="status"[^>]*aria-live="polite"[^>]*aria-atomic="false"/, "startup/migration feedback should have a polite non-atomic persistent status mount");
22
+ assert.match(html, /id="optionalFeatureMigrationDialog"[\s\S]*aria-labelledby="optionalFeatureMigrationDialogTitle"[\s\S]*id="optionalFeatureMigrationChooseDetails"[\s\S]*id="optionalFeatureMigrationConfirmButton"/, "migration should use one accessible combined confirmation with an optional Choose view");
23
+ assert.match(html, /id="optionalFeatureMigrationDialogError"[^>]*role="alert"/, "terminal dialog errors should be alerts");
24
+
25
+ const refreshSource = sourceBetween("async function refreshOptionalFeaturePackageStatuses", "function clearGitFooterPayloadState");
26
+ assert.match(refreshSource, /api\("\/api\/optional-features", \{ scoped: false \}\)/, "browser refresh should consume the cached server snapshot");
27
+ assert.doesNotMatch(refreshSource, /showDirectoryPicker|FileSystem|local-resource|node_modules|\.pi\/agent/, "browser refresh must not scan the host");
28
+
29
+ const surfaceSource = sourceBetween("function renderOptionalFeatureMigrationSurface", "function applyOptionalFeatureMigrationSnapshot");
30
+ assert.match(surfaceSource, /Checking optional features…[\s\S]*elapsed[\s\S]*Core ready/, "surface should expose checking elapsed time and a truthful ready summary");
31
+ assert.match(surfaceSource, /Previous optional features need migration[\s\S]*Migrate…[\s\S]*Later/, "action-required migration should expose Migrate and persisted Later actions");
32
+ assert.match(surfaceSource, /safely excluded[\s\S]*Copy recommended fix[\s\S]*Recheck/, "conflicts should explain safe exclusion using a recommended path-free fix and recheck");
33
+ assert.match(surfaceSource, /started safely without optional companions[\s\S]*Recheck/, "degraded startup should remain core-safe and recheckable");
34
+ assert.match(surfaceSource, /Migrating optional features[\s\S]*Retry failed[\s\S]*Copy commands[\s\S]*Restart tab/, "progress and recovery should expose the required sequential/retry/copy/deferred-restart actions");
35
+ assert.match(surfaceSource, /if \(optionalFeatureRestartNotice\.restartDeferred\)[\s\S]*Restart tab[\s\S]*else[\s\S]*Dismiss/, "a deferred restart action must remain persistent until restart succeeds");
36
+ assert.match(surfaceSource, /setAttribute\("role", "alert"\)/, "only conflict/partial terminal feedback should add alert semantics");
37
+ assert.match(surfaceSource, /optional-feature-migration-completion-summary[\s\S]*card\.focus/, "completion summary should receive focus once");
38
+ assert.doesNotMatch(surfaceSource, /percent|% complete/i, "package-manager progress must not fabricate percentages");
39
+
40
+ const dialogSource = sourceBetween("function renderOptionalFeatureMigrationDialog", "async function copyFailedOptionalFeatureCommands");
41
+ assert.match(dialogSource, /selectedByDefault === true[\s\S]*isOptionalFeatureDisabled/, "server defaults should be preselected while browser-disabled features stay unselected");
42
+ assert.match(dialogSource, /Previously enabled[\s\S]*Previously disabled[\s\S]*source:/, "expandable details should explain previous state and sanitized source kind");
43
+ assert.match(dialogSource, /This is the only confirmation before retry|only confirmation before Pi installs/i, "dialog copy should make the single confirmation boundary explicit");
44
+
45
+ const batchSource = sourceBetween("async function installOptionalFeatureBatch", "function runPublishWorkflow");
46
+ assert.match(batchSource, /body: \{ tab: activeTabId, featureIds, revision: optionalFeatureMigrationSnapshot\.revision, migration \}/, "every batch apply should send tab, cached revision, and migration intent");
47
+ assert.match(batchSource, /staleRevision[\s\S]*refreshOptionalFeaturePackageStatuses[\s\S]*refreshedSignature !== candidateSignature[\s\S]*optionalFeatureRevisionChurn/, "stale revisions should refetch, re-show on material candidate changes, retry silently once, and recover repeated churn without false failures");
48
+ assert.match(batchSource, /error\.optionalFeatureCandidatesChanged \|\| error\.optionalFeatureRevisionChurn[\s\S]*restoreOptionalFeatureInstallStates[\s\S]*reopen/, "candidate changes and repeated stale revisions should restore untouched rows and reopen the plan");
49
+ assert.match(batchSource, /for \(const feature of candidates\)[\s\S]*result\?\.ok === true[\s\S]*optionalFeatureInstallFailureFromBatchResult/, "partial batches should preserve and settle every per-feature terminal result");
50
+ assert.match(batchSource, /output\.slice\(-4000\)|slice\(-4000\)/, "localhost response output should remain bounded before entering activity/row feedback");
51
+ assert.match(batchSource, /restart\.autoRestarted \|\| restart\.restartDeferred[\s\S]*optionalFeatureRestartNotice/, "batch response restart fields should drive visible restart feedback");
52
+ assert.doesNotMatch(batchSource, /const reloadMessage|await appConfirmText\([^)]*Reload the active Pi tab/, "successful migration must not add a separate restart confirmation");
53
+
54
+ const eventSource = sourceBetween("function handleEvent(event)", "function connectEvents");
55
+ assert.match(eventSource, /webui_optional_feature_migration[\s\S]*applyOptionalFeatureMigrationSnapshot\(event\.snapshot\)/, "SSE migration snapshots should update reconnect-safe state");
56
+ assert.match(eventSource, /webui_optional_feature_restart_completed[\s\S]*webui_optional_feature_restart_deferred/, "SSE restart events should be consumed");
57
+ const progressRecoverySource = sourceBetween("function applyOptionalFeatureProgressStates", "function refreshOptionalFeatureMigrationElapsedText");
58
+ assert.match(progressRecoverySource, /progress\.restartDeferred === true[\s\S]*optionalFeatureRestartNotice/, "cached progress must rehydrate the deferred Restart action after a full browser reload");
59
+ assert.match(progressRecoverySource, /progress\.autoRestarted === true[\s\S]*optionalFeatureRestartNotice/, "cached progress should rehydrate the completed restart notice");
60
+ assert.match(app, /source\.onopen[\s\S]*refreshOptionalFeaturePackageStatuses\(\)/, "event-stream reconnect should recover the current cached server snapshot");
61
+ const timerSource = sourceBetween("function refreshOptionalFeatureMigrationElapsedText", "function optionalFeatureMigrationAction");
62
+ assert.doesNotMatch(timerSource, /renderOptionalFeatureMigrationSurface\(\)/, "elapsed ticks must not replace and re-announce the entire live region");
63
+ assert.match(timerSource, /querySelector\("\.optional-feature-migration-detail"\)/, "elapsed ticks should update only the detail node");
64
+
65
+ assert.match(css, /\.optional-feature-migration-surface[\s\S]*\.optional-feature-migration-dialog[\s\S]*@media \(max-width: 34rem\)/, "migration surfaces should have desktop and responsive styling");
66
+ assert.match(css, /\.optional-feature-migration-card:focus-visible/, "focused completion summary should have a visible focus treatment");
67
+
68
+ assert.match(readme, /read-only startup audit/i, "README should document startup auditing");
69
+ assert.match(readme, /--migrate-optional-features[\s\S]*--migration-dry-run/, "README should document explicit unattended migration and dry-run flags");
70
+ assert.match(readme, /Retry failed[\s\S]*Copy commands[\s\S]*Recheck/i, "README should document migration troubleshooting actions");
71
+
72
+ console.log("optional feature migration frontend static tests passed");
@@ -0,0 +1,142 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, readFile, rm, stat } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import {
7
+ OptionalFeatureAuditCoordinator,
8
+ OptionalFeatureMigrationStore,
9
+ classifyOptionalFeature,
10
+ } from "../lib/optional-feature-migration.mjs";
11
+
12
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-optional-feature-migration-"));
13
+ const stateFile = path.join(root, "private", "optional-feature-migration.json");
14
+ const catalog = [
15
+ { featureId: "registered", packageName: "@test/registered", expectedSpec: "^1.0.0" },
16
+ { featureId: "local", packageName: "@test/local", expectedSpec: "^1.0.0" },
17
+ { featureId: "legacy", packageName: "@test/legacy", expectedSpec: "^1.0.0" },
18
+ { featureId: "conflict", packageName: "@test/conflict", expectedSpec: "^1.0.0" },
19
+ { featureId: "missing", packageName: "@test/missing", expectedSpec: "^1.0.0" },
20
+ ];
21
+
22
+ try {
23
+ assert.equal(classifyOptionalFeature({ configured: true, installed: true }, {}).state, "registered");
24
+ assert.equal(classifyOptionalFeature({ locallyConfigured: true }, {}).state, "local-resource");
25
+ assert.equal(classifyOptionalFeature({ legacyEvidence: true }, {}).state, "legacy-migratable");
26
+ assert.equal(classifyOptionalFeature({ installed: true }, {}).state, "unknown");
27
+ assert.equal(classifyOptionalFeature({}, {}).state, "missing");
28
+ assert.equal(classifyOptionalFeature({ resourceConflict: true }, {}).state, "conflict");
29
+ assert.equal(classifyOptionalFeature({ configured: true, installed: true, updateAvailable: true }, {}).state, "update-available");
30
+ assert.equal(classifyOptionalFeature({}, { available: true, enabled: false }).state, "disabled");
31
+
32
+ const store = new OptionalFeatureMigrationStore({ filePath: stateFile });
33
+ await store.write({
34
+ schemaVersion: 1,
35
+ lastSuccessfulAudit: {
36
+ webuiVersion: "0.8.2",
37
+ completedAt: "2026-01-01T00:00:00.000Z",
38
+ features: { legacy: { available: true, enabled: true, sourceKind: "legacy-webui-bundled", installedVersion: "1.0.0" } },
39
+ },
40
+ pendingUpgrade: { fromVersion: "0.8.2", startedAt: "2026-01-02T00:00:00.000Z", featureIds: ["legacy"] },
41
+ secret: "must-not-survive",
42
+ });
43
+ const persisted = JSON.parse(await readFile(stateFile, "utf8"));
44
+ assert.equal(persisted.schemaVersion, 1);
45
+ assert.equal(Object.hasOwn(persisted, "secret"), false);
46
+ if (process.platform !== "win32") assert.equal((await stat(stateFile)).mode & 0o777, 0o600);
47
+
48
+ const events = [];
49
+ const coordinator = new OptionalFeatureAuditCoordinator({
50
+ catalog,
51
+ store,
52
+ webuiVersion: "0.8.3",
53
+ deadlineMs: 250,
54
+ onEvent: (event) => events.push(event),
55
+ collectStatuses: async () => [
56
+ { ...catalog[0], configured: true, installed: true, installedVersion: "1.0.0", installedRoot: "/private/registered", topLevelResources: [] },
57
+ { ...catalog[1], locallyConfigured: true, installed: true, installedVersion: "1.0.0", topLevelResources: ["/private/local/index.ts"] },
58
+ { ...catalog[2], legacyEvidence: true, installed: true, installedVersion: "1.0.0", legacyPath: "/private/legacy" },
59
+ { ...catalog[3], configured: true, locallyConfigured: true, resourceConflict: true, installed: true },
60
+ { ...catalog[4], installed: false },
61
+ ],
62
+ });
63
+ await assert.rejects(
64
+ coordinator.runMutation("pending", async () => {}),
65
+ (error) => error.statusCode === 409 && /not actionable/.test(error.message),
66
+ "checking snapshots must never authorize mutations",
67
+ );
68
+
69
+ const snapshot = await coordinator.recheck({ reason: "test" });
70
+ assert.equal(snapshot.phase, "action-required");
71
+ assert.equal(snapshot.installKind, "upgrade");
72
+ assert.match(snapshot.revision, /^sha256:[a-f0-9]{64}$/);
73
+ assert.deepEqual(snapshot.summary, { ready: 2, migratable: 1, missing: 1, conflicts: 1, disabled: 0, unknown: 0 });
74
+ assert.deepEqual(snapshot.features.map(({ state }) => state), ["registered", "local-resource", "legacy-migratable", "conflict", "missing"]);
75
+ assert.equal(snapshot.features[2].selectedByDefault, true);
76
+ assert.equal(JSON.stringify(snapshot).includes("/private/"), false, "browser snapshot must not expose host paths");
77
+ assert.equal(Object.isFrozen(snapshot), true);
78
+ assert.equal(Object.isFrozen(snapshot.features), true);
79
+ assert.throws(() => coordinator.assertRevision("sha256:stale"), (error) => error.statusCode === 409);
80
+ assert.ok(events.some(({ event }) => event === "audit-complete"));
81
+
82
+ await coordinator.dismiss(snapshot.revision);
83
+ assert.equal(coordinator.current().phase, "action-required", "conflicts remain actionable after migration dismissal");
84
+ assert.equal(coordinator.current().features.find(({ featureId }) => featureId === "legacy").selectedByDefault, false);
85
+ const dismissed = await store.read();
86
+ assert.deepEqual(dismissed.dismissedMigration.featureIds, ["legacy"]);
87
+ const afterDismissRecheck = await coordinator.recheck({ reason: "dismiss-persistence" });
88
+ assert.equal(afterDismissRecheck.phase, "action-required", "conflict remains actionable across rechecks");
89
+ assert.equal(afterDismissRecheck.features.find(({ featureId }) => featureId === "legacy").selectedByDefault, false, "dismissed migration stays unselected across rechecks");
90
+
91
+ let releaseMutation;
92
+ const blockedMutation = coordinator.runMutation(coordinator.current().revision, () => new Promise((resolve) => { releaseMutation = resolve; }));
93
+ await assert.rejects(
94
+ coordinator.runMutation(coordinator.current().revision, async () => {}),
95
+ (error) => error.statusCode === 409,
96
+ );
97
+ assert.throws(() => coordinator.assertIdle(), (error) => error.statusCode === 409, "recheck routes must reject while mutation is active");
98
+ await assert.rejects(
99
+ coordinator.dismiss(coordinator.current().revision),
100
+ (error) => error.statusCode === 409,
101
+ "dismiss must reject while mutation is active",
102
+ );
103
+ releaseMutation("done");
104
+ assert.equal(await blockedMutation, "done");
105
+
106
+ const timeoutStore = new OptionalFeatureMigrationStore({ filePath: path.join(root, "timeout", "state.json") });
107
+ const timeoutCoordinator = new OptionalFeatureAuditCoordinator({
108
+ catalog: [catalog[0]],
109
+ store: timeoutStore,
110
+ webuiVersion: "0.8.3",
111
+ deadlineMs: 20,
112
+ collectStatuses: async () => {
113
+ await delay(100);
114
+ return [{ ...catalog[0], configured: true, installed: true }];
115
+ },
116
+ });
117
+ const timeoutSnapshot = await timeoutCoordinator.recheck();
118
+ assert.equal(timeoutSnapshot.phase, "degraded");
119
+ assert.equal(timeoutSnapshot.features[0].state, "unknown");
120
+ assert.equal(timeoutSnapshot.diagnostic.kind, "audit-timeout");
121
+ assert.deepEqual([...timeoutCoordinator.excludedPackageNames()], ["@test/registered"]);
122
+ await assert.rejects(
123
+ timeoutCoordinator.runMutation(timeoutSnapshot.revision, async () => {}),
124
+ (error) => error.statusCode === 409 && /not actionable/.test(error.message),
125
+ "degraded snapshots must never authorize mutations",
126
+ );
127
+
128
+ const malformedFile = path.join(root, "malformed", "state.json");
129
+ await mkdir(path.dirname(malformedFile), { recursive: true });
130
+ await import("node:fs/promises").then(({ writeFile }) => writeFile(malformedFile, "{not-json", "utf8"));
131
+ const malformedCoordinator = new OptionalFeatureAuditCoordinator({
132
+ catalog: [catalog[0]],
133
+ store: new OptionalFeatureMigrationStore({ filePath: malformedFile }),
134
+ webuiVersion: "0.8.3",
135
+ collectStatuses: async () => [{ ...catalog[0], configured: true, installed: true }],
136
+ });
137
+ assert.equal((await malformedCoordinator.recheck()).phase, "degraded");
138
+
139
+ console.log("optional feature migration tests passed");
140
+ } finally {
141
+ await rm(root, { recursive: true, force: true });
142
+ }
@@ -0,0 +1,267 @@
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, 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", "service-worker.js"), "utf8"),
11
+ ]);
12
+
13
+ // --- Contract constants ----------------------------------------------------
14
+
15
+ assert.match(
16
+ app,
17
+ /const UI_LAYOUT_SCHEMA_VERSION = 1;[\s\S]*const UI_LAYOUT_ENDPOINT = "\/api\/interface-preferences";/,
18
+ "the browser controller should target the accepted version-1 layout schema on the existing interface-preferences endpoint",
19
+ );
20
+ assert.match(
21
+ app,
22
+ /const UI_LAYOUT_FIELDS = \["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"\];/,
23
+ "every approved arrangement surface should be a durable layout field",
24
+ );
25
+ for (const [constant, value] of [
26
+ ["UI_LAYOUT_ID_MAX_LENGTH", "256"],
27
+ ["UI_LAYOUT_TITLE_MAX_LENGTH", "160"],
28
+ ["UI_LAYOUT_LIST_MAX_ITEMS", "128"],
29
+ ["UI_LAYOUT_GROUP_MAX_COUNT", "32"],
30
+ ["UI_LAYOUT_GRID_MAX_COLUMNS", "24"],
31
+ ["UI_LAYOUT_GRID_MAX_SLOTS", "4096"],
32
+ ]) {
33
+ assert.match(app, new RegExp(`const ${constant} = ${value};`), `${constant} should mirror the accepted server-side bound`);
34
+ }
35
+ assert.doesNotMatch(
36
+ app,
37
+ /UI_LAYOUT_FIELDS = \[[^\]]*(selectedModel|activeTab|queue|attachment|prompt)/i,
38
+ "semantic file, queue, attachment, model, and prompt state must stay out of the durable layout schema",
39
+ );
40
+
41
+ // --- Local-first hydration and migration -----------------------------------
42
+
43
+ assert.match(
44
+ app,
45
+ /async function restoreSidePanelWidthPreference\(\)[\s\S]*readStoredSidePanelWidth\(\)[\s\S]*const layoutGenerations = new Map\(UI_LAYOUT_FIELDS\.map\(\(field\) => \[field, durableUiLayoutGeneration\(field\)\]\)\);[\s\S]*const readEpoch = \+\+durableLayoutReadEpoch;[\s\S]*await api\("\/api\/interface-preferences", \{ scoped: false \}\)[\s\S]*applyDurableUiLayoutSnapshot\(response\.data, \{ generations: layoutGenerations, readEpoch \}\)/,
46
+ "the local cache should apply first and a single non-blocking unscoped GET should hydrate both the width preference and the durable layout",
47
+ );
48
+ assert.equal(
49
+ (app.match(/api\("\/api\/interface-preferences", \{ scoped: false \}\)/g) || []).length
50
+ + (app.match(/api\(UI_LAYOUT_ENDPOINT, \{ scoped: false \}\)/g) || []).length,
51
+ 2,
52
+ "startup and reconciliation should share exactly one GET call site each instead of polling the settings endpoint",
53
+ );
54
+ assert.match(
55
+ app,
56
+ /function applyDurableUiLayoutSnapshot\(data, \{ generations = null, readEpoch = 0 \} = \{\}\)[\s\S]*readEpoch < durableLayoutAppliedReadEpoch[\s\S]*durableLayoutRevision = data\.layoutRevision/,
57
+ "the snapshot handler should reject out-of-order reads before retaining the opaque server layout revision",
58
+ );
59
+ assert.match(
60
+ app,
61
+ /function applyDurableUiLayoutSnapshot[\s\S]*const generationChanged = durableUiLayoutGeneration\(field\) !== requestedGeneration;[\s\S]*const dirtySubfields = dirtyEntry\?\.subfields/,
62
+ "a stale GET response should identify newer local generations and named dirty subfields",
63
+ );
64
+ assert.match(
65
+ app,
66
+ /function applyDurableUiLayoutSnapshot[\s\S]*!isDirty && !generationChanged && !durableUiLayoutInteractionActive\(field\)[\s\S]*applicable\[subfield\] = remote[\s\S]*applyDurableUiLayoutField\(field, applicable\)/,
67
+ "non-dirty sibling subfields should still adopt authoritative server values",
68
+ );
69
+ assert.match(
70
+ app,
71
+ /function applyDurableUiLayoutSnapshot[\s\S]*!isDirty && !durableUiLayoutValuePresent\(remote\) && durableUiLayoutValuePresent\(local\)[\s\S]*markDurableUiLayoutDirty\(field, subfield\)/,
72
+ "missing server subfields should migrate only their valid local values",
73
+ );
74
+ assert.match(
75
+ app,
76
+ /function refreshDurableUiLayoutFromServer\(\)[\s\S]*const readEpoch = \+\+durableLayoutReadEpoch[\s\S]*applyDurableUiLayoutSnapshot\(response\.data, \{ generations, readEpoch \}\)/,
77
+ "overlapping reconciliation reads should carry monotonic epochs",
78
+ );
79
+
80
+ // --- One coalescing writer, conflicts, and offline retention ---------------
81
+
82
+ assert.match(
83
+ app,
84
+ /function scheduleDurableUiLayoutSave\(delay = UI_LAYOUT_SAVE_DEBOUNCE_MS\)[\s\S]*clearTimeout\(durableLayoutSaveTimer\)[\s\S]*flushDurableUiLayoutSave\(\)/,
85
+ "saves should be coalesced through one debounced timer so drag-over movement cannot create a request storm",
86
+ );
87
+ assert.match(
88
+ app,
89
+ /function markDurableUiLayoutDirty\(field, subfield = null\)[\s\S]*durableUiLayoutGeneration\(field\) \+ 1[\s\S]*writeDurableUiLayoutPendingMutation\(field, key, value\?\.\[key\] \?\? null\)[\s\S]*subfieldMutationIds\.set\(key, nextMutationId\)[\s\S]*subfieldGenerations\.set\(key, generation\)/,
90
+ "each mutation should merge its named subfield into a reload-safe pending journal",
91
+ );
92
+ assert.match(
93
+ app,
94
+ /const UI_LAYOUT_PENDING_STORAGE_PREFIX = "pi-webui-ui-layout-pending-v3:";[\s\S]*function durableUiLayoutPendingMutationRecords\(\)[\s\S]*key\?\.startsWith\(UI_LAYOUT_PENDING_STORAGE_PREFIX\)[\s\S]*value\.version !== 3[\s\S]*function restoreDurableUiLayoutPendingJournal\(\)[\s\S]*candidate\.value[\s\S]*subfieldMutationIds[\s\S]*scheduleDurableUiLayoutSave\(\)/,
95
+ "per-writer pending layout values should survive reload without one tab replacing another tab's journal",
96
+ );
97
+ assert.match(
98
+ app,
99
+ /restoreDurableUiLayoutPendingJournal\(\);\s*\nrestoreSidePanelWidthPreference\(\);/,
100
+ "the pending journal should restore before the startup server read",
101
+ );
102
+ assert.match(
103
+ app,
104
+ /async function flushDurableUiLayoutSave\(\)[\s\S]*if \(durableLayoutSaveInFlight \|\| !durableLayoutDirtyFields\.size\) return;/,
105
+ "only one PUT may be in flight at a time",
106
+ );
107
+ assert.match(
108
+ app,
109
+ /async function flushDurableUiLayoutSave[\s\S]*durableLayoutDirtyFields\.keys\(\)[\s\S]*durableUiLayoutInteractionActive\(field\)[\s\S]*scheduleDurableUiLayoutSave\(\);\s*\n\s*return;/,
110
+ "an active interaction should defer only writes for its affected layout surface",
111
+ );
112
+ assert.match(
113
+ app,
114
+ /function durableUiLayoutInteractionActive\(field = null\)[\s\S]*sidePanelSectionPointerDrag\?\.active[\s\S]*composerActionPointerDrag\?\.active[\s\S]*footerScopedModelPointerDrag\?\.active[\s\S]*terminalTabDragId[\s\S]*fileViewerResizeState/,
115
+ "every durable reorder and resize interaction should be tracked per surface",
116
+ );
117
+ assert.match(
118
+ app,
119
+ /async function flushDurableUiLayoutSave[\s\S]*body: \{ layout: patch, expectedLayoutRevision: durableLayoutRevision \}/,
120
+ "layout writes should submit the latest known opaque revision",
121
+ );
122
+ assert.match(
123
+ app,
124
+ /async function flushDurableUiLayoutSave[\s\S]*current\.subfieldGenerations\?\.get\(subfield\) !== entry\.subfieldGenerations\?\.get\(subfield\)[\s\S]*current\.subfieldMutationIds\?\.get\(subfield\) !== entry\.subfieldMutationIds\?\.get\(subfield\)[\s\S]*clearAcknowledgedDurableUiLayoutPendingMutations\(snapshot\)/,
125
+ "acknowledgement should clear matching nested generations independently across every writer journal",
126
+ );
127
+ assert.match(
128
+ app,
129
+ /const UI_LAYOUT_MAX_CONFLICT_RETRIES = 1;[\s\S]*if \(status === 409\)[\s\S]*durableLayoutConflictAttempts \+= 1;[\s\S]*await refreshDurableUiLayoutFromServer\(\);[\s\S]*durableLayoutConflictAttempts <= UI_LAYOUT_MAX_CONFLICT_RETRIES[\s\S]*else warnDurableUiLayoutOnce/,
130
+ "a 409 should refresh once, retry within a bounded budget, and then report exactly one warning",
131
+ );
132
+ assert.match(
133
+ app,
134
+ /function warnDurableUiLayoutOnce\(message\)[\s\S]*if \(durableLayoutWarned\) return;[\s\S]*durableLayoutWarned = true;[\s\S]*addEvent\(message, "warn"\)/,
135
+ "conflict and rejection reporting should stay bounded to one warning",
136
+ );
137
+ assert.match(
138
+ app,
139
+ /async function flushDurableUiLayoutSave[\s\S]*navigator\.onLine === false\) return;/,
140
+ "offline browsers should keep the dirty layout instead of issuing doomed writes",
141
+ );
142
+ assert.match(
143
+ app,
144
+ /function reconcileDurableUiLayout\(\)[\s\S]*refreshDurableUiLayoutFromServer\(\)\.then\(\(ready\) => \{[\s\S]*durableLayoutDirtyFields\.size\) scheduleDurableUiLayoutSave\(0\)/,
145
+ "foreground reconciliation should retry retained dirty state",
146
+ );
147
+ assert.match(
148
+ app,
149
+ /window\.addEventListener\("online", \(\) => reconcileDurableUiLayout\(\)\);\s*\nwindow\.addEventListener\("pageshow", \(\) => reconcileDurableUiLayout\(\)\);\s*\ndocument\.addEventListener\("visibilitychange", \(\) => \{\s*\n\s*if \(document\.visibilityState === "visible"\) reconcileDurableUiLayout\(\);/,
150
+ "durable layout reconciliation should use dedicated online, pageshow, and foreground listeners",
151
+ );
152
+ // The pre-existing session/transcript reconciliation contracts must stay intact.
153
+ assert.match(
154
+ app,
155
+ /window\.addEventListener\("pageshow", \(\) => scheduleForegroundReconcile\("page show", 0\)\);/,
156
+ "existing foreground snapshot reconciliation must remain unchanged",
157
+ );
158
+ assert.match(
159
+ app,
160
+ /window\.addEventListener\("online", \(\) => scheduleForegroundReconcile\("network online", 0\)\);/,
161
+ "existing online snapshot reconciliation must remain unchanged",
162
+ );
163
+
164
+ // --- Every approved arrangement surface is durable -------------------------
165
+
166
+ for (const [persistFunction, field, subfield] of [
167
+ ["persistSidePanelSectionOrder", "sidePanel", "sectionOrder"],
168
+ ["persistSidePanelSectionState", "sidePanel", "collapsedSectionIds"],
169
+ ["persistSidePanelSectionVisibility", "sidePanel", "hiddenSectionIds"],
170
+ ["persistComposerActionOrder", "composerActions", null],
171
+ ["persistComposerActionSlotLayout", "composerActions", null],
172
+ ["persistTerminalTabsLayout", "terminalTabs", "layout"],
173
+ ["persistTerminalCustomGroups", "terminalTabs", "customGroups"],
174
+ ["persistFileViewerWidth", "fileViewerWidth", null],
175
+ ["writeFooterScopedModelOrder", "footerScopedModelOrder", null],
176
+ ]) {
177
+ const marker = subfield
178
+ ? `markDurableUiLayoutDirty\\("${field}", "${subfield}"\\)`
179
+ : `markDurableUiLayoutDirty\\("${field}"\\)`;
180
+ assert.match(
181
+ app,
182
+ new RegExp(`function ${persistFunction}\\([^)]*\\) \\{[\\s\\S]*?${marker};\\s*\\n\\}`),
183
+ `${persistFunction} should mark only its owned durable layout value after writing the local cache`,
184
+ );
185
+ }
186
+ assert.match(
187
+ app,
188
+ /localStorage\.setItem\(SIDE_PANEL_STORAGE_KEY, collapsed \? "1" : "0"\);[\s\S]{0,200}markDurableUiLayoutDirty\("sidePanel", "collapsed"\)/,
189
+ "Control Deck collapse state should be durable without dirtying sibling settings",
190
+ );
191
+ assert.match(
192
+ app,
193
+ /function restoreSidePanelState\(\)[\s\S]*setSidePanelCollapsed\(stored \?\? false, \{ persist: false \}\)/,
194
+ "passive Control Deck restoration must not echo stale cache back to the server",
195
+ );
196
+
197
+ // --- Composer order and grid stay one atomic logical update ----------------
198
+
199
+ assert.match(
200
+ app,
201
+ /function collectDurableComposerActionsLayout\(\)[\s\S]*return \{ order: durableLayoutStoredIdList\(COMPOSER_ACTION_ORDER_STORAGE_KEY\), grid \};/,
202
+ "composer order and sparse grid must be submitted together as one field",
203
+ );
204
+ assert.match(
205
+ app,
206
+ /function collectDurableComposerActionsLayout\(\)[\s\S]*grid = \{ version: 2, columns: stored\.columns, positions \};/,
207
+ "the persisted grid should use the accepted version-2 sparse envelope",
208
+ );
209
+ assert.match(
210
+ app,
211
+ /function applyDurableComposerActionsLayout\(value\)[\s\S]*writeDurableLayoutCache\(COMPOSER_ACTION_LAYOUT_STORAGE_KEY, JSON\.stringify\(value\.grid\)\);\s*\n\s*restoreComposerActionSlotLayout\(\)/,
212
+ "server grid slots should be cached locally and restored through the existing responsive restore pass",
213
+ );
214
+ assert.match(
215
+ app,
216
+ /function restoreComposerActionSlotLayout\(\)[\s\S]*stored\.columns === columns[\s\S]*remapComposerActionSlot[\s\S]*nearestAvailableComposerActionSlot/,
217
+ "stored slots should project into mismatched column counts without rewriting the saved source geometry",
218
+ );
219
+
220
+ // --- Cross-tab cache adoption without duplicate server writes --------------
221
+
222
+ assert.match(
223
+ app,
224
+ /window\.addEventListener\("storage"[\s\S]*event\.key === TERMINAL_CUSTOM_GROUPS_STORAGE_KEY[\s\S]*restoreTerminalCustomGroups\(\);[\s\S]*syncTerminalCustomGroupsWithTabs\(tabs, \{ persist: false \}\)/,
225
+ "another tab's terminal groups should be adopted through the existing tab-filtering restore without re-persisting",
226
+ );
227
+ assert.match(
228
+ app,
229
+ /window\.addEventListener\("storage"[\s\S]*event\.key === FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY[\s\S]*footerScopedModels = orderedFooterScopedModels\(\)/,
230
+ "another tab's footer order should be adopted locally",
231
+ );
232
+ assert.match(
233
+ app,
234
+ /window\.addEventListener\("storage"[\s\S]*event\.key === FILE_VIEWER_WIDTH_STORAGE_KEY\) restoreFileViewerWidthPreference\(\)/,
235
+ "another tab's file-viewer width should be adopted locally",
236
+ );
237
+ for (const applyFunction of [
238
+ "applyDurableSidePanelLayout",
239
+ "applyDurableComposerActionsLayout",
240
+ "applyDurableFooterScopedModelOrder",
241
+ "applyDurableTerminalTabsLayout",
242
+ "applyDurableFileViewerWidth",
243
+ ]) {
244
+ const body = new RegExp(`function ${applyFunction}\\(value\\) \\{[\\s\\S]*?\\n\\}`).exec(app)?.[0] || "";
245
+ assert.ok(body, `${applyFunction} should exist`);
246
+ assert.doesNotMatch(body, /markDurableUiLayoutDirty/, `${applyFunction} must not echo server state back as a new write`);
247
+ }
248
+
249
+ // --- Terminal groups keep the existing valid-tab filtering ------------------
250
+
251
+ assert.match(
252
+ app,
253
+ /function applyDurableTerminalTabsLayout\(value\)[\s\S]*setTerminalTabsLayout\(value\.layout, \{ persist: false \}\)/,
254
+ "an applied terminal layout should not re-persist",
255
+ );
256
+ assert.match(
257
+ app,
258
+ /function collectDurableTerminalTabsLayout\(\)[\s\S]*if \(!title \|\| tabIds\.length < 2\) continue;/,
259
+ "durable groups should honor the existing minimum-membership rule and bounded titles",
260
+ );
261
+
262
+ // --- Coherent browser asset revisions --------------------------------------
263
+
264
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v71"/, "changed browser assets should advance the PWA cache identity");
265
+ assert.match(html, /data-app-src="\/app\.js\?v=112"/, "the boot loader should request the updated app module revision");
266
+
267
+ console.log("persistent-ui-layout-static.test.mjs passed");