@firstpick/pi-package-webui 0.7.6 → 0.7.8

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 (48) hide show
  1. package/README.md +60 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +612 -0
  3. package/bin/pi-webui.mjs +1051 -95
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +317 -0
  6. package/lib/rpc-supervisor-protocol.mjs +245 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +4 -4
  10. package/public/app.js +1986 -170
  11. package/public/index.html +388 -25
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +8 -1
  15. package/public/styles.css +578 -52
  16. package/public/subagent-gate-visibility.mjs +36 -0
  17. package/public/workflow-status-stack.mjs +69 -0
  18. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  19. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  20. package/tests/completion-signal-contract.test.mjs +156 -0
  21. package/tests/cwd-footer-reliability-static.test.mjs +107 -0
  22. package/tests/durable-rpc-supervisor-harness.test.mjs +275 -0
  23. package/tests/fast-mode-client-static.test.mjs +2 -2
  24. package/tests/fixtures/fake-pi.mjs +90 -6
  25. package/tests/footer-context-contrast-static.test.mjs +10 -0
  26. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  27. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  28. package/tests/http-endpoints-harness.test.mjs +458 -33
  29. package/tests/issue-bot-client.test.mjs +135 -0
  30. package/tests/issue-wizard-state.test.mjs +126 -0
  31. package/tests/mobile-static.test.mjs +79 -16
  32. package/tests/native-parity-harness.test.mjs +2 -1
  33. package/tests/native-parity.test.mjs +13 -2
  34. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  35. package/tests/open-issue-wizard-static.test.mjs +75 -0
  36. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  37. package/tests/prompt-routing-tab-status.test.mjs +108 -0
  38. package/tests/rpc-supervisor-host.test.mjs +408 -0
  39. package/tests/rpc-supervisor-protocol.test.mjs +93 -0
  40. package/tests/rpc-supervisor-state.test.mjs +62 -0
  41. package/tests/run-all.mjs +4 -1
  42. package/tests/streaming-ui-coupling.test.mjs +18 -2
  43. package/tests/subagent-gate-visibility.test.mjs +66 -0
  44. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  45. package/tests/subagents-helper.test.mjs +136 -0
  46. package/tests/terminal-tab-workspace-static.test.mjs +99 -0
  47. package/tests/workflow-status-stack.test.mjs +87 -0
  48. package/webui-rpc-helper.mjs +160 -2
package/public/index.html CHANGED
@@ -12,9 +12,76 @@
12
12
  <link rel="manifest" href="/manifest.webmanifest" />
13
13
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
14
14
  <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
15
- <link rel="stylesheet" href="/styles.css?v=83" />
15
+ <link rel="stylesheet" href="/styles.css?v=86" />
16
+ <script>
17
+ // Public-only issue-bot runtime configuration. Keep disabled unless the gateway,
18
+ // Turnstile site key, exact CORS origin, and private-report destination are approved.
19
+ window.__PI_WEBUI_ISSUE_BOT_CONFIG__ ??= Object.freeze({
20
+ enabled: false,
21
+ gatewayBaseUrl: "",
22
+ turnstileSiteKey: "",
23
+ privateSecurityReportUrl: "",
24
+ });
25
+ </script>
26
+ <style id="webuiBootFailureStyles">
27
+ .webui-boot-failure[hidden] { display: none !important; }
28
+ .webui-boot-failure {
29
+ position: fixed;
30
+ inset: 0;
31
+ z-index: 1000;
32
+ display: grid;
33
+ place-items: center;
34
+ overflow: auto;
35
+ padding: 1rem;
36
+ color: #cdd6f4;
37
+ background: rgba(17, 17, 27, 0.96);
38
+ font: 16px/1.5 Inter, ui-sans-serif, system-ui, sans-serif;
39
+ }
40
+ .webui-boot-failure-card {
41
+ width: min(52rem, 100%);
42
+ padding: clamp(1.2rem, 4vw, 2rem);
43
+ border: 1px solid rgba(249, 226, 175, 0.5);
44
+ border-radius: 1rem;
45
+ background: #1e1e2e;
46
+ box-shadow: 0 1.2rem 4rem rgba(0, 0, 0, 0.6);
47
+ }
48
+ .webui-boot-failure-kicker { color: #f9e2af; font-size: 0.78rem; font-weight: 800; letter-spacing: 0.12em; text-transform: uppercase; }
49
+ .webui-boot-failure h1 { margin: 0.45rem 0; font-size: clamp(1.4rem, 4vw, 2rem); }
50
+ .webui-boot-failure p { margin: 0 0 1rem; }
51
+ .webui-boot-failure label { display: block; margin-bottom: 0.4rem; font-weight: 700; }
52
+ .webui-boot-failure textarea {
53
+ width: 100%;
54
+ min-height: min(42vh, 22rem);
55
+ padding: 0.8rem;
56
+ resize: vertical;
57
+ color: #cdd6f4;
58
+ background: #11111b;
59
+ border: 1px solid #45475a;
60
+ border-radius: 0.7rem;
61
+ font: 0.82rem/1.45 ui-monospace, SFMono-Regular, Consolas, monospace;
62
+ }
63
+ .webui-boot-failure-actions { display: flex; flex-wrap: wrap; gap: 0.7rem; margin-top: 0.8rem; }
64
+ .webui-boot-failure button { min-height: 44px; padding: 0.55rem 0.9rem; color: #cdd6f4; background: #313244; border: 1px solid #6c7086; border-radius: 0.7rem; cursor: pointer; font: inherit; }
65
+ .webui-boot-failure button:first-child { color: #11111b; background: #a6e3a1; border-color: #a6e3a1; font-weight: 800; }
66
+ .webui-boot-failure-status { min-height: 1.5em; margin-top: 0.65rem !important; color: #a6e3a1; }
67
+ </style>
16
68
  </head>
17
69
  <body>
70
+ <section id="webuiBootFailurePanel" class="webui-boot-failure" aria-live="assertive" hidden>
71
+ <div class="webui-boot-failure-card" role="alert">
72
+ <span class="webui-boot-failure-kicker">Frontend startup failed</span>
73
+ <h1>Pi Web UI could not load correctly</h1>
74
+ <p id="webuiBootFailureReason">The browser could not initialize the application. A bounded diagnostic report is being collected.</p>
75
+ <label for="webuiBootFailureReport">Copyable troubleshooting report</label>
76
+ <textarea id="webuiBootFailureReport" rows="14" readonly spellcheck="false">Collecting diagnostics…</textarea>
77
+ <div class="webui-boot-failure-actions">
78
+ <button id="copyWebuiBootFailureReportButton" type="button">Copy troubleshooting report</button>
79
+ <button id="reloadWebuiAfterBootFailureButton" type="button">Reload page</button>
80
+ </div>
81
+ <p id="webuiBootFailureCopyStatus" class="webui-boot-failure-status" role="status" aria-live="polite"></p>
82
+ </div>
83
+ </section>
84
+
18
85
  <button id="sidePanelExpandButton" class="side-panel-expand-button" type="button" aria-controls="sidePanel" aria-expanded="false" aria-label="Expand side panel" title="Expand side panel">
19
86
  <span class="side-panel-button-icon" aria-hidden="true">
20
87
  <span></span><span></span><span></span>
@@ -136,6 +203,27 @@
136
203
  <form id="composer" class="composer">
137
204
  <div id="commandSuggest" class="command-suggest" role="listbox" aria-label="Command and path suggestions" hidden></div>
138
205
  <div class="composer-input-row">
206
+ <div id="workflowModeControls" class="composer-workflow-mode-dock" role="group" aria-label="Workflow Mode controls" hidden>
207
+ <button
208
+ id="workflowOverlayOpenButton"
209
+ class="composer-icon-button composer-workflow-overlay-open-button"
210
+ type="button"
211
+ aria-label="Open workflow overlay"
212
+ aria-controls="widgetArea"
213
+ aria-expanded="false"
214
+ data-tooltip="Open the minimized workflow overlay."
215
+ hidden
216
+ ><svg class="composer-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M5 12h14M13 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
217
+ <button
218
+ id="workflowModeButton"
219
+ class="composer-icon-button composer-workflow-mode-button"
220
+ type="button"
221
+ aria-label="Enable Workflow Mode"
222
+ aria-pressed="false"
223
+ data-tooltip="Workflow Mode: generate and run reusable JavaScript orchestration for substantive prompts."
224
+ hidden
225
+ ><svg class="composer-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="3" width="8" height="8" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M7 11v4a2 2 0 0 0 2 2h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><rect x="13" y="13" width="8" height="8" rx="2" fill="none" stroke="currentColor" stroke-width="2"/></svg></button>
226
+ </div>
139
227
  <div class="composer-context-tags">
140
228
  <button
141
229
  id="busyPromptBehaviorTag"
@@ -178,27 +266,6 @@
178
266
  <div id="composerActionsPanel" class="composer-actions-panel" aria-label="Composer actions">
179
267
  <button id="newSessionButton" class="composer-new-button" type="button">New</button>
180
268
  <button id="compactButton" class="composer-compact-button" type="button" title="Compact the current Pi session context">Compact</button>
181
- <div id="workflowModeControls" class="composer-publish-menu composer-workflow-mode-controls" hidden>
182
- <button
183
- id="workflowOverlayOpenButton"
184
- class="composer-icon-button composer-workflow-overlay-open-button"
185
- type="button"
186
- aria-label="Open workflow overlay"
187
- aria-controls="widgetArea"
188
- aria-expanded="false"
189
- data-tooltip="Open the minimized workflow overlay."
190
- hidden
191
- ><svg class="composer-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M5 12h14M13 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
192
- <button
193
- id="workflowModeButton"
194
- class="composer-icon-button composer-workflow-mode-button"
195
- type="button"
196
- aria-label="Enable Workflow Mode"
197
- aria-pressed="false"
198
- data-tooltip="Workflow Mode: generate and run reusable JavaScript orchestration for substantive prompts."
199
- hidden
200
- ><svg class="composer-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="3" width="8" height="8" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M7 11v4a2 2 0 0 0 2 2h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><rect x="13" y="13" width="8" height="8" rx="2" fill="none" stroke="currentColor" stroke-width="2"/></svg></button>
201
- </div>
202
269
  <button
203
270
  id="gitWorkflowButton"
204
271
  class="composer-icon-button composer-git-button"
@@ -260,7 +327,7 @@
260
327
  aria-haspopup="menu"
261
328
  aria-expanded="false"
262
329
  aria-controls="optionsMenu"
263
- data-tooltip="Options: command palette, Safety Guard Setup, Guided Git Setup, Git-footer Visibility, natural conversation, resume, reload, remote, name, clone, settings, export, fork, or tree."
330
+ data-tooltip="Options: command palette, Workflow Permission Setup, Safety Guard Setup, Guided Git Setup, Git-footer Visibility, natural conversation, resume, reload, remote, name, clone, settings, export, fork, or tree."
264
331
  ><svg class="composer-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M4 12h16M4 17h16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="8" cy="7" r="1.6" fill="currentColor"/><circle cx="16" cy="12" r="1.6" fill="currentColor"/><circle cx="11" cy="17" r="1.6" fill="currentColor"/></svg></button>
265
332
  <div id="optionsMenu" class="composer-publish-menu-panel composer-options-menu-panel composer-auto-height-menu-panel" role="menu" aria-label="Common Pi options">
266
333
  <button id="optionsCommandPaletteButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem">
@@ -287,6 +354,9 @@
287
354
  <button id="optionsSettingsButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem" data-command="/settings">
288
355
  <span>Settings</span>
289
356
  </button>
357
+ <button id="optionsWorkflowSetupButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem" data-command="/workflow-setup" hidden>
358
+ <span>Workflow Permission Setup</span>
359
+ </button>
290
360
  <button id="optionsSafetyGuardSetupButton" class="composer-publish-menu-item composer-options-menu-item" type="button" role="menuitem" data-command="/safety-guard-setup" hidden>
291
361
  <span>Safety Guard Setup</span>
292
362
  </button>
@@ -400,7 +470,7 @@
400
470
  <button id="fileViewerCloseButton" type="button" aria-label="Close file viewer">Close</button>
401
471
  </div>
402
472
  </header>
403
- <p id="fileViewerHelp" class="file-viewer-help muted">Markdown files can be viewed as Preview or Source. Select text in the file, add a one-line comment, then Send to include the selection and surrounding context in this Pi session.</p>
473
+ <p id="fileViewerHelp" class="file-viewer-help muted">Files opened from Git start in Changes mode. Markdown files can also be viewed as Preview or Source. Select text in Source or Preview, add a one-line comment, then Send to include the selection and surrounding context in this Pi session.</p>
404
474
  <div id="fileSelectionBar" class="file-selection-bar" hidden>
405
475
  <span id="fileSelectionSummary" class="file-selection-summary">No selection</span>
406
476
  <input id="fileSelectionCommentInput" class="file-selection-comment" type="text" placeholder="Comment for Pi about this selection…" autocomplete="off" />
@@ -408,6 +478,7 @@
408
478
  </div>
409
479
  <div class="file-viewer-mode-row">
410
480
  <div class="file-viewer-mode-toggle" role="group" aria-label="File view mode">
481
+ <button id="fileViewerChangesModeButton" type="button" aria-pressed="false" hidden>Changes</button>
411
482
  <button id="fileViewerSourceModeButton" type="button" aria-pressed="true">Source</button>
412
483
  <button id="fileViewerPreviewModeButton" type="button" aria-pressed="false">Preview</button>
413
484
  </div>
@@ -415,6 +486,7 @@
415
486
  <div class="file-viewer-content">
416
487
  <textarea id="fileViewerEditor" class="file-viewer-editor" wrap="soft" spellcheck="false" aria-label="File contents"></textarea>
417
488
  <div id="fileViewerPreview" class="file-viewer-preview markdown-body" tabindex="0" hidden></div>
489
+ <div id="fileViewerChanges" class="file-viewer-changes" tabindex="0" aria-label="Git changes for this file" hidden></div>
418
490
  </div>
419
491
  <p id="fileViewerStatus" class="file-viewer-status muted" role="status" aria-live="polite"></p>
420
492
  </section>
@@ -840,6 +912,9 @@
840
912
  </div>
841
913
  </section>
842
914
  </div>
915
+ <footer class="side-panel-footer">
916
+ <button id="openIssueButton" class="open-issue-button" type="button" aria-haspopup="dialog" aria-controls="issueWizardDialog">Open Issue</button>
917
+ </footer>
843
918
  </aside>
844
919
  </main>
845
920
 
@@ -860,6 +935,47 @@
860
935
  <span class="undo-toast-progress" aria-hidden="true"></span>
861
936
  </aside>
862
937
 
938
+ <dialog id="issueWizardDialog" class="extension-dialog issue-wizard-dialog" aria-labelledby="issueWizardTitle" aria-describedby="issueWizardDescription">
939
+ <form method="dialog">
940
+ <header class="issue-wizard-header">
941
+ <div>
942
+ <span class="issue-wizard-kicker">GitHub issue</span>
943
+ <h2 id="issueWizardTitle">Open an issue</h2>
944
+ <p id="issueWizardDescription" class="muted">Use this five-step wizard to prepare a complete issue you can copy to GitHub.</p>
945
+ </div>
946
+ <button id="issueWizardCloseButton" type="button" aria-label="Close Open Issue wizard">Close</button>
947
+ </header>
948
+ <div class="issue-wizard-progress-row">
949
+ <span id="issueWizardProgress" class="issue-wizard-progress">Step 1 of 5</span>
950
+ <span>1 Category · 2 Component · 3 Template · 4 Details · 5 Review</span>
951
+ </div>
952
+ <div id="issueWizardPages" class="issue-wizard-pages">
953
+ <section class="issue-wizard-page" data-issue-wizard-page="1" aria-label="Step 1: choose issue category" hidden></section>
954
+ <section class="issue-wizard-page" data-issue-wizard-page="2" aria-label="Step 2: choose affected component" hidden></section>
955
+ <section class="issue-wizard-page" data-issue-wizard-page="3" aria-label="Step 3: choose issue template" hidden></section>
956
+ <section class="issue-wizard-page" data-issue-wizard-page="4" aria-label="Step 4: add issue details" hidden></section>
957
+ <section class="issue-wizard-page" data-issue-wizard-page="5" aria-label="Step 5: review GitHub issue" hidden></section>
958
+ </div>
959
+ <p id="issueWizardStatus" class="issue-wizard-status muted" role="status" aria-live="polite" aria-atomic="true">Start by choosing an issue category.</p>
960
+ <section id="issueWizardSubmissionStatus" class="issue-wizard-submission-status" role="status" aria-live="polite" aria-atomic="true" hidden>
961
+ <p id="issueWizardSubmissionMessage" class="issue-wizard-submission-message"></p>
962
+ <div class="issue-wizard-submission-actions">
963
+ <a id="issueWizardSubmissionLink" target="_blank" rel="noopener noreferrer" hidden></a>
964
+ <button id="issueWizardRefreshButton" type="button" hidden>Refresh status</button>
965
+ </div>
966
+ <p id="issueWizardSecurityGuidance" class="issue-wizard-security-guidance" hidden>Do not include security details or credentials in a public issue. <a id="issueWizardSecurityLink" target="_blank" rel="noopener noreferrer" hidden>Use private vulnerability reporting</a>.</p>
967
+ </section>
968
+ <div id="issueWizardTurnstile" class="issue-wizard-turnstile" aria-label="Bot protection challenge"></div>
969
+ <menu class="issue-wizard-actions">
970
+ <button id="issueWizardBackButton" type="button">Back</button>
971
+ <button id="issueWizardContinueButton" class="primary" type="button" disabled>Continue</button>
972
+ <button id="issueWizardCopyButton" type="button" hidden>Copy complete issue</button>
973
+ <button id="issueWizardBotButton" type="button" disabled hidden aria-describedby="issueWizardBotHint issueWizardSubmissionStatus">Send</button>
974
+ </menu>
975
+ <p id="issueWizardBotHint" class="issue-wizard-bot-hint muted" hidden>Automated submission is not enabled. Copy the issue and create it manually instead.</p>
976
+ </form>
977
+ </dialog>
978
+
863
979
  <dialog id="piReleaseNotesDialog" class="extension-dialog pi-release-notes-dialog" aria-labelledby="piReleaseNotesTitle">
864
980
  <form method="dialog">
865
981
  <div class="pi-release-notes-header">
@@ -1166,6 +1282,253 @@
1166
1282
  </form>
1167
1283
  </dialog>
1168
1284
 
1169
- <script type="module" src="/app.js?v=91"></script>
1285
+ <script id="webuiBootLoader" data-app-src="/app.js?v=92">
1286
+ (() => {
1287
+ "use strict";
1288
+
1289
+ const loader = document.currentScript;
1290
+ const panel = document.querySelector("#webuiBootFailurePanel");
1291
+ const reasonElement = document.querySelector("#webuiBootFailureReason");
1292
+ const reportElement = document.querySelector("#webuiBootFailureReport");
1293
+ const copyButton = document.querySelector("#copyWebuiBootFailureReportButton");
1294
+ const reloadButton = document.querySelector("#reloadWebuiAfterBootFailureButton");
1295
+ const copyStatus = document.querySelector("#webuiBootFailureCopyStatus");
1296
+ const appSource = loader?.dataset?.appSrc || "/app.js";
1297
+ const bootStartedAt = new Date();
1298
+ let bootSettled = false;
1299
+ let bootFailed = false;
1300
+ let watchdog = null;
1301
+
1302
+ function sanitizedUrl(value) {
1303
+ try {
1304
+ const url = new URL(String(value || ""), window.location.href);
1305
+ return `${url.origin}${url.pathname}`;
1306
+ } catch {
1307
+ return String(value || "").split(/[?#]/, 1)[0];
1308
+ }
1309
+ }
1310
+
1311
+ function boundedSafeText(value, limit = 600) {
1312
+ const sanitized = String(value || "Unknown startup failure")
1313
+ .replace(/https?:\/\/[^\s)\]}]+/gi, (url) => sanitizedUrl(url))
1314
+ .replace(/\b(Bearer\s+)[^\s]+/gi, "$1[redacted]")
1315
+ .replace(/\b(token|password|secret|api[-_]?key)\s*[=:]\s*[^\s,;]+/gi, "$1=[redacted]");
1316
+ return sanitized.length > limit ? `${sanitized.slice(0, limit)}…` : sanitized;
1317
+ }
1318
+
1319
+ function errorText(error) {
1320
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1321
+ return boundedSafeText(error);
1322
+ }
1323
+
1324
+ async function responseSummary(url, label, { parseHealth = false, readSource = false } = {}) {
1325
+ const safeUrl = sanitizedUrl(url);
1326
+ try {
1327
+ const response = await fetch(url, { cache: "no-store", credentials: "same-origin" });
1328
+ const type = String(response.headers?.get?.("content-type") || "unknown").split(";", 1)[0];
1329
+ let suffix = "";
1330
+ let source = "";
1331
+ if (parseHealth && response.ok) {
1332
+ const data = await response.clone().json().catch(() => null);
1333
+ const fields = [data?.ok === true ? "ok=true" : "", data?.webuiVersion ? `webuiVersion=${boundedSafeText(data.webuiVersion, 80)}` : ""].filter(Boolean);
1334
+ if (fields.length) suffix = ` (${fields.join(", ")})`;
1335
+ }
1336
+ if (readSource && response.ok) source = await response.text();
1337
+ else response.body?.cancel?.().catch?.(() => {});
1338
+ return { ok: response.ok, status: response.status, type, safeUrl, label, line: `- ${label}: HTTP ${response.status} ${type}${suffix} — ${safeUrl}`, source };
1339
+ } catch (error) {
1340
+ return { ok: false, status: null, type: "unknown", safeUrl, label, line: `- ${label}: request failed (${boundedSafeText(errorText(error), 240)}) — ${safeUrl}`, source: "" };
1341
+ }
1342
+ }
1343
+
1344
+ async function startupAssetReport() {
1345
+ const appUrl = new URL(appSource, window.location.href);
1346
+ const app = await responseSummary(appUrl.href, "entry module", { readSource: true });
1347
+ if (!app.source) return { probes: [app], lines: [app.line], failures: app.ok ? [] : [app] };
1348
+
1349
+ const imported = [];
1350
+ const importPattern = /(?:\bfrom\s+|\bimport\s*(?:\(\s*)?)["'](\.\/[^"']+)["']/g;
1351
+ for (const match of app.source.matchAll(importPattern)) {
1352
+ const assetUrl = new URL(match[1], appUrl);
1353
+ if (assetUrl.origin !== window.location.origin) continue;
1354
+ const key = `${assetUrl.origin}${assetUrl.pathname}`;
1355
+ if (!imported.some((item) => item.key === key)) imported.push({ key, url: assetUrl.href });
1356
+ if (imported.length >= 24) break;
1357
+ }
1358
+
1359
+ const importedProbes = await Promise.all(imported.map((item) => responseSummary(item.url, "imported module")));
1360
+ const probes = [app, ...importedProbes];
1361
+ return { probes, lines: probes.map((probe) => probe.line), failures: probes.filter((probe) => !probe.ok) };
1362
+ }
1363
+
1364
+ function startupAssessment(health, assets, error) {
1365
+ const missingImports = assets.failures.filter((probe) => probe.label === "imported module" && probe.status === 404);
1366
+ const firstFailure = assets.failures[0] || (!health.ok ? health : null);
1367
+ const originalError = boundedSafeText(errorText(error));
1368
+ if (missingImports.length) {
1369
+ const paths = missingImports.map((probe) => new URL(probe.safeUrl).pathname);
1370
+ return {
1371
+ summary: `Missing startup module${paths.length === 1 ? "" : "s"}: ${paths.join(", ")} (HTTP 404).`,
1372
+ likelyCause: health.ok
1373
+ ? "The backend is healthy, but the running server's static asset allowlist is out of sync with app.js."
1374
+ : "The startup module is unavailable and the backend health check also failed; verify the server process first.",
1375
+ failingUrls: missingImports.map((probe) => probe.safeUrl),
1376
+ };
1377
+ }
1378
+ if (firstFailure) {
1379
+ return {
1380
+ summary: `Startup request failed: ${new URL(firstFailure.safeUrl).pathname}${firstFailure.status ? ` (HTTP ${firstFailure.status})` : ""}.`,
1381
+ likelyCause: firstFailure.label === "backend health"
1382
+ ? "The browser shell loaded, but the WebUI backend is unavailable or unreachable."
1383
+ : "A startup asset is unavailable, blocked, or served with an unsuccessful response.",
1384
+ failingUrls: [firstFailure.safeUrl],
1385
+ };
1386
+ }
1387
+ if (/critical stylesheet/i.test(originalError)) {
1388
+ return { summary: "The critical stylesheet failed to load.", likelyCause: "The stylesheet request failed even though the startup-module probes succeeded.", failingUrls: [] };
1389
+ }
1390
+ return {
1391
+ summary: "All probed startup URLs currently respond successfully, but module evaluation still failed.",
1392
+ likelyCause: "The failure may be a stale browser/PWA cache, a transient request failure, or a JavaScript evaluation error rather than a current HTTP 404.",
1393
+ failingUrls: [],
1394
+ };
1395
+ }
1396
+
1397
+ async function troubleshootingReport(reason, error) {
1398
+ const pageUrl = sanitizedUrl(window.location.href);
1399
+ const health = await responseSummary(new URL("/api/health", window.location.href).href, "backend health", { parseHealth: true });
1400
+ const assets = await startupAssetReport();
1401
+ const assessment = startupAssessment(health, assets, error);
1402
+ const failedProbes = [...(!health.ok ? [health] : []), ...assets.failures];
1403
+ const failingChecks = failedProbes.length
1404
+ ? failedProbes.map((probe) => probe.line)
1405
+ : ["- none detected by the HTTP probes"];
1406
+ const failingAssetCommand = assessment.failingUrls[0]
1407
+ ? `3. Recheck the failing asset: curl -i ${assessment.failingUrls[0]}`
1408
+ : "3. Reload once with the browser cache bypassed, then compare the new report.";
1409
+ const text = [
1410
+ "Pi Web UI startup failure",
1411
+ "=========================",
1412
+ `Time: ${new Date().toISOString()}`,
1413
+ `Page: ${pageUrl}`,
1414
+ `Reason: ${boundedSafeText(reason)}`,
1415
+ `Error: ${boundedSafeText(errorText(error))}`,
1416
+ `Document state: ${document.readyState}`,
1417
+ `Browser: ${boundedSafeText(navigator.userAgent, 300)}`,
1418
+ "",
1419
+ "Diagnosis",
1420
+ "---------",
1421
+ `Summary: ${assessment.summary}`,
1422
+ `Likely cause: ${assessment.likelyCause}`,
1423
+ "Browser note: a transitive import failure may be reported as app.js; the individual probes below identify the actual failing file.",
1424
+ "",
1425
+ "Failing checks",
1426
+ "--------------",
1427
+ ...failingChecks,
1428
+ "",
1429
+ "All checks",
1430
+ "----------",
1431
+ health.line,
1432
+ ...assets.lines,
1433
+ "",
1434
+ "Suggested troubleshooting",
1435
+ "-------------------------",
1436
+ "1. In Pi, run: /webui-status detailed",
1437
+ `2. Check the backend: curl -i ${new URL("/api/health", pageUrl).href}`,
1438
+ failingAssetCommand,
1439
+ "4. For an imported-module 404, synchronize the WebUI static allowlist and PWA app shell with app.js imports.",
1440
+ "5. After correcting files, run /webui-start again to restart the server and restore tabs.",
1441
+ "6. Share this complete report with your troubleshooting assistant.",
1442
+ ].join("\n");
1443
+ return { text, summary: assessment.summary };
1444
+ }
1445
+
1446
+ async function showBootFailure(reason, error) {
1447
+ if (bootSettled || bootFailed) return;
1448
+ bootFailed = true;
1449
+ clearTimeout(watchdog);
1450
+ if (reasonElement) reasonElement.textContent = boundedSafeText(reason, 300);
1451
+ if (panel) panel.hidden = false;
1452
+ if (reportElement) reportElement.value = "Collecting diagnostics…";
1453
+ const report = await troubleshootingReport(reason, error).catch((diagnosticError) => ({
1454
+ summary: boundedSafeText(reason, 300),
1455
+ text: [
1456
+ "Pi Web UI startup failure",
1457
+ `Time: ${new Date().toISOString()}`,
1458
+ `Page: ${sanitizedUrl(window.location.href)}`,
1459
+ `Reason: ${boundedSafeText(reason)}`,
1460
+ `Error: ${boundedSafeText(errorText(error))}`,
1461
+ `Diagnostic collection failed: ${boundedSafeText(errorText(diagnosticError))}`,
1462
+ "Run /webui-status detailed and share this text with your troubleshooting assistant.",
1463
+ ].join("\n"),
1464
+ }));
1465
+ if (reasonElement) reasonElement.textContent = report.summary;
1466
+ if (reportElement) reportElement.value = report.text;
1467
+ }
1468
+
1469
+ function markBootReady() {
1470
+ if (bootFailed) return;
1471
+ bootSettled = true;
1472
+ clearTimeout(watchdog);
1473
+ window.removeEventListener("error", onWindowError, true);
1474
+ window.removeEventListener("unhandledrejection", onUnhandledRejection);
1475
+ if (panel) panel.hidden = true;
1476
+ }
1477
+
1478
+ function onWindowError(event) {
1479
+ const target = event.target;
1480
+ const resource = target && target !== window ? target.src || target.href : "";
1481
+ const tag = String(target?.tagName || "").toUpperCase();
1482
+ if (resource && !["SCRIPT", "LINK"].includes(tag)) return;
1483
+ const reason = resource ? `A critical ${tag.toLowerCase()} resource failed to load: ${sanitizedUrl(resource)}` : "A JavaScript error stopped WebUI startup.";
1484
+ showBootFailure(reason, event.error || event.message || resource);
1485
+ }
1486
+
1487
+ function onUnhandledRejection(event) {
1488
+ showBootFailure("An unhandled promise rejection stopped WebUI startup.", event.reason);
1489
+ }
1490
+
1491
+ async function copyReport() {
1492
+ const report = reportElement?.value || "";
1493
+ try {
1494
+ if (!report) throw new Error("The report is empty.");
1495
+ if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(report);
1496
+ else {
1497
+ reportElement.focus();
1498
+ reportElement.select();
1499
+ if (!document.execCommand?.("copy")) throw new Error("Clipboard API unavailable.");
1500
+ }
1501
+ if (copyStatus) copyStatus.textContent = "Troubleshooting report copied.";
1502
+ } catch {
1503
+ reportElement?.focus();
1504
+ reportElement?.select();
1505
+ if (copyStatus) copyStatus.textContent = "Automatic copy failed. The report is selected; copy it manually.";
1506
+ }
1507
+ }
1508
+
1509
+ window.addEventListener("error", onWindowError, true);
1510
+ window.addEventListener("unhandledrejection", onUnhandledRejection);
1511
+ copyButton?.addEventListener("click", copyReport);
1512
+ reloadButton?.addEventListener("click", () => window.location.reload());
1513
+
1514
+ watchdog = setTimeout(() => {
1515
+ showBootFailure(`WebUI startup did not finish within ${Math.round((Date.now() - bootStartedAt.getTime()) / 1000)} seconds.`, new Error("Startup watchdog timed out"));
1516
+ }, 12_000);
1517
+
1518
+ const importApp = typeof window.__PI_WEBUI_BOOT_IMPORT__ === "function"
1519
+ ? window.__PI_WEBUI_BOOT_IMPORT__
1520
+ : (source) => import(source);
1521
+ const criticalStylesheet = document.querySelector('link[rel="stylesheet"]');
1522
+ const stylesheetReady = criticalStylesheet?.sheet
1523
+ ? Promise.resolve()
1524
+ : fetch(criticalStylesheet?.href || "/styles.css", { cache: "no-store", credentials: "same-origin" }).then((response) => {
1525
+ if (!response.ok) throw new Error(`Critical stylesheet returned HTTP ${response.status}: ${sanitizedUrl(response.url || criticalStylesheet?.href)}`);
1526
+ response.body?.cancel?.().catch?.(() => {});
1527
+ });
1528
+ Promise.all([importApp(appSource), stylesheetReady]).then(markBootReady).catch((error) => {
1529
+ showBootFailure("The WebUI entry module, one of its imports, or the critical stylesheet failed to load or evaluate.", error);
1530
+ });
1531
+ })();
1532
+ </script>
1170
1533
  </body>
1171
1534
  </html>