@firstpick/pi-package-webui 0.8.1 → 0.8.3

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 (51) hide show
  1. package/README.md +21 -3
  2. package/bin/pi-webui.mjs +287 -32
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/thinking-stream-recovery.mjs +156 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/ui-layout-settings.mjs +254 -0
  8. package/package.json +5 -3
  9. package/public/app.js +3072 -142
  10. package/public/index.html +188 -39
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +1091 -39
  13. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  14. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  15. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  16. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  17. package/tests/browser/interaction-continuity.spec.mjs +187 -0
  18. package/tests/browser/mobile-foundation.spec.mjs +11 -0
  19. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  20. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  21. package/tests/browser/stats-overlay.spec.mjs +265 -0
  22. package/tests/codex-fast-mode-static.test.mjs +2 -2
  23. package/tests/component-update-api-static.test.mjs +67 -0
  24. package/tests/component-update-state.test.mjs +80 -0
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  27. package/tests/fast-mode-client-static.test.mjs +2 -2
  28. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  29. package/tests/fixtures/fake-pi.mjs +180 -6
  30. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  31. package/tests/git-workflow-preferences.test.mjs +4 -2
  32. package/tests/http-endpoints-harness.test.mjs +88 -1
  33. package/tests/interaction-state-stability-static.test.mjs +24 -4
  34. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  35. package/tests/mobile-foundation-static.test.mjs +6 -4
  36. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  37. package/tests/mobile-static.test.mjs +34 -16
  38. package/tests/native-parity-harness.test.mjs +2 -0
  39. package/tests/open-issue-wizard-static.test.mjs +1 -1
  40. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  41. package/tests/questionnaire-dialog.test.mjs +511 -0
  42. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  43. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  44. package/tests/side-panel-resize-static.test.mjs +1 -0
  45. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  46. package/tests/sse-backpressure-harness.test.mjs +51 -12
  47. package/tests/stats-dashboard-static.test.mjs +266 -0
  48. package/tests/subagent-launch-slots.test.mjs +1 -1
  49. package/tests/thinking-stream-recovery.test.mjs +88 -0
  50. package/tests/ui-layout-settings.test.mjs +92 -0
  51. package/tests/webui-settings-locking.test.mjs +159 -0
package/README.md CHANGED
@@ -79,6 +79,18 @@ Running `/webui-start` again on the same URL restarts the HTTP server. By defaul
79
79
 
80
80
  `/webui-status` reports the URL, online state, network exposure, and Remote PIN auth state. `detailed` adds tabs, sessions, models/providers, and recent backend events.
81
81
 
82
+ ### Control Deck component updates
83
+
84
+ The **Pi** and **Web UI** version tags in the Control Deck show component-specific `available`, `running`, `succeeded`, or `failed` status. Open the Pi tag for release notes and its Pi update action. Open the Web UI tag for installed/latest versions, the npm package link, and its Web UI update action.
85
+
86
+ Tag actions run one target in the background and do not replace the existing **Update & restart** controls:
87
+
88
+ - **Update Pi** uses the selected Pi installation's `pi update --self` path. It does not restart the Web UI or interrupt managed Pi tabs. New or explicitly reloaded Pi sessions use the updated Pi; already-running tabs keep their loaded runtime.
89
+ - **Update Web UI** updates only `@firstpick/pi-package-webui` in the installation that started the server. It does not restart the server automatically; restart the Web UI after success to activate the new version.
90
+ - Only one privileged component or legacy update runs at a time. Buttons remain disabled while work is running, and a bounded failure remains visible with a retry action.
91
+
92
+ For security, starting either component update is allowed only from localhost, even when Remote PIN access is enabled. Automatic Web UI self-update is disabled for source/development checkouts so it cannot overwrite a working tree; update that checkout with its normal source or package-manager workflow instead. Background job status is process-local, so if the server exits during an update, verify the installed version before retrying. The top-right update notification and existing update-and-restart actions retain their broader legacy behavior.
93
+
82
94
  ## Standalone CLI
83
95
 
84
96
  Use the CLI when you want to start the Web UI without first opening terminal Pi:
@@ -127,13 +139,19 @@ Environment variables:
127
139
  - `PI_WEBUI_OUTPUT_MODE=normal|compact-v1` sets the server default for newly auto-negotiated browser connections.
128
140
  - `PI_WEBUI_RPC_SUPERVISOR=0` opts out to the legacy server-owned Pi transport only when the current scope has no live managed tabs. Use explicit shutdown before disabling or downgrading; fallback startup refuses to create duplicate direct children for a live managed scope.
129
141
  - Pi Web UI automatically injects a loopback `PI_WEBUI_RECOVERY_URL` and a bearer `PI_WEBUI_RECOVERY_TOKEN` into spawned Pi RPC processes. The authenticated endpoint can only create a separate plan-only recovery tab; keep any manually supplied token private.
130
- - `PI_WEBUI_SETTINGS_FILE=/path/to/settings.json` overrides persisted Web UI settings such as Remote PIN auth, guided Git preferences, and global Tools/Skills defaults.
142
+ - `PI_WEBUI_SETTINGS_FILE=/path/to/settings.json` authoritatively overrides the private Web UI settings file (normally `~/.pi/webui/settings.json`) and disables automatic import from the old XDG location.
131
143
  - `PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT=/path/to/package-root` overrides the npm prefix used for optional companion installs.
132
144
  - `PI_WEBUI_FAST_PICKS_FILE=/path/to/paths.json` overrides saved cwd fast-pick storage.
133
145
  - `PI_WEBUI_NPM_BIN=/path/to/npm` overrides the npm executable used by optional feature install/update actions. By default, Web UI resolves the selected `pi` command, prefers `npm-cli.js` from that Pi installation, and runs it through Node. This prevents stale earlier `PATH` shims such as `%APPDATA%\npm\npm.cmd` from redirecting updates away from the active Pi installation.
134
146
  - `PI_BANG_AUTOCOMPLETE_INCLUDE_HISTORY=1` lets optional bang-command autocomplete include local fish/bash/zsh history executables.
135
147
  - `PI_BANG_AUTOCOMPLETE_RUNTIME_STORE_PATH=/path/to/runtime.json` overrides the runtime store shared with `@firstpick/pi-extension-bang-command-autocomplete`.
136
148
 
149
+ ### Persistent interface settings
150
+
151
+ Pi Web UI stores user-scoped settings in `~/.pi/webui/settings.json` by default. When that file is absent, a valid prior `$XDG_CONFIG_HOME/pi-webui/settings.json` (or `~/.config/pi-webui/settings.json`) is imported once without modifying or deleting the old file. An existing new file always wins, including when it is malformed, and `PI_WEBUI_SETTINGS_FILE` remains isolated from this migration. Writes use a private same-directory temporary file, atomic replacement, and a bounded same-host process lock; newly created settings files and directories use private permissions on supported platforms.
152
+
153
+ The authenticated `GET /api/interface-preferences` response includes normalized `preferences`, versioned `layout`, and an opaque `layoutRevision`. `PUT /api/interface-preferences` remains compatible with width-only `{ "sidePanelWidth": 612 }` writes. Layout patches require the latest revision in `expectedLayoutRevision`, merge only named fields, and are limited to 32 KiB; stale revisions return `409`, unsupported media types `415`, oversized bodies `413`, and invalid or unknown fields `400`. Browser local storage remains a non-destructive compatibility cache. Semantic file moves, prompt attachments, and follow-up queue mutations are not stored in the interface-layout envelope.
154
+
137
155
  ### Durable Pi session continuity
138
156
 
139
157
  Pi Web UI normally runs Pi RPC tabs under a narrow detached supervisor. Restarting only the HTTP Web UI—through `/webui-start` on the same URL, **Restart**, a successful **Update & restart**, `POST /api/restart`, or a restart-safe service-manager `SIGTERM`—preserves each managed Pi PID, tab identity, cwd, session file, running state, and active model turn. Output produced while the HTTP server is absent is replayed in supervisor order. The browser rejects duplicate or older replay records; if the bounded live buffer has a gap, it refreshes tabs, state, and the durable transcript from Pi and warns that buffered live output may be incomplete.
@@ -321,7 +339,7 @@ Discovery-path rules: at most 24 paths and direct children only (no recursive wa
321
339
  - **What it is:** A browser-native `/skills` setup dialog for skills available in the active Pi tab.
322
340
  - **What you can do:** Find skills by name or description, then use **Session only** to change automatic invocation on the current branch or **Global default** to save the skill allowlist inherited by future sessions.
323
341
 
324
- Session-specific choices always win when their branch is resumed or selected in `/tree`. Saving a global default does not mutate currently open sessions. Global defaults are stored in the Pi Web UI settings file (normally `~/.config/pi-webui/settings.json` or `$XDG_CONFIG_HOME/pi-webui/settings.json`).
342
+ Session-specific choices always win when their branch is resumed or selected in `/tree`. Saving a global default does not mutate currently open sessions. Global defaults are stored in the Pi Web UI settings file (normally `~/.pi/webui/settings.json`).
325
343
 
326
344
  ### Optional features
327
345
 
@@ -451,7 +469,7 @@ Optional companions:
451
469
 
452
470
  The Git workflow button runs local git commands in the active Pi working directory. It covers both empty/new projects and existing repositories.
453
471
 
454
- Before first use, run `/git-workflow-setup` in Pi or choose **Common Pi Options → Guided Git Setup** in the browser. Select an exact authenticated `provider/modelId`, a supported reasoning effort, and the workflow defaults described below. The browser preselects the active tab model when possible, but saving is always explicit. Preferences are stored globally in the Pi Web UI settings file (normally `~/.config/pi-webui/settings.json` or `$XDG_CONFIG_HOME/pi-webui/settings.json`), not in browser storage.
472
+ Before first use, run `/git-workflow-setup` in Pi or choose **Common Pi Options → Guided Git Setup** in the browser. Select an exact authenticated `provider/modelId`, a supported reasoning effort, and the workflow defaults described below. The browser preselects the active tab model when possible, but saving is always explicit. Preferences are stored globally in the Pi Web UI settings file (normally `~/.pi/webui/settings.json`), not in browser storage.
455
473
 
456
474
  For a new project, the browser flow can:
457
475
 
package/bin/pi-webui.mjs CHANGED
@@ -33,12 +33,14 @@ import {
33
33
  } from "../lib/session-actions.mjs";
34
34
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
35
35
  import { terminateProcessTree } from "../lib/process-tree.mjs";
36
+ import { ThinkingStreamRecovery } from "../lib/thinking-stream-recovery.mjs";
36
37
  import {
37
38
  classifyGitPathFailure,
38
39
  findWindowsReservedGitPath,
39
40
  windowsReservedGitPathFailure,
40
41
  } from "../lib/git-command-errors.mjs";
41
42
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
43
+ import { ComponentUpdateState, validateComponentUpdateRequest } from "../lib/component-update-state.mjs";
42
44
  import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
43
45
  import {
44
46
  GIT_WORKFLOW_DEFAULT_VARIANTS,
@@ -60,6 +62,12 @@ import {
60
62
  writeGitWorkflowPreferences,
61
63
  writeWebuiSettings,
62
64
  } from "../lib/git-workflow-preferences.mjs";
65
+ import {
66
+ UI_LAYOUT_REQUEST_MAX_BYTES,
67
+ mergeUiLayout,
68
+ uiLayoutRevision,
69
+ validateUiLayoutPatch,
70
+ } from "../lib/ui-layout-settings.mjs";
63
71
  import {
64
72
  SUBAGENT_LAUNCH_SLOT_LIMITS,
65
73
  SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
@@ -382,6 +390,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
382
390
  ["todoProgressWidget", "@firstpick/pi-extension-todo-progress"],
383
391
  ["tuiToolsCommand", "@firstpick/pi-extension-tools"],
384
392
  ["remoteWebui", "@firstpick/pi-package-remote-webui"],
393
+ ["questionnaire", "@firstpick/pi-package-questionnaire"],
385
394
  ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
386
395
  ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
387
396
  ["statsCommand", "@firstpick/pi-extension-stats"],
@@ -1274,35 +1283,106 @@ function sendRemoteAuthRequired(req, res, url) {
1274
1283
  sendJson(res, 401, { ok: false, error: "Remote PIN required", remoteAuthRequired: true }, { "www-authenticate": "PiRemotePin" });
1275
1284
  }
1276
1285
 
1277
- // Browser SSE does not have a replay queue. A client that stops draining is
1278
- // therefore removed on the first backpressure signal instead of accumulating
1279
- // an unbounded queue or selectively dropping/reordering semantic events.
1280
- // Reconnection remains authoritative through the existing tab/state refresh.
1286
+ // A false ServerResponse.write() result means the frame was accepted but the
1287
+ // writable buffer crossed its high-water mark. Treating that as a dead client
1288
+ // disconnects healthy Chromium EventSource streams as soon as a frame exceeds
1289
+ // roughly 16 KiB. Queue subsequent frames until "drain", with strict bounds so
1290
+ // a client that truly stops reading cannot grow server memory indefinitely.
1291
+ const SSE_BACKPRESSURE_MAX_PENDING_BYTES = 512 * 1024;
1292
+ const SSE_BACKPRESSURE_MAX_PENDING_FRAMES = 256;
1293
+ const SSE_BACKPRESSURE_TIMEOUT_MS = 10_000;
1294
+
1295
+ function clearSseBackpressureTimer(client) {
1296
+ if (!client?.backpressureTimer) return;
1297
+ clearTimeout(client.backpressureTimer);
1298
+ client.backpressureTimer = undefined;
1299
+ }
1300
+
1281
1301
  function evictSlowSseClient(client) {
1282
1302
  if (!client || client.evicted) return;
1283
1303
  client.evicted = true;
1304
+ client.backpressured = false;
1305
+ clearSseBackpressureTimer(client);
1306
+ client.pendingFrames = [];
1307
+ client.pendingFrameBytes = 0;
1284
1308
  client.tab?.sseClients?.delete(client);
1285
1309
  try {
1286
- client.res?.destroy();
1310
+ // Complete the chunked response so Chromium can reconnect without
1311
+ // ERR_INCOMPLETE_CHUNKED_ENCODING.
1312
+ client.res?.end();
1287
1313
  } catch {
1288
1314
  // A closed browser socket needs no further cleanup.
1289
1315
  }
1290
1316
  }
1291
1317
 
1292
- function sendSse(client, event) {
1318
+ function scheduleSseBackpressureTimeout(client) {
1319
+ clearSseBackpressureTimer(client);
1320
+ client.backpressureTimer = setTimeout(() => evictSlowSseClient(client), SSE_BACKPRESSURE_TIMEOUT_MS);
1321
+ client.backpressureTimer.unref?.();
1322
+ }
1323
+
1324
+ function flushSseClient(client) {
1325
+ const res = client?.res;
1326
+ if (!client || client.evicted) return;
1327
+ if (!res || res.destroyed || res.writableEnded) {
1328
+ evictSlowSseClient(client);
1329
+ return;
1330
+ }
1331
+ client.backpressured = false;
1332
+ clearSseBackpressureTimer(client);
1333
+ while (client.pendingFrames?.length) {
1334
+ const frame = client.pendingFrames.shift();
1335
+ client.pendingFrameBytes -= Buffer.byteLength(frame);
1336
+ try {
1337
+ if (!res.write(frame)) {
1338
+ client.backpressured = true;
1339
+ scheduleSseBackpressureTimeout(client);
1340
+ res.once("drain", () => flushSseClient(client));
1341
+ return;
1342
+ }
1343
+ } catch {
1344
+ evictSlowSseClient(client);
1345
+ return;
1346
+ }
1347
+ }
1348
+ client.pendingFrameBytes = 0;
1349
+ }
1350
+
1351
+ function writeSseFrame(client, frame) {
1293
1352
  const res = client?.res || client;
1294
- const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
1295
- if (payload === undefined || !res || res.destroyed || client?.evicted) return false;
1353
+ if (!res || res.destroyed || res.writableEnded || client?.evicted) return false;
1354
+ if (client?.res && client.backpressured) {
1355
+ const frameBytes = Buffer.byteLength(frame);
1356
+ const pendingFrames = client.pendingFrames || (client.pendingFrames = []);
1357
+ const pendingBytes = Number(client.pendingFrameBytes) || 0;
1358
+ if (pendingFrames.length >= SSE_BACKPRESSURE_MAX_PENDING_FRAMES || pendingBytes + frameBytes > SSE_BACKPRESSURE_MAX_PENDING_BYTES) {
1359
+ evictSlowSseClient(client);
1360
+ return false;
1361
+ }
1362
+ pendingFrames.push(frame);
1363
+ client.pendingFrameBytes = pendingBytes + frameBytes;
1364
+ return true;
1365
+ }
1296
1366
  try {
1297
- const accepted = res.write(`data: ${payload}\n\n`);
1298
- if (!accepted && client?.res) evictSlowSseClient(client);
1299
- return accepted;
1367
+ if (!res.write(frame) && client?.res) {
1368
+ client.backpressured = true;
1369
+ scheduleSseBackpressureTimeout(client);
1370
+ res.once("drain", () => flushSseClient(client));
1371
+ }
1372
+ // write() returning false still accepted this frame.
1373
+ return true;
1300
1374
  } catch {
1301
1375
  if (client?.res) evictSlowSseClient(client);
1302
1376
  return false;
1303
1377
  }
1304
1378
  }
1305
1379
 
1380
+ function sendSse(client, event) {
1381
+ const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
1382
+ if (payload === undefined) return false;
1383
+ return writeSseFrame(client, `data: ${payload}\n\n`);
1384
+ }
1385
+
1306
1386
  function rpcSuccess(command, data = {}) {
1307
1387
  return { type: "response", command, success: true, data };
1308
1388
  }
@@ -9724,7 +9804,8 @@ async function primeTabRpc(tab) {
9724
9804
  function attachRpcToTab(tab, rpc) {
9725
9805
  tab.rpcUnsubscribe?.();
9726
9806
  tab.rpc = rpc;
9727
- tab.rpcUnsubscribe = rpc.onEvent((event) => {
9807
+ tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
9808
+ const event = tab.thinkingStreamRecovery.ingest(rawEvent);
9728
9809
  if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
9729
9810
  updateTabActivityFromEvent(tab, event);
9730
9811
  let scopedEvent = eventForTabClients(tab, event);
@@ -9764,6 +9845,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9764
9845
  gitWorkspace: gitWorkspace || null,
9765
9846
  lastState: null,
9766
9847
  pendingThinkingLevel: undefined,
9848
+ thinkingStreamRecovery: new ThinkingStreamRecovery(),
9767
9849
  gitWorkflowGenerationRestore: null,
9768
9850
  gitWorkflowMessageGeneration: null,
9769
9851
  activity: createTabActivity(createdAt),
@@ -10352,6 +10434,28 @@ function spawnRestartServer(restorableTabs, supervisorCursor) {
10352
10434
  let updateStatusCache = null;
10353
10435
  let updateStatusCacheAt = 0;
10354
10436
  let piUpdateInProgress = false;
10437
+ const componentUpdateState = new ComponentUpdateState();
10438
+
10439
+ function webuiComponentUpdateUnavailableReason() {
10440
+ if (webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules")) {
10441
+ return "Automatic Web UI update is unavailable from a source or development checkout.";
10442
+ }
10443
+ return "";
10444
+ }
10445
+
10446
+ function privilegedUpdateInProgress() {
10447
+ return piUpdateInProgress || componentUpdateState.hasRunning();
10448
+ }
10449
+
10450
+ function componentUpdatesForRequest(req) {
10451
+ const webuiUnavailableReason = webuiComponentUpdateUnavailableReason();
10452
+ return componentUpdateState.publicStates({
10453
+ localRequest: isLocalRequest(req),
10454
+ updateInProgress: privilegedUpdateInProgress(),
10455
+ webuiAvailable: !webuiUnavailableReason,
10456
+ webuiUnavailableReason,
10457
+ });
10458
+ }
10355
10459
 
10356
10460
  function updateChecksSkippedReason() {
10357
10461
  if (process.env.PI_OFFLINE) return "PI_OFFLINE is set";
@@ -10434,7 +10538,8 @@ function updateStatusForRequest(status, req) {
10434
10538
  return {
10435
10539
  ...status,
10436
10540
  canRunUpdate: isLocalRequest(req),
10437
- updateInProgress: piUpdateInProgress,
10541
+ updateInProgress: privilegedUpdateInProgress(),
10542
+ componentUpdates: componentUpdatesForRequest(req),
10438
10543
  };
10439
10544
  }
10440
10545
 
@@ -10704,6 +10809,42 @@ async function bunGlobalPackageRootUpdateTask() {
10704
10809
  };
10705
10810
  }
10706
10811
 
10812
+ async function currentWebuiComponentUpdateTask(npmRuntime = {}) {
10813
+ const unavailableReason = webuiComponentUpdateUnavailableReason();
10814
+ if (unavailableReason) throw makeHttpError(409, unavailableReason);
10815
+
10816
+ const normalizedPackageRoot = path.resolve(packageRoot);
10817
+ for (const nodeModulesRoot of await bunGlobalNodeModulesRoots()) {
10818
+ if (path.resolve(packageNodeModulesPath(nodeModulesRoot, WEBUI_PACKAGE)) !== normalizedPackageRoot) continue;
10819
+ return {
10820
+ label: "global Bun Web UI package",
10821
+ command: "bun",
10822
+ args: ["install", "-g", "--ignore-scripts", "--minimum-release-age=0", `${WEBUI_PACKAGE}@latest`],
10823
+ cwd: homedir(),
10824
+ };
10825
+ }
10826
+
10827
+ const installRoot = nodeModulesParentForPackageRoot(packageRoot);
10828
+ return npmPrefixUpdateTask("current Web UI package", installRoot, [WEBUI_PACKAGE], npmRuntime);
10829
+ }
10830
+
10831
+ async function resolveComponentUpdateTasks(target) {
10832
+ if (target === "pi") return resolvePiUpdateCommands({ all: false });
10833
+ if (target === "webui") {
10834
+ let npmRuntime = {};
10835
+ try {
10836
+ const piTasks = await resolvePiUpdateCommands({ all: false });
10837
+ npmRuntime = {
10838
+ preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
10839
+ };
10840
+ } catch {
10841
+ recordEvent({ type: "webui_component_update_npm_resolution_fallback", target });
10842
+ }
10843
+ return [await currentWebuiComponentUpdateTask(npmRuntime)];
10844
+ }
10845
+ throw makeHttpError(400, "Unsupported component update target.");
10846
+ }
10847
+
10707
10848
  function updateTaskDisplay(task) {
10708
10849
  return task.displayCommand || formatCommandForDisplay(task.command, task.args || []);
10709
10850
  }
@@ -10792,8 +10933,43 @@ function combinedUpdateOutput(results, field) {
10792
10933
  .join("\n\n");
10793
10934
  }
10794
10935
 
10936
+ function componentUpdateSuccessMessage(target) {
10937
+ if (target === "pi") return "Pi update completed. New or reloaded Pi sessions use the update.";
10938
+ return "Web UI update completed. Restart the Web UI to use the update.";
10939
+ }
10940
+
10941
+ async function runComponentUpdate(target) {
10942
+ try {
10943
+ const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
10944
+ if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
10945
+ const command = updateTasks.map(updateTaskDisplay).join(" && ");
10946
+ recordEvent({ type: "webui_component_update_started", target, command });
10947
+ for (const task of updateTasks) await runUpdateTask(task);
10948
+ updateStatusCache = null;
10949
+ updateStatusCacheAt = 0;
10950
+ componentUpdateState.succeed(target, componentUpdateSuccessMessage(target));
10951
+ recordEvent({ type: "webui_component_update_completed", target, command });
10952
+ } catch (error) {
10953
+ updateStatusCache = null;
10954
+ updateStatusCacheAt = 0;
10955
+ componentUpdateState.fail(target, error);
10956
+ recordEvent({ type: "webui_component_update_failed", target, error: componentUpdateState.get(target).error });
10957
+ }
10958
+ }
10959
+
10960
+ function startComponentUpdate(target) {
10961
+ if (piUpdateInProgress || componentUpdateState.hasRunning()) throw makeHttpError(409, "Another privileged update is already running.");
10962
+ const unavailableReason = target === "webui" ? webuiComponentUpdateUnavailableReason() : "";
10963
+ if (unavailableReason) throw makeHttpError(409, unavailableReason);
10964
+ componentUpdateState.begin(target);
10965
+ recordEvent({ type: "webui_component_update_accepted", target });
10966
+ setImmediate(() => { void runComponentUpdate(target); });
10967
+ return componentUpdateState.get(target);
10968
+ }
10969
+
10795
10970
  async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
10796
10971
  if (piUpdateInProgress) throw makeHttpError(409, "A Pi update is already running.");
10972
+ if (componentUpdateState.hasRunning()) throw makeHttpError(409, "A component update is already running.");
10797
10973
  piUpdateInProgress = true;
10798
10974
  let restartPrepared = false;
10799
10975
  try {
@@ -11100,7 +11276,11 @@ function fallbackRpcResponse(tab, command, error) {
11100
11276
 
11101
11277
  async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
11102
11278
  try {
11103
- return rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
11279
+ const response = rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
11280
+ if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
11281
+ response.data = { ...response.data, messages: tab.thinkingStreamRecovery.applyToMessages(response.data.messages) };
11282
+ }
11283
+ return response;
11104
11284
  } catch (error) {
11105
11285
  const message = sanitizeError(error);
11106
11286
  if (/Pi RPC process is not running/i.test(message)) return responseWithPendingThinking(tab, fallbackRpcResponse(tab, command, error));
@@ -13558,18 +13738,73 @@ async function saveOutputModeDefault(value) {
13558
13738
  return outputModeMetadata();
13559
13739
  }
13560
13740
 
13741
+ function interfacePreferencesResponse(settings) {
13742
+ return {
13743
+ preferences: settings.interfacePreferences,
13744
+ layout: settings.uiLayout,
13745
+ layoutRevision: uiLayoutRevision(settings.uiLayout),
13746
+ };
13747
+ }
13748
+
13749
+ function interfacePreferencesRequestError(error, operation) {
13750
+ if (error?.statusCode) return error;
13751
+ if (error?.code === "UI_LAYOUT_INVALID" || error instanceof TypeError) return makeHttpError(400, formatCliError(error));
13752
+ if (error?.code === "UI_LAYOUT_STALE_REVISION") return makeHttpError(409, "The interface layout changed after it was read; refresh and retry.");
13753
+ const message = error?.code === "WEBUI_SETTINGS_LOCK_TIMEOUT"
13754
+ ? "Interface preferences are busy; retry shortly."
13755
+ : `Could not ${operation} interface preferences.`;
13756
+ const wrapped = makeHttpError(error?.code === "WEBUI_SETTINGS_LOCK_TIMEOUT" ? 503 : 500, message);
13757
+ wrapped.userMessage = message;
13758
+ return wrapped;
13759
+ }
13760
+
13761
+ function requireInterfacePreferencesJsonRequest(req) {
13762
+ const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
13763
+ if (contentType !== "application/json") throw makeHttpError(415, "Interface preference saves require Content-Type: application/json.");
13764
+ }
13765
+
13766
+ function validateInterfacePreferencesBody(body) {
13767
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw makeHttpError(400, "Interface preference save body must be an object.");
13768
+ const allowed = new Set(["sidePanelWidth", "layout", "expectedLayoutRevision"]);
13769
+ const unknown = Object.keys(body).filter((key) => !allowed.has(key));
13770
+ if (unknown.length) throw makeHttpError(400, `Interface preference save contains unsupported field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`);
13771
+ const hasWidth = Object.hasOwn(body, "sidePanelWidth");
13772
+ const hasLayout = Object.hasOwn(body, "layout");
13773
+ if (!hasWidth && !hasLayout) throw makeHttpError(400, "Interface preference save must include sidePanelWidth or layout.");
13774
+ if (hasWidth) {
13775
+ if (typeof body.sidePanelWidth !== "number" || !Number.isFinite(body.sidePanelWidth) || body.sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || body.sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
13776
+ throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
13777
+ }
13778
+ }
13779
+ if (hasLayout) {
13780
+ if (!Object.hasOwn(body, "expectedLayoutRevision") || typeof body.expectedLayoutRevision !== "string" || !/^[a-f0-9]{64}$/u.test(body.expectedLayoutRevision)) {
13781
+ throw makeHttpError(400, "layout saves require the latest layoutRevision as expectedLayoutRevision.");
13782
+ }
13783
+ validateUiLayoutPatch(body.layout);
13784
+ } else if (Object.hasOwn(body, "expectedLayoutRevision")) {
13785
+ throw makeHttpError(400, "expectedLayoutRevision is only valid with a layout save.");
13786
+ }
13787
+ return { hasWidth, hasLayout };
13788
+ }
13789
+
13561
13790
  async function interfacePreferencesData() {
13562
- const settings = await readWebuiSettings();
13563
- return { preferences: settings.interfacePreferences };
13791
+ return interfacePreferencesResponse(await readWebuiSettings());
13564
13792
  }
13565
13793
 
13566
13794
  async function saveInterfacePreferences(body = {}) {
13567
- const sidePanelWidth = Number(body.sidePanelWidth);
13568
- if (!Number.isFinite(sidePanelWidth) || sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
13569
- throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
13570
- }
13571
- const settings = await writeWebuiSettings({ interfacePreferences: { sidePanelWidth: Math.round(sidePanelWidth) } });
13572
- return { preferences: settings.interfacePreferences };
13795
+ const { hasWidth, hasLayout } = validateInterfacePreferencesBody(body);
13796
+ const settings = await updateWebuiSettings((current) => {
13797
+ if (hasLayout && body.expectedLayoutRevision !== uiLayoutRevision(current.uiLayout)) {
13798
+ const error = new Error("stale interface layout revision");
13799
+ error.code = "UI_LAYOUT_STALE_REVISION";
13800
+ throw error;
13801
+ }
13802
+ const patch = {};
13803
+ if (hasWidth) patch.interfacePreferences = { sidePanelWidth: Math.round(body.sidePanelWidth) };
13804
+ if (hasLayout) patch.uiLayout = mergeUiLayout(current.uiLayout, body.layout);
13805
+ return patch;
13806
+ });
13807
+ return interfacePreferencesResponse(settings);
13573
13808
  }
13574
13809
 
13575
13810
  const remoteAuth = {
@@ -14074,12 +14309,28 @@ const server = createServer(async (req, res) => {
14074
14309
  }
14075
14310
 
14076
14311
  if (url.pathname === "/api/interface-preferences" && req.method === "GET") {
14077
- sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
14312
+ try {
14313
+ sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
14314
+ } catch (error) {
14315
+ throw interfacePreferencesRequestError(error, "read");
14316
+ }
14078
14317
  return;
14079
14318
  }
14080
14319
 
14081
14320
  if (url.pathname === "/api/interface-preferences" && req.method === "PUT") {
14082
- sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(await readJsonBody(req)) });
14321
+ requireInterfacePreferencesJsonRequest(req);
14322
+ try {
14323
+ let body;
14324
+ try {
14325
+ body = await readJsonBody(req, { limitBytes: UI_LAYOUT_REQUEST_MAX_BYTES });
14326
+ } catch (error) {
14327
+ if (error instanceof SyntaxError) throw makeHttpError(400, "Interface preference save body must be valid JSON.");
14328
+ throw error;
14329
+ }
14330
+ sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(body) });
14331
+ } catch (error) {
14332
+ throw interfacePreferencesRequestError(error, "save");
14333
+ }
14083
14334
  return;
14084
14335
  }
14085
14336
 
@@ -14283,16 +14534,10 @@ const server = createServer(async (req, res) => {
14283
14534
  replayExtensionStatuses(tab, client);
14284
14535
  replayExtensionWidgets(tab, client);
14285
14536
  replayPendingExtensionUiRequests(tab, client);
14286
- const keepAlive = setInterval(() => {
14287
- try {
14288
- if (!res.write(": keepalive\n\n")) evictSlowSseClient(client);
14289
- } catch {
14290
- evictSlowSseClient(client);
14291
- }
14292
- }, 15000);
14537
+ const keepAlive = setInterval(() => writeSseFrame(client, ": keepalive\n\n"), 15000);
14293
14538
  req.on("close", () => {
14294
14539
  clearInterval(keepAlive);
14295
- tab.sseClients.delete(client);
14540
+ evictSlowSseClient(client);
14296
14541
  });
14297
14542
  return;
14298
14543
  }
@@ -14435,6 +14680,16 @@ const server = createServer(async (req, res) => {
14435
14680
  return;
14436
14681
  }
14437
14682
 
14683
+ if (url.pathname === "/api/component-update" && req.method === "POST") {
14684
+ requireLocalhostRoute(req, url.pathname);
14685
+ const body = await readJsonBody(req);
14686
+ const validation = validateComponentUpdateRequest(body);
14687
+ if (!validation.ok) throw makeHttpError(400, validation.error);
14688
+ startComponentUpdate(validation.target);
14689
+ sendJson(res, 202, { ok: true, data: componentUpdatesForRequest(req)[validation.target] });
14690
+ return;
14691
+ }
14692
+
14438
14693
  if (url.pathname === "/api/update" && req.method === "POST") {
14439
14694
  requireLocalhostRoute(req, url.pathname);
14440
14695
  const body = await readJsonBody(req);
@@ -0,0 +1,126 @@
1
+ export const COMPONENT_UPDATE_TARGETS = Object.freeze(["pi", "webui"]);
2
+
3
+ const TARGET_SET = new Set(COMPONENT_UPDATE_TARGETS);
4
+ const DEFAULT_ERROR_MAX_LENGTH = 1200;
5
+ const DEFAULT_MESSAGE_MAX_LENGTH = 320;
6
+
7
+ function targetLabel(target) {
8
+ return target === "pi" ? "Pi" : "Web UI";
9
+ }
10
+
11
+ function boundedText(value, maxLength) {
12
+ const text = String(value ?? "")
13
+ .replace(/\u001b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "")
14
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "")
15
+ .trim();
16
+ return text.length > maxLength ? `${text.slice(0, Math.max(0, maxLength - 1))}…` : text;
17
+ }
18
+
19
+ export function sanitizeComponentUpdateError(value, maxLength = DEFAULT_ERROR_MAX_LENGTH) {
20
+ const raw = value instanceof Error ? (value.userMessage || value.message || String(value)) : String(value ?? "Unknown error");
21
+ const redacted = raw
22
+ .replace(/\b(authorization\s*:\s*)(?:bearer|basic)\s+[^\s,;]+/gi, "$1[redacted]")
23
+ .replace(/\b((?:_?auth[_-]?token|access[_-]?token|api[_-]?key|password|passwd|secret|token)\s*[=:]\s*)[^\s,;]+/gi, "$1[redacted]")
24
+ .replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[redacted]@")
25
+ .replace(/\b(?:npm_[A-Za-z0-9]{20,}|gh[opusr]_[A-Za-z0-9_]{20,})\b/g, "[redacted]");
26
+ return boundedText(redacted, Math.max(80, Number(maxLength) || DEFAULT_ERROR_MAX_LENGTH)) || "Unknown error";
27
+ }
28
+
29
+ export function validateComponentUpdateRequest(body) {
30
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
31
+ return { ok: false, error: "Request body must be an object containing only target." };
32
+ }
33
+ const keys = Object.keys(body);
34
+ if (keys.length !== 1 || keys[0] !== "target" || !TARGET_SET.has(body.target)) {
35
+ return { ok: false, error: 'target must be exactly "pi" or "webui", with no additional fields.' };
36
+ }
37
+ return { ok: true, target: body.target };
38
+ }
39
+
40
+ function initialState(target) {
41
+ return {
42
+ target,
43
+ state: "idle",
44
+ startedAt: null,
45
+ finishedAt: null,
46
+ message: "",
47
+ error: "",
48
+ restartRequired: target === "webui",
49
+ };
50
+ }
51
+
52
+ export class ComponentUpdateState {
53
+ #states;
54
+ #now;
55
+
56
+ constructor({ now = () => new Date() } = {}) {
57
+ this.#now = now;
58
+ this.#states = Object.fromEntries(COMPONENT_UPDATE_TARGETS.map((target) => [target, initialState(target)]));
59
+ }
60
+
61
+ hasRunning() {
62
+ return COMPONENT_UPDATE_TARGETS.some((target) => this.#states[target].state === "running");
63
+ }
64
+
65
+ begin(target) {
66
+ if (!TARGET_SET.has(target)) throw new TypeError(`Unsupported component update target: ${target}`);
67
+ if (this.hasRunning()) throw new Error("Another component update is already running.");
68
+ const startedAt = this.#now().toISOString();
69
+ this.#states[target] = {
70
+ ...initialState(target),
71
+ state: "running",
72
+ startedAt,
73
+ message: `Updating ${targetLabel(target)}…`,
74
+ };
75
+ return this.get(target);
76
+ }
77
+
78
+ succeed(target, message) {
79
+ this.#requireRunning(target);
80
+ this.#states[target] = {
81
+ ...this.#states[target],
82
+ state: "succeeded",
83
+ finishedAt: this.#now().toISOString(),
84
+ message: boundedText(message, DEFAULT_MESSAGE_MAX_LENGTH),
85
+ error: "",
86
+ };
87
+ return this.get(target);
88
+ }
89
+
90
+ fail(target, error, message = `${targetLabel(target)} update failed.`) {
91
+ this.#requireRunning(target);
92
+ this.#states[target] = {
93
+ ...this.#states[target],
94
+ state: "failed",
95
+ finishedAt: this.#now().toISOString(),
96
+ message: boundedText(message, DEFAULT_MESSAGE_MAX_LENGTH),
97
+ error: sanitizeComponentUpdateError(error),
98
+ };
99
+ return this.get(target);
100
+ }
101
+
102
+ get(target) {
103
+ if (!TARGET_SET.has(target)) throw new TypeError(`Unsupported component update target: ${target}`);
104
+ return { ...this.#states[target] };
105
+ }
106
+
107
+ publicStates({ localRequest = false, updateInProgress = this.hasRunning(), webuiAvailable = true, webuiUnavailableReason = "" } = {}) {
108
+ return Object.fromEntries(COMPONENT_UPDATE_TARGETS.map((target) => {
109
+ const state = this.get(target);
110
+ let unavailableReason = "";
111
+ if (!localRequest) unavailableReason = "Component updates are only available from localhost.";
112
+ else if (target === "webui" && !webuiAvailable) unavailableReason = boundedText(webuiUnavailableReason || "Automatic Web UI update is unavailable for this installation.", DEFAULT_MESSAGE_MAX_LENGTH);
113
+ else if (updateInProgress) unavailableReason = "Another privileged update is already running.";
114
+ return [target, {
115
+ ...state,
116
+ canStart: unavailableReason === "",
117
+ unavailableReason,
118
+ }];
119
+ }));
120
+ }
121
+
122
+ #requireRunning(target) {
123
+ if (!TARGET_SET.has(target)) throw new TypeError(`Unsupported component update target: ${target}`);
124
+ if (this.#states[target].state !== "running") throw new Error(`Component update target ${target} is not running.`);
125
+ }
126
+ }