@firstpick/pi-package-webui 0.8.6 → 0.8.7

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 (89) hide show
  1. package/README.md +18 -606
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +558 -524
  5. package/index.ts +8 -5
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +17 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-preferences.mjs +16 -1
  11. package/lib/subagent-launch-slots.mjs +14 -2
  12. package/lib/trust-boundaries.mjs +3 -0
  13. package/lib/update/executor.mjs +99 -0
  14. package/lib/update/journal.mjs +175 -0
  15. package/lib/update/owners.mjs +70 -0
  16. package/lib/update/plan.mjs +134 -0
  17. package/lib/update/resolver.mjs +168 -0
  18. package/lib/update/supervisor.mjs +238 -0
  19. package/lib/update/verify.mjs +52 -0
  20. package/lib/update-commands.mjs +25 -13
  21. package/lib/webui-workspaces.mjs +17 -1
  22. package/package.json +4 -4
  23. package/public/app.js +1290 -82
  24. package/public/index.html +124 -48
  25. package/public/middle-button-drag-scroll.mjs +154 -0
  26. package/public/sampling-parameter-controls.mjs +361 -0
  27. package/public/service-worker.js +3 -1
  28. package/public/styles.css +417 -1
  29. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  30. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  31. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  32. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  33. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  34. package/tests/browser/update-reconnect.spec.mjs +92 -0
  35. package/tests/codex-fast-mode-static.test.mjs +2 -2
  36. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  37. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  38. package/tests/component-update-api-static.test.mjs +22 -61
  39. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  40. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  41. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  42. package/tests/fast-mode-client-static.test.mjs +1 -1
  43. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  44. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  45. package/tests/fixtures/fake-pi.mjs +66 -0
  46. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  47. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  48. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  49. package/tests/http-endpoints-harness.test.mjs +68 -18
  50. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  51. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  52. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  53. package/tests/mobile-foundation-static.test.mjs +4 -4
  54. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  55. package/tests/mobile-static.test.mjs +23 -21
  56. package/tests/open-issue-wizard-static.test.mjs +1 -1
  57. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  58. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  59. package/tests/questionnaire-dialog.test.mjs +3 -3
  60. package/tests/remote-auth-settings-harness.test.mjs +34 -0
  61. package/tests/rpc-supervisor-host.test.mjs +11 -2
  62. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  63. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  64. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  65. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  66. package/tests/sampling-parameter-controls.test.mjs +241 -0
  67. package/tests/session-sampling-helper.test.mjs +228 -0
  68. package/tests/session-sampling-http.test.mjs +168 -0
  69. package/tests/session-sampling-ui-static.test.mjs +370 -0
  70. package/tests/session-summary-core.test.mjs +24 -11
  71. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  72. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  73. package/tests/staged-content-hash-contract.test.mjs +52 -11
  74. package/tests/subagent-launch-slots.test.mjs +18 -1
  75. package/tests/theme-customizer-static.test.mjs +1 -1
  76. package/tests/ui-layout-settings.test.mjs +18 -1
  77. package/tests/update-api-harness.test.mjs +111 -0
  78. package/tests/update-commands.test.mjs +15 -45
  79. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  80. package/tests/update-journal-harness.test.mjs +59 -0
  81. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  82. package/tests/update-owners.test.mjs +27 -0
  83. package/tests/update-plan.test.mjs +58 -0
  84. package/tests/update-resolver.test.mjs +56 -0
  85. package/tests/update-supervisor-harness.test.mjs +57 -0
  86. package/tests/update-tab-restore-harness.test.mjs +24 -0
  87. package/tests/update-verify.test.mjs +31 -0
  88. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  89. package/webui-rpc-helper.mjs +119 -0
package/bin/pi-webui.mjs CHANGED
@@ -52,14 +52,19 @@ import {
52
52
  findWindowsReservedGitPath,
53
53
  windowsReservedGitPathFailure,
54
54
  } from "../lib/git-command-errors.mjs";
55
- import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
56
- import { ComponentUpdateState, validateComponentUpdateRequest } from "../lib/component-update-state.mjs";
55
+ import { ComponentUpdateState, sanitizeComponentUpdateError, validateComponentUpdateRequest, validateUpdateApplyRequest, validateUpdatePlanRequest } from "../lib/component-update-state.mjs";
56
+ import { resolveCanonicalPiRuntime, resolveWebuiRuntimeIdentity } from "../lib/update/resolver.mjs";
57
+ import { createUpdatePlan, assertPlanIdentity, assertUpdatePlanDigest } from "../lib/update/plan.mjs";
58
+ import { executeCommand, executePlanTargets } from "../lib/update/executor.mjs";
59
+ import { verifyTargetResult } from "../lib/update/verify.mjs";
60
+ import { acquireInstallLock, createUpdateJournal, readUpdateJournal, reconcileInterruptedUpdates, releaseInstallLock, transferInstallLock, transitionUpdateJournal } from "../lib/update/journal.mjs";
61
+ import { collectManagedRuntimes, createRestoreFile, listenWithRetry, managedRuntimePaths, probeCandidateRuntime, readRestoreFileOnce, readRuntimePointer, rollbackRuntimePointer, sweepRestoreFiles } from "../lib/update/supervisor.mjs";
57
62
  import { OPTIONAL_FEATURE_BY_ID, OPTIONAL_FEATURE_CATALOG } from "../lib/optional-feature-catalog.mjs";
58
63
  import {
59
64
  OptionalFeatureAuditCoordinator,
60
65
  OptionalFeatureMigrationStore,
61
66
  } from "../lib/optional-feature-migration.mjs";
62
- import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
67
+ import { resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
63
68
  import {
64
69
  GIT_WORKFLOW_DEFAULT_VARIANTS,
65
70
  GIT_WORKFLOW_DELIVERY_MODES,
@@ -175,6 +180,7 @@ const PROMPT_REQUEST_TIMEOUT_MS = Math.max(REQUEST_TIMEOUT_MS, Number.parseInt(p
175
180
  const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
176
181
  const WEBUI_HELPER_COMMAND = "webui-helper";
177
182
  const WEBUI_HELPER_RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
183
+ const SAMPLING_PARAMS_HTTP_MAX_BYTES = 20 * 1024;
178
184
  const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
179
185
  const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
180
186
  const WEBUI_SUBAGENT_RUN_LIMIT = 128;
@@ -281,7 +287,9 @@ const PATH_SUGGESTION_QUERY_LIMIT = 512;
281
287
  const PATH_SUGGESTION_SCAN_LIMIT = 5000;
282
288
  const PATH_SUGGESTION_MAX_OUTPUT_LENGTH = 300000;
283
289
  const PATH_SUGGESTION_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
284
- const RESTORE_TAB_LIMIT = 30;
290
+ const RESTORE_TAB_LIMIT = 256;
291
+ const UPDATE_HEALTH_GATE_MS = Math.max(90_000, Number.parseInt(process.env.PI_WEBUI_UPDATE_HEALTH_GATE_MS || "90000", 10) || 90_000);
292
+ const bootIdentity = randomUUID();
285
293
  const SESSION_SELECTOR_LIMIT = 200;
286
294
  const TREE_SELECTOR_TEXT_LIMIT = 260;
287
295
  const NETWORK_REBIND_DELAY_MS = 100;
@@ -704,12 +712,12 @@ async function fetchJsonWithTimeout(url, { timeoutMs = UPDATE_STATUS_TIMEOUT_MS,
704
712
  return response.json();
705
713
  }
706
714
 
707
- function installedPiRelease() {
708
- const version = String(piPackageJson.version || "").trim().replace(/^v/i, "");
709
- if (!parsePackageVersion(version)) throw makeHttpError(503, "The installed Pi version could not be determined");
710
- const tagName = `v${version}`;
715
+ function piRelease(version = piPackageJson.version) {
716
+ const cleanVersion = String(version || "").trim().replace(/^v/i, "");
717
+ if (!parsePackageVersion(cleanVersion)) throw makeHttpError(503, "The Pi release version could not be determined");
718
+ const tagName = `v${cleanVersion}`;
711
719
  return {
712
- version,
720
+ version: cleanVersion,
713
721
  tagName,
714
722
  apiUrl: `${PI_RELEASES_API_BASE_URL}/${encodeURIComponent(tagName)}`,
715
723
  pageUrl: `${PI_RELEASES_PAGE_BASE_URL}/${encodeURIComponent(tagName)}`,
@@ -718,8 +726,14 @@ function installedPiRelease() {
718
726
 
719
727
  let piReleaseNotesCache = null;
720
728
 
721
- async function installedPiReleaseNotes() {
722
- const release = installedPiRelease();
729
+ async function piReleaseNotes() {
730
+ const cachedUpdateStatus = updateStatusCache && Date.now() - updateStatusCacheAt < UPDATE_STATUS_CACHE_MS
731
+ ? updateStatusCache.pi
732
+ : null;
733
+ const piStatus = cachedUpdateStatus || await checkLatestPiReleaseStatus();
734
+ const currentVersion = String(piStatus?.currentVersion || piPackageJson.version || "").trim().replace(/^v/i, "");
735
+ const latestVersion = String(piStatus?.latestVersion || "").trim().replace(/^v/i, "");
736
+ const release = piRelease(piStatus?.updateAvailable && parsePackageVersion(latestVersion) ? latestVersion : currentVersion);
723
737
  if (piReleaseNotesCache?.tagName === release.tagName) return piReleaseNotesCache;
724
738
  if (process.env.PI_OFFLINE) throw makeHttpError(503, "Pi release notes are unavailable while PI_OFFLINE is set");
725
739
 
@@ -1143,7 +1157,7 @@ function formatBytes(bytes) {
1143
1157
  return `${value} B`;
1144
1158
  }
1145
1159
 
1146
- async function readJsonBody(req, { limitBytes = BODY_LIMIT_BYTES } = {}) {
1160
+ async function readJsonBody(req, { limitBytes = BODY_LIMIT_BYTES, emptyError } = {}) {
1147
1161
  const chunks = [];
1148
1162
  let size = 0;
1149
1163
  for await (const chunk of req) {
@@ -1151,9 +1165,15 @@ async function readJsonBody(req, { limitBytes = BODY_LIMIT_BYTES } = {}) {
1151
1165
  if (size > limitBytes) throw makeHttpError(413, `Request body too large (limit ${formatBytes(limitBytes)})`);
1152
1166
  chunks.push(chunk);
1153
1167
  }
1154
- if (chunks.length === 0) return {};
1168
+ if (chunks.length === 0) {
1169
+ if (emptyError) throw makeHttpError(400, emptyError);
1170
+ return {};
1171
+ }
1155
1172
  const text = Buffer.concat(chunks).toString("utf8");
1156
- if (!text.trim()) return {};
1173
+ if (!text.trim()) {
1174
+ if (emptyError) throw makeHttpError(400, emptyError);
1175
+ return {};
1176
+ }
1157
1177
  return JSON.parse(text);
1158
1178
  }
1159
1179
 
@@ -1309,7 +1329,7 @@ function sendRemoteAuthRequired(req, res, url) {
1309
1329
  // disconnects healthy Chromium EventSource streams as soon as a frame exceeds
1310
1330
  // roughly 16 KiB. Queue subsequent frames until "drain", with strict bounds so
1311
1331
  // a client that truly stops reading cannot grow server memory indefinitely.
1312
- const SSE_BACKPRESSURE_MAX_PENDING_BYTES = 512 * 1024;
1332
+ const SSE_BACKPRESSURE_MAX_PENDING_BYTES = 4 * 1024 * 1024;
1313
1333
  const SSE_BACKPRESSURE_MAX_PENDING_FRAMES = 256;
1314
1334
  const SSE_BACKPRESSURE_TIMEOUT_MS = 10_000;
1315
1335
 
@@ -1929,6 +1949,25 @@ function formatCommandForDisplay(command, args) {
1929
1949
  return [command, ...args].map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" ");
1930
1950
  }
1931
1951
 
1952
+ async function npmGlobalNodeModulesRoot() {
1953
+ const invocation = resolveNpmCommandInvocation(["root", "-g"]);
1954
+ const result = await runCommand(invocation.command, invocation.args, { timeoutMs: 10_000, maxOutputLength: 8_000 });
1955
+ if (result.exitCode !== 0 || result.timedOut || result.error) return null;
1956
+ return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
1957
+ }
1958
+
1959
+ async function bunGlobalNodeModulesRoots() {
1960
+ const available = await runCommand("bun", ["--version"], { timeoutMs: 10_000, maxOutputLength: 2_000 });
1961
+ if (available.exitCode !== 0 || available.timedOut || available.error) return [];
1962
+ const roots = new Set([path.join(homedir(), ".bun", "install", "global", "node_modules")]);
1963
+ const binResult = await runCommand("bun", ["pm", "bin", "-g"], { timeoutMs: 10_000, maxOutputLength: 8_000 });
1964
+ if (binResult.exitCode === 0 && !binResult.timedOut && !binResult.error) {
1965
+ const binDir = binResult.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
1966
+ if (binDir) roots.add(path.join(path.dirname(binDir), "install", "global", "node_modules"));
1967
+ }
1968
+ return [...roots];
1969
+ }
1970
+
1932
1971
  let optionalPackageNodeModulesRootsCache = null;
1933
1972
  async function optionalPackageNodeModulesRoots() {
1934
1973
  if (optionalPackageNodeModulesRootsCache) return optionalPackageNodeModulesRootsCache;
@@ -2554,9 +2593,25 @@ async function safetyGuardConfigModule() {
2554
2593
  new URL("../../pi-extension-safety-guard/src/config.mjs", import.meta.url).href,
2555
2594
  ];
2556
2595
  const failures = [];
2596
+ const requiredExports = [
2597
+ "SAFETY_GUARD_CATEGORIES",
2598
+ "SAFETY_GUARD_CONTEXT_LINES_MAX",
2599
+ "SAFETY_GUARD_CONTEXT_LINES_MIN",
2600
+ "SAFETY_GUARD_CONFIG_VERSION",
2601
+ "SAFETY_GUARD_THINKING_LEVELS",
2602
+ "assertSafetyGuardConfigPatch",
2603
+ "defaultSafetyGuardConfig",
2604
+ "mergeSafetyGuardConfig",
2605
+ "readSafetyGuardConfig",
2606
+ "safetyGuardConfigFile",
2607
+ "writeSafetyGuardConfig",
2608
+ ];
2557
2609
  for (const specifier of specifiers) {
2558
2610
  try {
2559
- return await import(specifier);
2611
+ const module = await import(specifier);
2612
+ const missing = requiredExports.filter((name) => module[name] === undefined);
2613
+ if (missing.length) throw new Error(`missing ${missing.join(", ")}`);
2614
+ return module;
2560
2615
  } catch (error) {
2561
2616
  failures.push(error instanceof Error ? error.message : String(error));
2562
2617
  }
@@ -2570,9 +2625,14 @@ async function safetyGuardConfigModule() {
2570
2625
  return safetyGuardConfigModulePromise;
2571
2626
  }
2572
2627
 
2573
- async function safetyGuardConfigData() {
2628
+ function safetyGuardModelKey(model) {
2629
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
2630
+ }
2631
+
2632
+ async function safetyGuardConfigData(tab, { config: suppliedConfig, models: suppliedModels } = {}) {
2574
2633
  const settingsModule = await safetyGuardConfigModule();
2575
- const config = settingsModule.readSafetyGuardConfig();
2634
+ const config = suppliedConfig || settingsModule.readSafetyGuardConfig();
2635
+ const models = suppliedModels || await availableGitWorkflowModels(tab);
2576
2636
  return {
2577
2637
  config,
2578
2638
  defaults: settingsModule.defaultSafetyGuardConfig(),
@@ -2581,12 +2641,18 @@ async function safetyGuardConfigData() {
2581
2641
  min: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MIN,
2582
2642
  max: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MAX,
2583
2643
  },
2644
+ models,
2645
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [
2646
+ safetyGuardModelKey(model),
2647
+ supportedGitWorkflowThinkingLevels(model),
2648
+ ])),
2649
+ thinkingLevels: [...settingsModule.SAFETY_GUARD_THINKING_LEVELS],
2584
2650
  version: settingsModule.SAFETY_GUARD_CONFIG_VERSION,
2585
2651
  path: settingsModule.safetyGuardConfigFile(),
2586
2652
  };
2587
2653
  }
2588
2654
 
2589
- async function saveSafetyGuardConfigData(body = {}) {
2655
+ async function saveSafetyGuardConfigData(tab, body = {}) {
2590
2656
  const settingsModule = await safetyGuardConfigModule();
2591
2657
  const submitted = body.config && typeof body.config === "object" ? body.config : body;
2592
2658
  try {
@@ -2595,12 +2661,27 @@ async function saveSafetyGuardConfigData(body = {}) {
2595
2661
  throw makeHttpError(400, error instanceof Error ? error.message : String(error));
2596
2662
  }
2597
2663
 
2664
+ const next = settingsModule.mergeSafetyGuardConfig(settingsModule.readSafetyGuardConfig(), submitted);
2665
+ let models;
2666
+ if (next.autoReview.enabled) {
2667
+ models = await availableGitWorkflowModels(tab);
2668
+ const provider = next.autoReview.model.provider;
2669
+ const modelId = next.autoReview.model.modelId;
2670
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
2671
+ if (!model) throw makeHttpError(400, `Selected auto-review model is not currently available: ${provider || "unset"}/${modelId || "unset"}`);
2672
+ const supportedLevels = supportedGitWorkflowThinkingLevels(model);
2673
+ if (!supportedLevels.includes(next.autoReview.model.thinkingLevel)) {
2674
+ throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.autoReview.model.thinkingLevel}`);
2675
+ }
2676
+ }
2677
+
2678
+ let config;
2598
2679
  try {
2599
- const config = settingsModule.writeSafetyGuardConfig(submitted);
2600
- return { ...(await safetyGuardConfigData()), config };
2680
+ config = settingsModule.writeSafetyGuardConfig(submitted);
2601
2681
  } catch (error) {
2602
2682
  throw makeHttpError(500, error instanceof Error ? error.message : String(error));
2603
2683
  }
2684
+ return safetyGuardConfigData(tab, { config, models });
2604
2685
  }
2605
2686
 
2606
2687
  function requireSubagentLaunchSlotScope(value) {
@@ -2709,8 +2790,8 @@ function gitWorkflowModelKey(model) {
2709
2790
  }
2710
2791
 
2711
2792
  async function availableGitWorkflowModels(tab) {
2712
- const response = await safeRpcData(tab, { type: "get_available_models" });
2713
- if (!response.ok) throw makeHttpError(400, response.error || "Failed to load available models");
2793
+ const response = await safeRpcResponse(tab, { type: "get_available_models" });
2794
+ if (response.success === false) throw makeHttpError(400, response.error || "Failed to load available models");
2714
2795
  return (Array.isArray(response.data?.models) ? response.data.models : [])
2715
2796
  .filter((model) => model?.provider && model?.id)
2716
2797
  .sort((left, right) => gitWorkflowModelKey(left).localeCompare(gitWorkflowModelKey(right)));
@@ -3302,7 +3383,12 @@ function appRunnerCandidate({ id, label, kind, command, args = [], projectFile =
3302
3383
 
3303
3384
  function addAppRunner(runners, runner) {
3304
3385
  if (!runner?.id || !runner.command) return;
3305
- if (runners.some((item) => item.id === runner.id || item.displayCommand === runner.displayCommand)) return;
3386
+ if (runners.some((item) => item.id === runner.id)) return;
3387
+ const duplicateIndex = runners.findIndex((item) => item.displayCommand === runner.displayCommand);
3388
+ if (duplicateIndex >= 0) {
3389
+ if (runner.custom && !runners[duplicateIndex].custom) runners.splice(duplicateIndex, 1, runner);
3390
+ return;
3391
+ }
3306
3392
  runners.push(runner);
3307
3393
  }
3308
3394
 
@@ -8984,6 +9070,12 @@ function commandFromGet(pathname) {
8984
9070
  }
8985
9071
  }
8986
9072
 
9073
+ const candidateProbeRequested = process.argv.length === 3 && process.argv[2] === "--candidate-probe";
9074
+ if (candidateProbeRequested) {
9075
+ process.stdout.write(`${JSON.stringify({ ok: true, packageName: WEBUI_PACKAGE, version: packageJson.version, piVersion: piPackageJson.version, serverEntry: fileURLToPath(import.meta.url) })}\n`);
9076
+ process.exit(0);
9077
+ }
9078
+
8987
9079
  let options;
8988
9080
  try {
8989
9081
  options = parseArgs(process.argv.slice(2));
@@ -9040,7 +9132,7 @@ if (Number.isFinite(startupDelayMs) && startupDelayMs > 0) {
9040
9132
  await delay(Math.min(startupDelayMs, 10_000));
9041
9133
  }
9042
9134
 
9043
- const restoreTabs = readRestoreTabsFromEnv();
9135
+ const restoreTabs = await readRestoreTabsFromEnv();
9044
9136
  const supervisorAttachCursor = readSupervisorCursorFromEnv();
9045
9137
 
9046
9138
  function normalizedRestoreString(value, maxLength) {
@@ -9068,18 +9160,17 @@ function normalizeRestoreTabDescriptor(item, seenIds) {
9068
9160
  return descriptor;
9069
9161
  }
9070
9162
 
9071
- function readRestoreTabsFromEnv() {
9072
- const raw = process.env.PI_WEBUI_RESTORE_TABS;
9163
+ async function readRestoreTabsFromEnv() {
9164
+ const restoreFile = process.env.PI_WEBUI_RESTORE_FILE;
9165
+ delete process.env.PI_WEBUI_RESTORE_FILE;
9073
9166
  delete process.env.PI_WEBUI_RESTORE_TABS;
9074
- if (!raw) return [];
9075
-
9167
+ if (!restoreFile) return [];
9076
9168
  try {
9077
- const parsed = JSON.parse(raw);
9078
- const items = Array.isArray(parsed) ? parsed : [];
9169
+ const items = await readRestoreFileOnce(restoreFile, agentDir);
9079
9170
  const seenIds = new Set();
9080
9171
  return items.map((item) => normalizeRestoreTabDescriptor(item, seenIds)).filter(Boolean).slice(0, RESTORE_TAB_LIMIT);
9081
9172
  } catch (error) {
9082
- console.warn(`failed to parse PI_WEBUI_RESTORE_TABS: ${sanitizeError(error)}`);
9173
+ console.warn(`failed to read private restore descriptor: ${sanitizeError(error)}`);
9083
9174
  return [];
9084
9175
  }
9085
9176
  }
@@ -9304,19 +9395,43 @@ function resolveSelectedPiCommand(piArgs) {
9304
9395
  };
9305
9396
  }
9306
9397
 
9307
- async function resolvePiCommand(piArgs) {
9308
- if (options.piBinExplicit) return resolveSelectedPiCommand(piArgs);
9309
-
9310
- const bundledCli = await resolvedPiCliScript();
9311
- if (bundledCli) {
9312
- return {
9313
- command: process.execPath,
9314
- args: [bundledCli, ...piArgs],
9315
- displayCommand: `${process.execPath} ${bundledCli} ${piArgs.join(" ")}`,
9316
- };
9398
+ let canonicalPiRuntimePromise = null;
9399
+ let canonicalPiRuntimeProbeVersion = null;
9400
+
9401
+ async function canonicalPiRuntimeIdentity({ force = false, probeVersion = true } = {}) {
9402
+ if (force || canonicalPiRuntimeProbeVersion !== probeVersion) canonicalPiRuntimePromise = null;
9403
+ if (!canonicalPiRuntimePromise) {
9404
+ canonicalPiRuntimeProbeVersion = probeVersion;
9405
+ canonicalPiRuntimePromise = (async () => resolveCanonicalPiRuntime({
9406
+ explicitCommand: options.piBinExplicit ? options.piBin : "",
9407
+ bundledCli: await resolvedPiCliScript(),
9408
+ pathCommand: options.piBin || "pi",
9409
+ runCommand,
9410
+ timeoutMs: 10_000,
9411
+ probeVersion,
9412
+ }))().catch((error) => {
9413
+ canonicalPiRuntimePromise = null;
9414
+ throw error;
9415
+ });
9317
9416
  }
9417
+ return canonicalPiRuntimePromise;
9418
+ }
9318
9419
 
9319
- return resolveSelectedPiCommand(piArgs);
9420
+ function invalidateCanonicalPiRuntime() {
9421
+ canonicalPiRuntimePromise = null;
9422
+ canonicalPiRuntimeProbeVersion = null;
9423
+ }
9424
+
9425
+ async function resolvePiCommand(piArgs) {
9426
+ const resolution = await canonicalPiRuntimeIdentity({ probeVersion: false });
9427
+ const active = resolution.active;
9428
+ if (!active) throw new Error(resolution.refusal?.message || "No supported active Pi runtime could be verified.");
9429
+ const args = [...(active.invocation?.args || []), ...piArgs];
9430
+ return {
9431
+ command: active.invocation.command,
9432
+ args,
9433
+ displayCommand: formatCommandForDisplay(active.invocation.command, args),
9434
+ };
9320
9435
  }
9321
9436
 
9322
9437
  const tabs = new Map();
@@ -11256,17 +11371,19 @@ async function loadWebuiWorkspace(id, body = {}) {
11256
11371
  }
11257
11372
  }
11258
11373
 
11259
- function spawnRestartServer(restorableTabs, supervisorCursor) {
11374
+ async function spawnRestartServer(restorableTabs, supervisorCursor) {
11375
+ const restore = await createRestoreFile(agentDir, restorableTabs || []);
11260
11376
  const env = {
11261
11377
  ...process.env,
11262
- PI_WEBUI_RESTORE_TABS: JSON.stringify(restorableTabs || []),
11378
+ PI_WEBUI_RESTORE_FILE: restore.file,
11263
11379
  PI_WEBUI_START_DELAY_MS: "1200",
11264
11380
  };
11265
11381
  if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
11266
11382
  else delete env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
11267
11383
  if (webuiDevServer) env.PI_WEBUI_DEV = "1";
11268
11384
  else delete env.PI_WEBUI_DEV;
11269
- const child = spawn(process.execPath, process.argv.slice(1), {
11385
+ const launcher = path.join(packageRoot, "bin", "pi-webui-launcher.mjs");
11386
+ const child = spawn(process.execPath, [launcher, ...process.argv.slice(2)], {
11270
11387
  cwd: process.cwd(),
11271
11388
  env,
11272
11389
  detached: true,
@@ -11282,6 +11399,279 @@ let updateStatusCacheAt = 0;
11282
11399
  let piUpdateInProgress = false;
11283
11400
  const componentUpdateState = new ComponentUpdateState();
11284
11401
 
11402
+ async function canonicalUpdateIdentities({ forcePi = false } = {}) {
11403
+ const pi = await canonicalPiRuntimeIdentity({ force: forcePi });
11404
+ const webui = resolveWebuiRuntimeIdentity({
11405
+ packageRoot,
11406
+ packageName: WEBUI_PACKAGE,
11407
+ version: packageJson.version,
11408
+ owner: { manager: webuiDevServer ? "source" : "managed-bootstrap" },
11409
+ });
11410
+ return { pi, webui };
11411
+ }
11412
+
11413
+ function updateOwnerForTarget(target, identities) {
11414
+ if (target === "webui") {
11415
+ const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
11416
+ return sourceCheckout
11417
+ ? { manager: "unknown", packageRoot, ownerRoot: packageRoot, sourceCheckout: true }
11418
+ : { manager: "npm", packageRoot, ownerRoot: nodeModulesParentForPackageRoot(packageRoot), topLevel: true };
11419
+ }
11420
+ const active = identities.pi.active;
11421
+ const piRoot = active?.packageRoot || "";
11422
+ const installRoot = piRoot ? nodeModulesParentForPackageRoot(piRoot) : "";
11423
+ const bundled = piRoot && exactUpdatePathInside(path.join(packageRoot, "node_modules"), piRoot);
11424
+ if (bundled && webuiDevServer) return { manager: "unknown", packageRoot: piRoot, ownerRoot: packageRoot, sourceCheckout: true };
11425
+ if (bundled) return { manager: "npm", packageRoot: piRoot, ownerRoot: installRoot, topLevel: true };
11426
+ if ((active?.source === "explicit" || active?.source === "path") && piRoot) {
11427
+ return { manager: "pi", packageRoot: piRoot, ownerRoot: piRoot, topLevel: true };
11428
+ }
11429
+ return { manager: "unknown", packageRoot: piRoot, ownerRoot: "", topLevel: true };
11430
+ }
11431
+
11432
+ async function createServerOwnedUpdatePlan(targets) {
11433
+ if (privilegedUpdateInProgress()) throw makeHttpError(409, "Another privileged update is already running.");
11434
+ const identities = await canonicalUpdateIdentities({ forcePi: true });
11435
+ const transactionId = randomUUID();
11436
+ const statePaths = managedRuntimePaths(agentDir);
11437
+ const status = await getUpdateStatus({ force: true });
11438
+ for (const target of targets) {
11439
+ if (!status[target]?.checked || !status[target]?.latestVersion) throw makeHttpError(409, `${target} exact target metadata is unavailable.`);
11440
+ }
11441
+ const piRoot = identities.pi.active?.packageRoot || "";
11442
+ const bundledPi = Boolean(piRoot && exactUpdatePathInside(path.join(packageRoot, "node_modules"), piRoot));
11443
+ const requested = new Set(targets);
11444
+ const desiredPiVersion = requested.has("pi") ? status.pi.latestVersion : identities.pi.active?.version;
11445
+ const desiredWebuiVersion = requested.has("webui") ? status.webui.latestVersion : identities.webui.version;
11446
+ const separatePathPi = identities.pi.path?.canonicalId && identities.pi.path.canonicalId !== identities.pi.active?.canonicalId
11447
+ ? identities.pi.path
11448
+ : null;
11449
+ const managedRuntimeRoot = path.join(statePaths.runtimesDir, `txn-${transactionId}`);
11450
+ const candidates = [];
11451
+ for (const target of targets) {
11452
+ const identity = target === "pi" ? identities.pi.active : identities.webui;
11453
+ if (!identity) throw makeHttpError(409, identities.pi.refusal?.message || `The ${target} runtime identity could not be verified.`);
11454
+ const managedRuntime = target === "webui" || (target === "pi" && bundledPi);
11455
+ candidates.push({
11456
+ id: target,
11457
+ kind: target,
11458
+ packageName: target === "pi" ? PI_CODING_AGENT_PACKAGE : WEBUI_PACKAGE,
11459
+ currentVersion: identity.version,
11460
+ identityId: identity.canonicalId,
11461
+ requested: "latest",
11462
+ registry: NPM_REGISTRY_URL,
11463
+ strategy: managedRuntime ? "managed-side-by-side" : "delegate-exact-pi",
11464
+ owner: updateOwnerForTarget(target, identities),
11465
+ exactTargetVersion: status[target].latestVersion,
11466
+ managedRuntime,
11467
+ runtimeRoot: managedRuntime ? managedRuntimeRoot : "",
11468
+ commandForVersion: async (version, registry) => {
11469
+ if (!managedRuntime) {
11470
+ const invocation = identity.invocation;
11471
+ if (!invocation?.command) throw new Error("The exact active Pi executable cannot own its update.");
11472
+ return { command: invocation.command, args: [...(invocation.args || []), "update", "--self"] };
11473
+ }
11474
+ const piVersion = target === "pi" ? version : desiredPiVersion;
11475
+ const webuiVersion = target === "webui" ? version : desiredWebuiVersion;
11476
+ const npm = resolvedNpmCommandForExactUpdate([
11477
+ "install", "--prefix", managedRuntimeRoot, "--ignore-scripts", "--no-save", "--package-lock=false", "--registry", registry,
11478
+ `${WEBUI_PACKAGE}@${webuiVersion}`,
11479
+ `${PI_CODING_AGENT_PACKAGE}@${piVersion}`,
11480
+ ]);
11481
+ return { command: npm.command, args: npm.args };
11482
+ },
11483
+ });
11484
+ }
11485
+
11486
+ if (requested.has("pi") && requested.has("webui") && identities.pi.active) {
11487
+ const optionalStatuses = await optionalFeaturePackageStatuses(options.cwd);
11488
+ for (const feature of optionalStatuses.features) {
11489
+ if (!feature.configured || !feature.ready || !feature.installedVersion || !feature.installedRoot) continue;
11490
+ const latest = await checkLatestNpmPackageStatus(feature.packageName, feature.installedVersion);
11491
+ if (!latest.checked || !latest.updateAvailable || !latest.latestVersion) continue;
11492
+ const invocation = identities.pi.active.invocation;
11493
+ candidates.push({
11494
+ id: `optional:${feature.featureId}`,
11495
+ kind: "optional",
11496
+ packageName: feature.packageName,
11497
+ currentVersion: feature.installedVersion,
11498
+ identityId: identities.pi.active.canonicalId,
11499
+ requested: "latest",
11500
+ registry: NPM_REGISTRY_URL,
11501
+ strategy: "pi-owned-optional",
11502
+ owner: {
11503
+ manager: "pi",
11504
+ packageRoot: feature.installedRoot,
11505
+ ownerRoot: configuredAgentNpmRoot(),
11506
+ topLevel: true,
11507
+ optional: true,
11508
+ piOwned: true,
11509
+ },
11510
+ exactTargetVersion: latest.latestVersion,
11511
+ optionalFeature: true,
11512
+ featureId: feature.featureId,
11513
+ commandForVersion: async (version) => ({
11514
+ command: invocation.command,
11515
+ args: [...(invocation.args || []), "install", `npm:${feature.packageName}@${version}`],
11516
+ }),
11517
+ });
11518
+ }
11519
+ }
11520
+
11521
+ const plan = await createUpdatePlan({
11522
+ transactionId,
11523
+ registry: NPM_REGISTRY_URL,
11524
+ identities: [identities.pi.active, separatePathPi, identities.webui].filter(Boolean),
11525
+ candidates,
11526
+ resolveExactTarget: async ({ id, registry }) => {
11527
+ const candidate = candidates.find((item) => item.id === id);
11528
+ const targetVersion = candidate?.exactTargetVersion;
11529
+ if (!candidate || !targetVersion) throw new Error(`${id} exact target metadata is unavailable.`);
11530
+ let metadata = { delegatedExecutable: true };
11531
+ if (candidate.managedRuntime) {
11532
+ metadata = {
11533
+ managedRuntime: true,
11534
+ runtimeRoot: candidate.runtimeRoot,
11535
+ webuiVersion: id === "webui" ? targetVersion : desiredWebuiVersion,
11536
+ piVersion: id === "pi" ? targetVersion : desiredPiVersion,
11537
+ };
11538
+ } else if (candidate.optionalFeature) {
11539
+ metadata = { optionalFeature: true, featureId: candidate.featureId };
11540
+ }
11541
+ return { version: targetVersion, registry, metadata };
11542
+ },
11543
+ });
11544
+ await createUpdateJournal(agentDir, plan);
11545
+ return plan;
11546
+ }
11547
+
11548
+ async function activeIdentityForTarget(target) {
11549
+ const usesPiIdentity = target.id === "pi" || target.metadata?.optionalFeature === true;
11550
+ const identities = await canonicalUpdateIdentities({ forcePi: usesPiIdentity });
11551
+ return usesPiIdentity ? identities.pi.active : identities.webui;
11552
+ }
11553
+
11554
+ async function launchManagedActivation(journal, target, lock, outcome) {
11555
+ const runtimeRoot = path.resolve(target.metadata.runtimeRoot);
11556
+ const serverEntry = path.join(runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
11557
+ const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
11558
+ if (!probe.ok) throw new Error(probe.error || "Managed Web UI candidate probe failed.");
11559
+ if (target.metadata.webuiVersion !== packageJson.version) {
11560
+ const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-activation" });
11561
+ const featureIds = snapshot.features
11562
+ .filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
11563
+ .map(({ featureId }) => featureId);
11564
+ await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
11565
+ }
11566
+ const restore = await createRestoreFile(agentDir, await restorableTabsForRestart());
11567
+ const supervisorCursor = await prepareRpcSupervisorHandoff();
11568
+ const helper = path.join(packageRoot, "bin", "pi-webui-update-supervisor.mjs");
11569
+ const host = formatUrlHost(currentHost);
11570
+ const helperArgs = [
11571
+ helper,
11572
+ "--agent-dir", agentDir,
11573
+ "--runtime-root", runtimeRoot,
11574
+ "--server-entry", serverEntry,
11575
+ "--version", target.metadata.webuiVersion,
11576
+ "--pi-version", target.metadata.piVersion,
11577
+ "--outcome", outcome,
11578
+ "--transaction", journal.transactionId,
11579
+ "--url", `http://${host}:${options.port}/`,
11580
+ "--old-boot", bootIdentity,
11581
+ "--timeout-ms", String(UPDATE_HEALTH_GATE_MS),
11582
+ "--server-args", Buffer.from(JSON.stringify(process.argv.slice(2))).toString("base64url"),
11583
+ ];
11584
+ const env = { ...process.env, PI_WEBUI_RESTORE_FILE: restore.file, PI_WEBUI_START_DELAY_MS: "300", PI_WEBUI_UPDATE_LOCK_TOKEN: lock.token };
11585
+ if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
11586
+ const child = spawn(process.execPath, helperArgs, { cwd: process.cwd(), env, detached: true, stdio: "ignore", windowsHide: true });
11587
+ await new Promise((resolve, reject) => {
11588
+ child.once("spawn", resolve);
11589
+ child.once("error", reject);
11590
+ });
11591
+ await transferInstallLock(lock, child.pid);
11592
+ child.unref();
11593
+ return { pid: child.pid, runtimeRoot, serverEntry };
11594
+ }
11595
+
11596
+ async function applyServerOwnedUpdate(transactionId, planDigest) {
11597
+ if (privilegedUpdateInProgress()) throw makeHttpError(409, "Another privileged update is already running.");
11598
+ const journal = await readUpdateJournal(agentDir, transactionId);
11599
+ if (!journal) throw makeHttpError(404, "Update transaction was not found.");
11600
+ assertUpdatePlanDigest(journal.plan, planDigest);
11601
+ if (journal.state !== "planned") throw makeHttpError(409, `Update transaction is already ${journal.state}.`);
11602
+ piUpdateInProgress = true;
11603
+ let lock = null;
11604
+ let lockTransferred = false;
11605
+ let state = "planned";
11606
+ try {
11607
+ lock = await acquireInstallLock(agentDir);
11608
+ await transitionUpdateJournal(agentDir, transactionId, "applying");
11609
+ state = "applying";
11610
+ let installedManagedRuntime = "";
11611
+ const result = await executePlanTargets(journal.plan, {
11612
+ runner: async (command, args, { target }) => {
11613
+ if (target.metadata?.managedRuntime && installedManagedRuntime === target.metadata.runtimeRoot) {
11614
+ return { exitCode: 0, timedOut: false, error: "", stdout: "Managed runtime exact package set already staged by the preceding target.", stderr: "", skippedDuplicate: true };
11615
+ }
11616
+ const commandResult = await executeCommand(command, args, { cwd: target.metadata?.runtimeRoot || process.cwd(), timeoutMs: PACKAGE_UPDATE_TIMEOUT_MS, maxOutputLength: PACKAGE_UPDATE_OUTPUT_MAX_CHARS });
11617
+ if (target.metadata?.managedRuntime && commandResult.exitCode === 0 && !commandResult.timedOut && !commandResult.error) installedManagedRuntime = target.metadata.runtimeRoot;
11618
+ return commandResult;
11619
+ },
11620
+ beforeTarget: async (target) => {
11621
+ const active = await activeIdentityForTarget(target);
11622
+ assertPlanIdentity(target, active);
11623
+ if (target.metadata?.managedRuntime) {
11624
+ await mkdir(target.metadata.runtimeRoot, { recursive: true, mode: 0o700 });
11625
+ try {
11626
+ await writeFile(path.join(target.metadata.runtimeRoot, "package.json"), `${JSON.stringify({ private: true })}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
11627
+ } catch (error) {
11628
+ if (error?.code !== "EEXIST") throw error;
11629
+ }
11630
+ }
11631
+ },
11632
+ verifyTarget: async (target, command) => {
11633
+ if (target.metadata?.optionalFeature) {
11634
+ const [afterIdentity, afterStatus] = await Promise.all([
11635
+ activeIdentityForTarget(target),
11636
+ optionalFeaturePackageStatus(target.metadata.featureId, options.cwd),
11637
+ ]);
11638
+ return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity, beforeVersion: target.currentVersion, afterVersion: afterStatus.ready ? afterStatus.installedVersion : "", command });
11639
+ }
11640
+ if (target.metadata?.managedRuntime) {
11641
+ const serverEntry = path.join(target.metadata.runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
11642
+ const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
11643
+ const afterVersion = target.id === "pi" ? probe.data?.piVersion : probe.data?.version;
11644
+ return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: { canonicalId: target.identityId }, beforeVersion: target.currentVersion, afterVersion: probe.ok ? afterVersion : "", command });
11645
+ }
11646
+ const after = await activeIdentityForTarget(target);
11647
+ return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: after, beforeVersion: target.currentVersion, afterVersion: after?.version, command });
11648
+ },
11649
+ });
11650
+ await transitionUpdateJournal(agentDir, transactionId, "verifying", { outcome: result.outcome, receipts: result.receipts });
11651
+ state = "verifying";
11652
+ const managedTargets = journal.plan.targets.filter((target) => target.metadata?.managedRuntime);
11653
+ const managedTargetsVerified = managedTargets.length > 0 && managedTargets.every((target) => result.receipts.find((receipt) => receipt.targetId === target.id)?.status === "success");
11654
+ const activationTarget = managedTargetsVerified ? managedTargets[0] : null;
11655
+ if (activationTarget) {
11656
+ const activation = await launchManagedActivation(journal, activationTarget, lock, result.outcome);
11657
+ lockTransferred = true;
11658
+ return { transactionId, planDigest, state: "activating", outcome: result.outcome, receipts: result.receipts, activation };
11659
+ }
11660
+ const terminal = result.outcome === "success" ? "success" : result.outcome === "partial" ? "partial" : "failed";
11661
+ const completed = await transitionUpdateJournal(agentDir, transactionId, terminal, { outcome: result.outcome, receipts: result.receipts });
11662
+ return completed;
11663
+ } catch (error) {
11664
+ if (state === "applying" || state === "verifying") await transitionUpdateJournal(agentDir, transactionId, "failed", { error: sanitizeComponentUpdateError(error), outcome: "failed" }).catch(() => {});
11665
+ throw error;
11666
+ } finally {
11667
+ if (lock && !lockTransferred) await releaseInstallLock(lock);
11668
+ piUpdateInProgress = false;
11669
+ invalidateCanonicalPiRuntime();
11670
+ updateStatusCache = null;
11671
+ updateStatusCacheAt = 0;
11672
+ }
11673
+ }
11674
+
11285
11675
  function webuiComponentUpdateUnavailableReason() {
11286
11676
  if (webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules")) {
11287
11677
  return "Automatic Web UI update is unavailable from a source or development checkout.";
@@ -11322,8 +11712,17 @@ function basePackageUpdateStatus(packageName, currentVersion) {
11322
11712
  };
11323
11713
  }
11324
11714
 
11715
+ async function currentPiRuntimeVersion() {
11716
+ try {
11717
+ return (await canonicalUpdateIdentities({ forcePi: true })).pi.active?.version || "unknown";
11718
+ } catch {
11719
+ return "unknown";
11720
+ }
11721
+ }
11722
+
11325
11723
  async function checkLatestPiReleaseStatus() {
11326
- const status = basePackageUpdateStatus(PI_CODING_AGENT_PACKAGE, piPackageJson.version);
11724
+ const currentVersion = await currentPiRuntimeVersion();
11725
+ const status = basePackageUpdateStatus(PI_CODING_AGENT_PACKAGE, currentVersion);
11327
11726
  const skippedReason = updateChecksSkippedReason();
11328
11727
  if (skippedReason) {
11329
11728
  status.skipped = true;
@@ -11333,7 +11732,7 @@ async function checkLatestPiReleaseStatus() {
11333
11732
  try {
11334
11733
  const data = await fetchJsonWithTimeout(PI_LATEST_VERSION_URL, {
11335
11734
  headers: {
11336
- "User-Agent": `pi-webui/${packageJson.version} pi/${piPackageJson.version || "unknown"}`,
11735
+ "User-Agent": `pi-webui/${packageJson.version} pi/${currentVersion || "unknown"}`,
11337
11736
  accept: "application/json",
11338
11737
  },
11339
11738
  });
@@ -11401,464 +11800,28 @@ async function getUpdateStatus({ force = false } = {}) {
11401
11800
  checkedAt: new Date(now).toISOString(),
11402
11801
  updateAvailable,
11403
11802
  restartRequired: true,
11404
- command: piUpdateCommandText(),
11405
- allCommand: piUpdateCommandText({ all: true, supportsAll: true }),
11406
- allFallbackCommand: piUpdateCommandText({ all: true }),
11803
+ planEndpoint: "/api/update/plan",
11804
+ applyEndpoint: "/api/update/apply",
11407
11805
  webuiDev: webuiDevServer,
11408
11806
  pi: piStatus,
11409
11807
  webui: webuiStatus,
11410
11808
  packages: {
11411
11809
  checked: false,
11412
- note: "Update all checks whether the selected Pi executable supports pi update --all. If not, it falls back to pi update --self followed by pi update --extensions."
11810
+ note: "Automatic updates use only persisted exact-target plans. Unsupported or unproven owners are reported as refusals and never scanned or mutated."
11413
11811
  },
11414
11812
  };
11415
11813
  updateStatusCacheAt = now;
11416
11814
  return updateStatusCache;
11417
11815
  }
11418
11816
 
11419
- async function piUpdateCommandSupportsAll(command) {
11420
- const result = await runCommand(command.command, command.args || [], {
11421
- cwd: process.cwd(),
11422
- timeoutMs: 5000,
11423
- maxOutputLength: 20_000,
11424
- });
11425
- if (result.exitCode !== 0 || result.timedOut || result.error) return false;
11426
- return piUpdateHelpSupportsAll(`${result.stdout}\n${result.stderr}`);
11817
+ function resolvedNpmCommandForExactUpdate(args) {
11818
+ const invocation = resolveNpmCommandInvocation(args);
11819
+ return { command: invocation.command, args: invocation.args };
11427
11820
  }
11428
11821
 
11429
- async function resolvePiUpdateCommands({ all = false } = {}) {
11430
- let resolveCommand;
11431
- let labelPrefix = "";
11432
- let useBundledPi = false;
11433
-
11434
- if (options.piBinExplicit) {
11435
- resolveCommand = (args) => resolvePiCommand(args);
11436
- } else {
11437
- const selectedPi = resolveSelectedPiCommand(["--version"]);
11438
- const pathPi = await runCommand(selectedPi.command, selectedPi.args, { timeoutMs: 3000, maxOutputLength: 4000 });
11439
- if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
11440
- resolveCommand = async (args) => resolveSelectedPiCommand(args);
11441
- } else {
11442
- resolveCommand = (args) => resolvePiCommand(args);
11443
- labelPrefix = "bundled ";
11444
- useBundledPi = true;
11445
- }
11446
- }
11447
-
11448
- const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
11449
- const steps = piUpdateCommandSteps({ all, supportsAll });
11450
- return Promise.all(steps.map(async (step) => {
11451
- const command = await resolveCommand(step.args);
11452
- const selectedPiDirectory = useBundledPi || isNodeScriptCommand(options.piBin) ? "" : resolveCommandDirectory(options.piBin);
11453
- const piInstallDirectory = selectedPiDirectory || resolveCommandDirectory(command.command);
11454
- return {
11455
- ...command,
11456
- label: `${labelPrefix}${step.label}`,
11457
- timeoutMs: PI_UPDATE_TIMEOUT_MS,
11458
- maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
11459
- piInstallDirectory,
11460
- env: piInstallDirectory ? prependedPathEnvironment(piInstallDirectory) : undefined,
11461
- };
11462
- }));
11463
- }
11464
-
11465
- function packageNodeModulesPath(nodeModulesRoot, packageName) {
11466
- return path.join(nodeModulesRoot, ...String(packageName || "").split("/").filter(Boolean));
11467
- }
11468
-
11469
- function isWebuiOrPiPackageName(packageName) {
11470
- const name = String(packageName || "").trim();
11471
- if (OPTIONAL_FEATURE_PACKAGE_NAMES.has(name)) return false;
11472
- return UPDATE_PACKAGE_NAMES.includes(name)
11473
- || /^@firstpick\/pi(?:-|$)/.test(name)
11474
- || /^@earendil-works\/pi(?:-|$)/.test(name)
11475
- || /^@firstpick\/.*webui/i.test(name);
11476
- }
11477
-
11478
- function declaredWebuiPiPackageNames(manifest) {
11479
- const names = new Set();
11480
- for (const section of [manifest?.dependencies, manifest?.optionalDependencies, manifest?.devDependencies]) {
11481
- for (const packageName of Object.keys(section || {})) {
11482
- if (isWebuiOrPiPackageName(packageName)) names.add(packageName);
11483
- }
11484
- }
11485
- return [...names].sort();
11486
- }
11487
-
11488
- async function packagesPresentInNodeModulesRoot(nodeModulesRoot, packageNames = UPDATE_PACKAGE_NAMES) {
11489
- const found = new Set();
11490
- if (!nodeModulesRoot || !await directoryExists(nodeModulesRoot)) return [];
11491
- for (const packageName of packageNames) {
11492
- if (await directoryExists(packageNodeModulesPath(nodeModulesRoot, packageName))) found.add(packageName);
11493
- }
11494
-
11495
- let entries = [];
11496
- try {
11497
- entries = await readdir(nodeModulesRoot, { withFileTypes: true });
11498
- } catch {
11499
- return [...found].sort();
11500
- }
11501
-
11502
- for (const entry of entries) {
11503
- if (!entry.isDirectory()) continue;
11504
- if (entry.name.startsWith("@")) {
11505
- let scopedEntries = [];
11506
- try {
11507
- scopedEntries = await readdir(path.join(nodeModulesRoot, entry.name), { withFileTypes: true });
11508
- } catch {
11509
- continue;
11510
- }
11511
- for (const scopedEntry of scopedEntries) {
11512
- if (!scopedEntry.isDirectory()) continue;
11513
- const packageName = `${entry.name}/${scopedEntry.name}`;
11514
- if (isWebuiOrPiPackageName(packageName)) found.add(packageName);
11515
- }
11516
- continue;
11517
- }
11518
- if (isWebuiOrPiPackageName(entry.name)) found.add(entry.name);
11519
- }
11520
- return [...found].sort();
11521
- }
11522
-
11523
- async function packagesPresentInInstallPrefix(installRoot, packageNames = UPDATE_PACKAGE_NAMES) {
11524
- const found = new Set();
11525
- if (!installRoot || !await directoryExists(installRoot)) return [];
11526
- const manifest = await readJsonFileIfExists(path.join(installRoot, "package.json"));
11527
- for (const packageName of packageNames) {
11528
- if (declaredDependencySpec(manifest, packageName) !== undefined) found.add(packageName);
11529
- }
11530
- for (const packageName of declaredWebuiPiPackageNames(manifest)) found.add(packageName);
11531
- for (const packageName of await packagesPresentInNodeModulesRoot(path.join(installRoot, "node_modules"), packageNames)) {
11532
- found.add(packageName);
11533
- }
11534
- return [...found].sort();
11535
- }
11536
-
11537
- function packageInstallSpecs(packageNames) {
11538
- return packageNames.map((packageName) => `${packageName}@latest`);
11539
- }
11540
-
11541
- function resolvedNpmCommand(args, runtime = {}) {
11542
- const invocation = resolveNpmCommandInvocation(args, runtime);
11543
- return {
11544
- command: invocation.command,
11545
- args: invocation.args,
11546
- displayCommand: formatCommandForDisplay(invocation.displayCommand, invocation.displayArgs),
11547
- };
11548
- }
11549
-
11550
- function npmPrefixUpdateTask(label, installRoot, packageNames, npmRuntime = {}) {
11551
- if (!packageNames.length) return null;
11552
- const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)], npmRuntime);
11553
- return {
11554
- label,
11555
- command: npmCommand.command,
11556
- args: npmCommand.args,
11557
- displayCommand: npmCommand.displayCommand,
11558
- cwd: installRoot,
11559
- };
11560
- }
11561
-
11562
- async function currentWebuiPackageUpdateTask(npmRuntime = {}) {
11563
- const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
11564
- if (sourceCheckout) {
11565
- const manifest = await readJsonFileIfExists(path.join(packageRoot, "package.json"));
11566
- const packages = declaredWebuiPiPackageNames(manifest);
11567
- return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages, npmRuntime);
11568
- }
11569
-
11570
- const installRoot = nodeModulesParentForPackageRoot(packageRoot);
11571
- const packages = await packagesPresentInInstallPrefix(installRoot);
11572
- return npmPrefixUpdateTask("current Web UI install root", installRoot, packages, npmRuntime);
11573
- }
11574
-
11575
- async function agentPackageRootUpdateTask(npmRuntime = {}) {
11576
- const installRoot = configuredAgentNpmRoot();
11577
- const packages = await packagesPresentInInstallPrefix(installRoot);
11578
- return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages, npmRuntime);
11579
- }
11580
-
11581
- async function optionalFeatureInstallRootUpdateTask(npmRuntime = {}) {
11582
- const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
11583
- if (!configuredRoot) return null;
11584
- const installRoot = path.resolve(expandUserPath(configuredRoot));
11585
- const packages = await packagesPresentInInstallPrefix(installRoot);
11586
- return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages, npmRuntime);
11587
- }
11588
-
11589
- function activeProjectPackageRoots() {
11590
- const roots = new Set();
11591
- const add = (cwd) => {
11592
- if (!cwd) return;
11593
- roots.add(path.join(path.resolve(cwd), ".pi", "npm"));
11594
- };
11595
- add(options.cwd);
11596
- for (const tab of tabs.values()) add(tab.cwd);
11597
- for (const tab of closedRestorableTabs) add(tab.cwd);
11598
- return [...roots].sort();
11599
- }
11600
-
11601
- async function projectPackageRootUpdateTasks(npmRuntime = {}) {
11602
- const tasks = [];
11603
- for (const installRoot of activeProjectPackageRoots()) {
11604
- const packages = await packagesPresentInInstallPrefix(installRoot);
11605
- const task = npmPrefixUpdateTask(`project Pi package root (${displayPath(path.dirname(installRoot))})`, installRoot, packages, npmRuntime);
11606
- if (task) tasks.push(task);
11607
- }
11608
- return tasks;
11609
- }
11610
-
11611
- async function npmGlobalNodeModulesRoot(npmRuntime = {}) {
11612
- const npmCommand = resolvedNpmCommand(["root", "-g"], npmRuntime);
11613
- const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
11614
- if (result.exitCode !== 0 || result.timedOut || result.error) return null;
11615
- return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
11616
- }
11617
-
11618
- async function npmGlobalPackageRootUpdateTask(npmRuntime = {}) {
11619
- const nodeModulesRoot = await npmGlobalNodeModulesRoot(npmRuntime);
11620
- const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
11621
- if (!packages.length) return null;
11622
- const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)], npmRuntime);
11623
- return {
11624
- label: "global npm package root",
11625
- command: npmCommand.command,
11626
- args: npmCommand.args,
11627
- displayCommand: npmCommand.displayCommand,
11628
- cwd: nodeModulesRoot ? path.dirname(nodeModulesRoot) : process.cwd(),
11629
- };
11630
- }
11631
-
11632
- async function bunGlobalNodeModulesRoots() {
11633
- const available = await runCommand("bun", ["--version"], { timeoutMs: 3000, maxOutputLength: 2000 });
11634
- if (available.exitCode !== 0 || available.timedOut || available.error) return [];
11635
-
11636
- const roots = new Set([path.join(homedir(), ".bun", "install", "global", "node_modules")]);
11637
- const binResult = await runCommand("bun", ["pm", "bin", "-g"], { timeoutMs: 3000, maxOutputLength: 8000 });
11638
- if (binResult.exitCode === 0 && !binResult.timedOut && !binResult.error) {
11639
- const binDir = binResult.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
11640
- if (binDir) roots.add(path.join(path.dirname(binDir), "install", "global", "node_modules"));
11641
- }
11642
- return [...roots];
11643
- }
11644
-
11645
- async function bunGlobalPackageRootUpdateTask() {
11646
- const packages = new Set();
11647
- for (const nodeModulesRoot of await bunGlobalNodeModulesRoots()) {
11648
- for (const packageName of await packagesPresentInNodeModulesRoot(nodeModulesRoot)) packages.add(packageName);
11649
- }
11650
- if (!packages.size) return null;
11651
- return {
11652
- label: "global Bun package root",
11653
- command: "bun",
11654
- args: ["install", "-g", "--ignore-scripts", "--minimum-release-age=0", ...packageInstallSpecs([...packages])],
11655
- cwd: homedir(),
11656
- };
11657
- }
11658
-
11659
- async function currentWebuiComponentUpdateTask(npmRuntime = {}) {
11660
- const unavailableReason = webuiComponentUpdateUnavailableReason();
11661
- if (unavailableReason) throw makeHttpError(409, unavailableReason);
11662
-
11663
- const normalizedPackageRoot = path.resolve(packageRoot);
11664
- for (const nodeModulesRoot of await bunGlobalNodeModulesRoots()) {
11665
- if (path.resolve(packageNodeModulesPath(nodeModulesRoot, WEBUI_PACKAGE)) !== normalizedPackageRoot) continue;
11666
- return {
11667
- label: "global Bun Web UI package",
11668
- command: "bun",
11669
- args: ["install", "-g", "--ignore-scripts", "--minimum-release-age=0", `${WEBUI_PACKAGE}@latest`],
11670
- cwd: homedir(),
11671
- };
11672
- }
11673
-
11674
- const installRoot = nodeModulesParentForPackageRoot(packageRoot);
11675
- return npmPrefixUpdateTask("current Web UI package", installRoot, [WEBUI_PACKAGE], npmRuntime);
11676
- }
11677
-
11678
- async function resolveComponentUpdateTasks(target) {
11679
- if (target === "pi") return resolvePiUpdateCommands({ all: false });
11680
- if (target === "webui") {
11681
- let npmRuntime = {};
11682
- try {
11683
- const piTasks = await resolvePiUpdateCommands({ all: false });
11684
- npmRuntime = {
11685
- preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
11686
- };
11687
- } catch {
11688
- recordEvent({ type: "webui_component_update_npm_resolution_fallback", target });
11689
- }
11690
- return [await currentWebuiComponentUpdateTask(npmRuntime)];
11691
- }
11692
- throw makeHttpError(400, "Unsupported component update target.");
11693
- }
11694
-
11695
- function updateTaskDisplay(task) {
11696
- return task.displayCommand || formatCommandForDisplay(task.command, task.args || []);
11697
- }
11698
-
11699
- function uniqueUpdateTasks(tasks) {
11700
- const unique = [];
11701
- const seen = new Set();
11702
- for (const task of tasks.filter(Boolean)) {
11703
- const key = [task.command, JSON.stringify(task.args || []), task.cwd || ""].join("\u0000");
11704
- if (seen.has(key)) continue;
11705
- seen.add(key);
11706
- unique.push(task);
11707
- }
11708
- return unique;
11709
- }
11710
-
11711
- async function resolveUpdateTasks({ all = false } = {}) {
11712
- const piTasks = await resolvePiUpdateCommands({ all });
11713
- if (!all) return uniqueUpdateTasks(piTasks);
11714
-
11715
- const npmRuntime = {
11716
- preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
11717
- };
11718
- const [
11719
- currentWebuiTask,
11720
- agentTask,
11721
- optionalFeatureTask,
11722
- projectTasks,
11723
- globalNpmTask,
11724
- globalBunTask,
11725
- ] = await Promise.all([
11726
- currentWebuiPackageUpdateTask(npmRuntime),
11727
- agentPackageRootUpdateTask(npmRuntime),
11728
- optionalFeatureInstallRootUpdateTask(npmRuntime),
11729
- projectPackageRootUpdateTasks(npmRuntime),
11730
- npmGlobalPackageRootUpdateTask(npmRuntime),
11731
- bunGlobalPackageRootUpdateTask(),
11732
- ]);
11733
-
11734
- return uniqueUpdateTasks([
11735
- ...piTasks,
11736
- currentWebuiTask,
11737
- agentTask,
11738
- optionalFeatureTask,
11739
- ...projectTasks,
11740
- globalNpmTask,
11741
- globalBunTask,
11742
- ]);
11743
- }
11744
-
11745
- function updateFailureDetails(result) {
11746
- return [result.error, result.timedOut ? "timed out" : undefined, result.stderr?.trim(), result.stdout?.trim()].filter(Boolean).join("\n");
11747
- }
11748
-
11749
- async function runUpdateTask(task) {
11750
- const command = updateTaskDisplay(task);
11751
- recordEvent({ type: "webui_update_step_started", command });
11752
- const result = await runCommand(task.command, task.args || [], {
11753
- cwd: task.cwd || process.cwd(),
11754
- timeoutMs: task.timeoutMs || PACKAGE_UPDATE_TIMEOUT_MS,
11755
- maxOutputLength: task.maxOutputLength || PACKAGE_UPDATE_OUTPUT_MAX_CHARS,
11756
- env: task.env,
11757
- });
11758
- const ok = result.exitCode === 0 && !result.timedOut && !result.error;
11759
- if (!ok) {
11760
- const details = updateFailureDetails(result);
11761
- recordEvent({ type: "webui_update_step_failed", command, error: truncateStatusText(details || `exit code ${result.exitCode ?? "unknown"}`) });
11762
- throw makeHttpError(500, truncateLongText(`Update step failed (${task.label || "package update"}): ${command}${details ? `\n${details}` : ""}`));
11763
- }
11764
- recordEvent({ type: "webui_update_step_completed", command });
11765
- return {
11766
- label: task.label || "package update",
11767
- command,
11768
- stdout: result.stdout,
11769
- stderr: result.stderr,
11770
- };
11771
- }
11772
-
11773
- function combinedUpdateOutput(results, field) {
11774
- return results
11775
- .map((result) => {
11776
- const output = String(result?.[field] || "").trim();
11777
- return output ? `# ${result.label}\n${output}` : "";
11778
- })
11779
- .filter(Boolean)
11780
- .join("\n\n");
11781
- }
11782
-
11783
- function componentUpdateSuccessMessage(target) {
11784
- if (target === "pi") return "Pi update completed. New or reloaded Pi sessions use the update.";
11785
- return "Web UI update completed. Restart the Web UI to use the update.";
11786
- }
11787
-
11788
- async function persistOptionalFeaturePendingUpgrade() {
11789
- optionalFeatureAuditCoordinator.assertIdle();
11790
- const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-update" });
11791
- const featureIds = snapshot.features
11792
- .filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
11793
- .map(({ featureId }) => featureId);
11794
- await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
11795
- }
11796
-
11797
- async function runComponentUpdate(target) {
11798
- try {
11799
- if (target === "webui") await persistOptionalFeaturePendingUpgrade();
11800
- const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
11801
- if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
11802
- const command = updateTasks.map(updateTaskDisplay).join(" && ");
11803
- recordEvent({ type: "webui_component_update_started", target, command });
11804
- for (const task of updateTasks) await runUpdateTask(task);
11805
- updateStatusCache = null;
11806
- updateStatusCacheAt = 0;
11807
- componentUpdateState.succeed(target, componentUpdateSuccessMessage(target));
11808
- recordEvent({ type: "webui_component_update_completed", target, command });
11809
- } catch (error) {
11810
- updateStatusCache = null;
11811
- updateStatusCacheAt = 0;
11812
- componentUpdateState.fail(target, error);
11813
- recordEvent({ type: "webui_component_update_failed", target, error: componentUpdateState.get(target).error });
11814
- }
11815
- }
11816
-
11817
- function startComponentUpdate(target) {
11818
- if (piUpdateInProgress || componentUpdateState.hasRunning()) throw makeHttpError(409, "Another privileged update is already running.");
11819
- const unavailableReason = target === "webui" ? webuiComponentUpdateUnavailableReason() : "";
11820
- if (unavailableReason) throw makeHttpError(409, unavailableReason);
11821
- componentUpdateState.begin(target);
11822
- recordEvent({ type: "webui_component_update_accepted", target });
11823
- setImmediate(() => { void runComponentUpdate(target); });
11824
- return componentUpdateState.get(target);
11825
- }
11826
-
11827
- async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
11828
- if (piUpdateInProgress) throw makeHttpError(409, "A Pi update is already running.");
11829
- if (componentUpdateState.hasRunning()) throw makeHttpError(409, "A component update is already running.");
11830
- piUpdateInProgress = true;
11831
- let restartPrepared = false;
11832
- try {
11833
- if (all) await persistOptionalFeaturePendingUpgrade();
11834
- const restorableTabs = await restorableTabsForRestart();
11835
- const updateTasks = await resolveUpdateTasks({ all });
11836
- if (!updateTasks.length) throw makeHttpError(500, "No Pi update command could be resolved.");
11837
- const command = updateTasks.map(updateTaskDisplay).join(" && ");
11838
- const updateLabel = all ? "Pi and package updates" : "Pi update";
11839
- recordEvent({ type: "webui_update_started", command, updateAll: all, restorableTabCount: restorableTabs.length });
11840
- const results = [];
11841
- for (const task of updateTasks) results.push(await runUpdateTask(task));
11842
-
11843
- updateStatusCache = null;
11844
- updateStatusCacheAt = 0;
11845
- const supervisorCursor = await prepareRpcSupervisorHandoff();
11846
- const child = spawnRestartServer(restorableTabs, supervisorCursor);
11847
- restartPrepared = true;
11848
- recordEvent({ type: "webui_update_restarting", command, updateAll: all, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
11849
- return {
11850
- message: `${updateLabel} completed. Pi Web UI is restarting.`,
11851
- command,
11852
- commands: results.map((result) => ({ label: result.label, command: result.command })),
11853
- stdout: combinedUpdateOutput(results, "stdout"),
11854
- stderr: combinedUpdateOutput(results, "stderr"),
11855
- webuiPid: process.pid,
11856
- nextWebuiPid: child.pid,
11857
- restorableTabCount: restorableTabs.length,
11858
- };
11859
- } finally {
11860
- if (!restartPrepared) piUpdateInProgress = false;
11861
- }
11822
+ function exactUpdatePathInside(root, candidate) {
11823
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
11824
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
11862
11825
  }
11863
11826
 
11864
11827
  function rememberClosedRestorableTab(tab, state = null) {
@@ -13628,9 +13591,15 @@ async function moveFileSystemEntryData(tab, body = {}) {
13628
13591
  }
13629
13592
 
13630
13593
  function defaultEditorCommand(targetPath) {
13594
+ if (process.env.PI_WEBUI_OPEN_COMMAND) {
13595
+ const override = process.env.PI_WEBUI_OPEN_COMMAND;
13596
+ return [".js", ".cjs", ".mjs"].includes(path.extname(override).toLowerCase())
13597
+ ? { command: process.execPath, args: [override, targetPath] }
13598
+ : { command: override, args: [targetPath] };
13599
+ }
13631
13600
  if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
13632
13601
  if (platform() === "darwin") return { command: "open", args: [targetPath] };
13633
- return { command: process.env.PI_WEBUI_OPEN_COMMAND || "xdg-open", args: [targetPath] };
13602
+ return { command: "xdg-open", args: [targetPath] };
13634
13603
  }
13635
13604
 
13636
13605
  function firstCommandOutputLine(value = "") {
@@ -15228,6 +15197,33 @@ const server = createServer(async (req, res) => {
15228
15197
  return;
15229
15198
  }
15230
15199
 
15200
+ const samplingParametersRoute = /^\/api\/tabs\/([^/]+)\/sampling-parameters$/.exec(url.pathname);
15201
+ if (samplingParametersRoute && (req.method === "GET" || req.method === "PUT")) {
15202
+ const tabId = decodeURIComponent(samplingParametersRoute[1]);
15203
+ const tab = tabs.get(tabId);
15204
+ if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${tabId}`);
15205
+ if (req.method === "GET") {
15206
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "sampling-state") }, { "cache-control": "private, no-store" });
15207
+ return;
15208
+ }
15209
+ let samplingParams;
15210
+ try {
15211
+ samplingParams = await readJsonBody(req, {
15212
+ limitBytes: SAMPLING_PARAMS_HTTP_MAX_BYTES,
15213
+ emptyError: "Sampling parameters body must be a JSON object.",
15214
+ });
15215
+ } catch (error) {
15216
+ if (error instanceof SyntaxError) throw makeHttpError(400, "Sampling parameters body must be valid JSON.");
15217
+ throw error;
15218
+ }
15219
+ const action = samplingParams && typeof samplingParams === "object" && !Array.isArray(samplingParams) && Object.keys(samplingParams).length === 0
15220
+ ? "sampling-reset"
15221
+ : "sampling-set";
15222
+ const payload = action === "sampling-set" ? { samplingParams } : {};
15223
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, action, payload) }, { "cache-control": "private, no-store" });
15224
+ return;
15225
+ }
15226
+
15231
15227
  if (url.pathname === "/api/workspaces" && req.method === "GET") {
15232
15228
  sendJson(res, 200, { ok: true, data: { workspaces: await listWebuiWorkspaces() } });
15233
15229
  return;
@@ -15446,6 +15442,7 @@ const server = createServer(async (req, res) => {
15446
15442
  const status = await webuiStatus({ includeAuthPin: isLocalRequest(req) });
15447
15443
  sendJson(res, optionalFeatureStartupReady ? 200 : 503, {
15448
15444
  ok: optionalFeatureStartupReady,
15445
+ bootIdentity,
15449
15446
  startupPhase: optionalFeatureAuditCoordinator.current().phase,
15450
15447
  webuiVersion: status.webuiVersion,
15451
15448
  piVersion: status.piVersion,
@@ -15465,7 +15462,7 @@ const server = createServer(async (req, res) => {
15465
15462
  }
15466
15463
 
15467
15464
  if (url.pathname === "/api/pi-release-notes" && req.method === "GET") {
15468
- sendJson(res, 200, { ok: true, data: await installedPiReleaseNotes() }, { "cache-control": "private, no-store" });
15465
+ sendJson(res, 200, { ok: true, data: await piReleaseNotes() }, { "cache-control": "private, no-store" });
15469
15466
  return;
15470
15467
  }
15471
15468
 
@@ -15593,33 +15590,70 @@ const server = createServer(async (req, res) => {
15593
15590
  requireLocalhostRoute(req, url.pathname);
15594
15591
  const restorableTabs = await restorableTabsForRestart();
15595
15592
  const supervisorCursor = await prepareRpcSupervisorHandoff();
15596
- const child = spawnRestartServer(restorableTabs, supervisorCursor);
15593
+ const child = await spawnRestartServer(restorableTabs, supervisorCursor);
15597
15594
  sendJson(res, 200, { ok: true, message: "Pi Web UI restarting", webuiPid: process.pid, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
15598
15595
  setTimeout(() => { void shutdown("api restart", { preserveSessions: true }); }, 20).unref();
15599
15596
  return;
15600
15597
  }
15601
15598
 
15602
- if (url.pathname === "/api/component-update" && req.method === "POST") {
15599
+ if (url.pathname === "/api/update/plan" && req.method === "POST") {
15603
15600
  requireLocalhostRoute(req, url.pathname);
15604
- const body = await readJsonBody(req);
15605
- const validation = validateComponentUpdateRequest(body);
15601
+ const validation = validateUpdatePlanRequest(await readJsonBody(req));
15606
15602
  if (!validation.ok) throw makeHttpError(400, validation.error);
15607
- startComponentUpdate(validation.target);
15608
- sendJson(res, 202, { ok: true, data: componentUpdatesForRequest(req)[validation.target] });
15603
+ const plan = await createServerOwnedUpdatePlan(validation.targets);
15604
+ sendJson(res, 201, { ok: true, data: { plan } });
15609
15605
  return;
15610
15606
  }
15611
15607
 
15612
- if (url.pathname === "/api/update" && req.method === "POST") {
15608
+ if (url.pathname === "/api/update/apply" && req.method === "POST") {
15613
15609
  requireLocalhostRoute(req, url.pathname);
15614
- const body = await readJsonBody(req);
15615
- const queryAll = ["1", "true", "yes", "all"].includes(String(url.searchParams.get("all") || "").toLowerCase());
15616
- const bodyAll = body?.all === true || String(body?.mode || "").toLowerCase() === "all";
15617
- const data = await runPiUpdateAndPrepareRestart({ all: queryAll || bodyAll });
15618
- sendJson(res, 200, { ok: true, data });
15619
- setTimeout(() => { void shutdown("api update", { preserveSessions: true }); }, 20).unref();
15610
+ const validation = validateUpdateApplyRequest(await readJsonBody(req));
15611
+ if (!validation.ok) throw makeHttpError(400, validation.error);
15612
+ const data = await applyServerOwnedUpdate(validation.transactionId, validation.planDigest);
15613
+ sendJson(res, data.state === "activating" ? 202 : 200, { ok: true, data });
15614
+ if (data.state === "activating") setTimeout(() => { void shutdown("managed Web UI activation", { preserveSessions: true }); }, 20).unref();
15620
15615
  return;
15621
15616
  }
15622
15617
 
15618
+ const updateTransactionRoute = url.pathname.match(/^\/api\/update\/transactions\/([A-Za-z0-9._-]{1,128})$/);
15619
+ if (updateTransactionRoute && req.method === "GET") {
15620
+ requireLocalhost(req, "Viewing update transactions is only allowed from localhost");
15621
+ const journal = await readUpdateJournal(agentDir, updateTransactionRoute[1]);
15622
+ if (!journal) throw makeHttpError(404, "Update transaction was not found.");
15623
+ sendJson(res, 200, { ok: true, data: journal });
15624
+ return;
15625
+ }
15626
+
15627
+ if (url.pathname === "/api/update/rollback" && req.method === "POST") {
15628
+ requireLocalhostRoute(req, url.pathname);
15629
+ const validation = validateUpdateApplyRequest(await readJsonBody(req));
15630
+ if (!validation.ok) throw makeHttpError(400, validation.error);
15631
+ const journal = await readUpdateJournal(agentDir, validation.transactionId);
15632
+ if (!journal) throw makeHttpError(404, "Update transaction was not found.");
15633
+ assertUpdatePlanDigest(journal.plan, validation.planDigest);
15634
+ const webuiTarget = journal.plan.targets.find((target) => target.id === "webui");
15635
+ if (journal.state !== "success" || !webuiTarget) throw makeHttpError(409, "Only a successfully activated Web UI transaction can be rolled back manually.");
15636
+ const currentPointer = await readRuntimePointer(agentDir, "current");
15637
+ if (!currentPointer || currentPointer.version !== webuiTarget.targetVersion) throw makeHttpError(409, "The active managed runtime no longer matches this rollback receipt.");
15638
+ const lock = await acquireInstallLock(agentDir);
15639
+ let pointer;
15640
+ let child;
15641
+ try {
15642
+ pointer = await rollbackRuntimePointer(agentDir);
15643
+ child = await spawnRestartServer(await restorableTabsForRestart(), await prepareRpcSupervisorHandoff());
15644
+ await transitionUpdateJournal(agentDir, journal.transactionId, "rolled-back", { outcome: "rolled-back", rollback: { manual: true, at: new Date().toISOString(), pointer } });
15645
+ } finally {
15646
+ await releaseInstallLock(lock);
15647
+ }
15648
+ sendJson(res, 202, { ok: true, data: { outcome: "rolled-back", pointer, nextWebuiPid: child.pid } });
15649
+ setTimeout(() => { void shutdown("manual update rollback", { preserveSessions: true }); }, 20).unref();
15650
+ return;
15651
+ }
15652
+
15653
+ if ((url.pathname === "/api/component-update" || url.pathname === "/api/update") && req.method === "POST") {
15654
+ throw makeHttpError(410, "Legacy update mutation is disabled. Create an exact server-owned plan and apply its transactionId plus planDigest.");
15655
+ }
15656
+
15623
15657
  if (url.pathname === "/api/shutdown" && req.method === "POST") {
15624
15658
  requireLocalhostRoute(req, url.pathname);
15625
15659
  sendJson(res, 200, { ok: true, message: "Pi Web UI shutting down", webuiPid: process.pid });
@@ -16105,8 +16139,8 @@ const server = createServer(async (req, res) => {
16105
16139
  }
16106
16140
 
16107
16141
  if (url.pathname === "/api/safety-guard/config" && req.method === "GET") {
16108
- getRequestedTab(req, url);
16109
- sendJson(res, 200, { ok: true, data: await safetyGuardConfigData() });
16142
+ const tab = getRequestedTab(req, url);
16143
+ sendJson(res, 200, { ok: true, data: await safetyGuardConfigData(tab) });
16110
16144
  return;
16111
16145
  }
16112
16146
 
@@ -16114,7 +16148,7 @@ const server = createServer(async (req, res) => {
16114
16148
  const body = await readJsonBody(req);
16115
16149
  const tab = getRequestedTab(req, url, body);
16116
16150
  ensureNaturalConversationRouteAllowed(tab, "safety guard setup changes are blocked");
16117
- sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(body) });
16151
+ sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(tab, body) });
16118
16152
  return;
16119
16153
  }
16120
16154
 
@@ -16528,6 +16562,7 @@ const server = createServer(async (req, res) => {
16528
16562
  });
16529
16563
 
16530
16564
  server.on("error", (error) => {
16565
+ if (error?.code === "EADDRINUSE" && !server.listening) return;
16531
16566
  if (networkRebindInProgress) {
16532
16567
  console.error("Web UI network rebind failed:", sanitizeError(error));
16533
16568
  return;
@@ -16544,19 +16579,7 @@ function sweepWebuiTempArtifacts() {
16544
16579
  sweepWebuiTempArtifacts();
16545
16580
  setInterval(sweepWebuiTempArtifacts, TEMP_ARTIFACT_SWEEP_INTERVAL_MS).unref();
16546
16581
 
16547
- await new Promise((resolve, reject) => {
16548
- const onError = (error) => {
16549
- server.off("listening", onListening);
16550
- reject(error);
16551
- };
16552
- const onListening = () => {
16553
- server.off("error", onError);
16554
- resolve();
16555
- };
16556
- server.once("error", onError);
16557
- server.once("listening", onListening);
16558
- server.listen(options.port, currentHost);
16559
- });
16582
+ await listenWithRetry(server, { port: options.port, host: currentHost, attempts: 40, initialDelayMs: 250 });
16560
16583
 
16561
16584
  const urlHost = formatUrlHost(currentHost);
16562
16585
  console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
@@ -16565,6 +16588,17 @@ if (!isLocalHost(currentHost)) {
16565
16588
  console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
16566
16589
  }
16567
16590
 
16591
+ await sweepRestoreFiles(agentDir).catch(() => {});
16592
+ await collectManagedRuntimes(agentDir).catch((error) => console.warn(`managed runtime retention failed: ${sanitizeError(error)}`));
16593
+ if (!process.env.PI_WEBUI_ACTIVATION_TRANSACTION) {
16594
+ await reconcileInterruptedUpdates(agentDir, {
16595
+ recover: async (journal) => {
16596
+ if (journal.state !== "activating") return { state: "failed", error: "Update was interrupted before verification completed." };
16597
+ const pointer = await rollbackRuntimePointer(agentDir);
16598
+ return { state: "rolled-back", pointer, error: "Activation was interrupted; the previous runtime pointer was restored." };
16599
+ },
16600
+ }).catch((error) => console.warn(`update reconciliation failed: ${sanitizeError(error)}`));
16601
+ }
16568
16602
  const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
16569
16603
  if (options.migrationDryRun) {
16570
16604
  console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);