@firstpick/pi-package-webui 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) 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 +562 -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 +1543 -109
  24. package/public/index.html +146 -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 +512 -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 +68 -1
  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 +217 -24
  56. package/tests/open-issue-wizard-static.test.mjs +1 -1
  57. package/tests/optional-feature-migration-frontend.test.mjs +13 -5
  58. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  59. package/tests/prompt-routing-tab-status.test.mjs +8 -0
  60. package/tests/questionnaire-dialog.test.mjs +3 -3
  61. package/tests/remote-auth-settings-harness.test.mjs +34 -0
  62. package/tests/rpc-supervisor-host.test.mjs +11 -2
  63. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  64. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  65. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  66. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  67. package/tests/sampling-parameter-controls.test.mjs +241 -0
  68. package/tests/session-sampling-helper.test.mjs +228 -0
  69. package/tests/session-sampling-http.test.mjs +168 -0
  70. package/tests/session-sampling-ui-static.test.mjs +370 -0
  71. package/tests/session-summary-core.test.mjs +24 -11
  72. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  73. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  74. package/tests/staged-content-hash-contract.test.mjs +52 -11
  75. package/tests/subagent-launch-slots.test.mjs +18 -1
  76. package/tests/theme-customizer-static.test.mjs +1 -1
  77. package/tests/ui-layout-settings.test.mjs +18 -1
  78. package/tests/update-api-harness.test.mjs +111 -0
  79. package/tests/update-commands.test.mjs +15 -45
  80. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  81. package/tests/update-journal-harness.test.mjs +59 -0
  82. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  83. package/tests/update-owners.test.mjs +27 -0
  84. package/tests/update-plan.test.mjs +58 -0
  85. package/tests/update-resolver.test.mjs +56 -0
  86. package/tests/update-supervisor-harness.test.mjs +57 -0
  87. package/tests/update-tab-restore-harness.test.mjs +24 -0
  88. package/tests/update-verify.test.mjs +31 -0
  89. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  90. 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
 
@@ -1876,6 +1896,10 @@ function nodeModulesParentForPackageRoot(root = packageRoot) {
1876
1896
  return root;
1877
1897
  }
1878
1898
 
1899
+ function packageNodeModulesPath(nodeModulesRoot, packageName) {
1900
+ return path.join(nodeModulesRoot, ...String(packageName).split("/").filter(Boolean));
1901
+ }
1902
+
1879
1903
  function prependNodePathEntries(entries) {
1880
1904
  const existing = String(process.env.NODE_PATH || "").split(path.delimiter).filter(Boolean);
1881
1905
  const seen = new Set();
@@ -1929,6 +1953,25 @@ function formatCommandForDisplay(command, args) {
1929
1953
  return [command, ...args].map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" ");
1930
1954
  }
1931
1955
 
1956
+ async function npmGlobalNodeModulesRoot() {
1957
+ const invocation = resolveNpmCommandInvocation(["root", "-g"]);
1958
+ const result = await runCommand(invocation.command, invocation.args, { timeoutMs: 10_000, maxOutputLength: 8_000 });
1959
+ if (result.exitCode !== 0 || result.timedOut || result.error) return null;
1960
+ return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
1961
+ }
1962
+
1963
+ async function bunGlobalNodeModulesRoots() {
1964
+ const available = await runCommand("bun", ["--version"], { timeoutMs: 10_000, maxOutputLength: 2_000 });
1965
+ if (available.exitCode !== 0 || available.timedOut || available.error) return [];
1966
+ const roots = new Set([path.join(homedir(), ".bun", "install", "global", "node_modules")]);
1967
+ const binResult = await runCommand("bun", ["pm", "bin", "-g"], { timeoutMs: 10_000, maxOutputLength: 8_000 });
1968
+ if (binResult.exitCode === 0 && !binResult.timedOut && !binResult.error) {
1969
+ const binDir = binResult.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
1970
+ if (binDir) roots.add(path.join(path.dirname(binDir), "install", "global", "node_modules"));
1971
+ }
1972
+ return [...roots];
1973
+ }
1974
+
1932
1975
  let optionalPackageNodeModulesRootsCache = null;
1933
1976
  async function optionalPackageNodeModulesRoots() {
1934
1977
  if (optionalPackageNodeModulesRootsCache) return optionalPackageNodeModulesRootsCache;
@@ -2554,9 +2597,25 @@ async function safetyGuardConfigModule() {
2554
2597
  new URL("../../pi-extension-safety-guard/src/config.mjs", import.meta.url).href,
2555
2598
  ];
2556
2599
  const failures = [];
2600
+ const requiredExports = [
2601
+ "SAFETY_GUARD_CATEGORIES",
2602
+ "SAFETY_GUARD_CONTEXT_LINES_MAX",
2603
+ "SAFETY_GUARD_CONTEXT_LINES_MIN",
2604
+ "SAFETY_GUARD_CONFIG_VERSION",
2605
+ "SAFETY_GUARD_THINKING_LEVELS",
2606
+ "assertSafetyGuardConfigPatch",
2607
+ "defaultSafetyGuardConfig",
2608
+ "mergeSafetyGuardConfig",
2609
+ "readSafetyGuardConfig",
2610
+ "safetyGuardConfigFile",
2611
+ "writeSafetyGuardConfig",
2612
+ ];
2557
2613
  for (const specifier of specifiers) {
2558
2614
  try {
2559
- return await import(specifier);
2615
+ const module = await import(specifier);
2616
+ const missing = requiredExports.filter((name) => module[name] === undefined);
2617
+ if (missing.length) throw new Error(`missing ${missing.join(", ")}`);
2618
+ return module;
2560
2619
  } catch (error) {
2561
2620
  failures.push(error instanceof Error ? error.message : String(error));
2562
2621
  }
@@ -2570,9 +2629,14 @@ async function safetyGuardConfigModule() {
2570
2629
  return safetyGuardConfigModulePromise;
2571
2630
  }
2572
2631
 
2573
- async function safetyGuardConfigData() {
2632
+ function safetyGuardModelKey(model) {
2633
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
2634
+ }
2635
+
2636
+ async function safetyGuardConfigData(tab, { config: suppliedConfig, models: suppliedModels } = {}) {
2574
2637
  const settingsModule = await safetyGuardConfigModule();
2575
- const config = settingsModule.readSafetyGuardConfig();
2638
+ const config = suppliedConfig || settingsModule.readSafetyGuardConfig();
2639
+ const models = suppliedModels || await availableGitWorkflowModels(tab);
2576
2640
  return {
2577
2641
  config,
2578
2642
  defaults: settingsModule.defaultSafetyGuardConfig(),
@@ -2581,12 +2645,18 @@ async function safetyGuardConfigData() {
2581
2645
  min: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MIN,
2582
2646
  max: settingsModule.SAFETY_GUARD_CONTEXT_LINES_MAX,
2583
2647
  },
2648
+ models,
2649
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [
2650
+ safetyGuardModelKey(model),
2651
+ supportedGitWorkflowThinkingLevels(model),
2652
+ ])),
2653
+ thinkingLevels: [...settingsModule.SAFETY_GUARD_THINKING_LEVELS],
2584
2654
  version: settingsModule.SAFETY_GUARD_CONFIG_VERSION,
2585
2655
  path: settingsModule.safetyGuardConfigFile(),
2586
2656
  };
2587
2657
  }
2588
2658
 
2589
- async function saveSafetyGuardConfigData(body = {}) {
2659
+ async function saveSafetyGuardConfigData(tab, body = {}) {
2590
2660
  const settingsModule = await safetyGuardConfigModule();
2591
2661
  const submitted = body.config && typeof body.config === "object" ? body.config : body;
2592
2662
  try {
@@ -2595,12 +2665,27 @@ async function saveSafetyGuardConfigData(body = {}) {
2595
2665
  throw makeHttpError(400, error instanceof Error ? error.message : String(error));
2596
2666
  }
2597
2667
 
2668
+ const next = settingsModule.mergeSafetyGuardConfig(settingsModule.readSafetyGuardConfig(), submitted);
2669
+ let models;
2670
+ if (next.autoReview.enabled) {
2671
+ models = await availableGitWorkflowModels(tab);
2672
+ const provider = next.autoReview.model.provider;
2673
+ const modelId = next.autoReview.model.modelId;
2674
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
2675
+ if (!model) throw makeHttpError(400, `Selected auto-review model is not currently available: ${provider || "unset"}/${modelId || "unset"}`);
2676
+ const supportedLevels = supportedGitWorkflowThinkingLevels(model);
2677
+ if (!supportedLevels.includes(next.autoReview.model.thinkingLevel)) {
2678
+ throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.autoReview.model.thinkingLevel}`);
2679
+ }
2680
+ }
2681
+
2682
+ let config;
2598
2683
  try {
2599
- const config = settingsModule.writeSafetyGuardConfig(submitted);
2600
- return { ...(await safetyGuardConfigData()), config };
2684
+ config = settingsModule.writeSafetyGuardConfig(submitted);
2601
2685
  } catch (error) {
2602
2686
  throw makeHttpError(500, error instanceof Error ? error.message : String(error));
2603
2687
  }
2688
+ return safetyGuardConfigData(tab, { config, models });
2604
2689
  }
2605
2690
 
2606
2691
  function requireSubagentLaunchSlotScope(value) {
@@ -2709,8 +2794,8 @@ function gitWorkflowModelKey(model) {
2709
2794
  }
2710
2795
 
2711
2796
  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");
2797
+ const response = await safeRpcResponse(tab, { type: "get_available_models" });
2798
+ if (response.success === false) throw makeHttpError(400, response.error || "Failed to load available models");
2714
2799
  return (Array.isArray(response.data?.models) ? response.data.models : [])
2715
2800
  .filter((model) => model?.provider && model?.id)
2716
2801
  .sort((left, right) => gitWorkflowModelKey(left).localeCompare(gitWorkflowModelKey(right)));
@@ -3302,7 +3387,12 @@ function appRunnerCandidate({ id, label, kind, command, args = [], projectFile =
3302
3387
 
3303
3388
  function addAppRunner(runners, runner) {
3304
3389
  if (!runner?.id || !runner.command) return;
3305
- if (runners.some((item) => item.id === runner.id || item.displayCommand === runner.displayCommand)) return;
3390
+ if (runners.some((item) => item.id === runner.id)) return;
3391
+ const duplicateIndex = runners.findIndex((item) => item.displayCommand === runner.displayCommand);
3392
+ if (duplicateIndex >= 0) {
3393
+ if (runner.custom && !runners[duplicateIndex].custom) runners.splice(duplicateIndex, 1, runner);
3394
+ return;
3395
+ }
3306
3396
  runners.push(runner);
3307
3397
  }
3308
3398
 
@@ -8984,6 +9074,12 @@ function commandFromGet(pathname) {
8984
9074
  }
8985
9075
  }
8986
9076
 
9077
+ const candidateProbeRequested = process.argv.length === 3 && process.argv[2] === "--candidate-probe";
9078
+ if (candidateProbeRequested) {
9079
+ process.stdout.write(`${JSON.stringify({ ok: true, packageName: WEBUI_PACKAGE, version: packageJson.version, piVersion: piPackageJson.version, serverEntry: fileURLToPath(import.meta.url) })}\n`);
9080
+ process.exit(0);
9081
+ }
9082
+
8987
9083
  let options;
8988
9084
  try {
8989
9085
  options = parseArgs(process.argv.slice(2));
@@ -9040,7 +9136,7 @@ if (Number.isFinite(startupDelayMs) && startupDelayMs > 0) {
9040
9136
  await delay(Math.min(startupDelayMs, 10_000));
9041
9137
  }
9042
9138
 
9043
- const restoreTabs = readRestoreTabsFromEnv();
9139
+ const restoreTabs = await readRestoreTabsFromEnv();
9044
9140
  const supervisorAttachCursor = readSupervisorCursorFromEnv();
9045
9141
 
9046
9142
  function normalizedRestoreString(value, maxLength) {
@@ -9068,18 +9164,17 @@ function normalizeRestoreTabDescriptor(item, seenIds) {
9068
9164
  return descriptor;
9069
9165
  }
9070
9166
 
9071
- function readRestoreTabsFromEnv() {
9072
- const raw = process.env.PI_WEBUI_RESTORE_TABS;
9167
+ async function readRestoreTabsFromEnv() {
9168
+ const restoreFile = process.env.PI_WEBUI_RESTORE_FILE;
9169
+ delete process.env.PI_WEBUI_RESTORE_FILE;
9073
9170
  delete process.env.PI_WEBUI_RESTORE_TABS;
9074
- if (!raw) return [];
9075
-
9171
+ if (!restoreFile) return [];
9076
9172
  try {
9077
- const parsed = JSON.parse(raw);
9078
- const items = Array.isArray(parsed) ? parsed : [];
9173
+ const items = await readRestoreFileOnce(restoreFile, agentDir);
9079
9174
  const seenIds = new Set();
9080
9175
  return items.map((item) => normalizeRestoreTabDescriptor(item, seenIds)).filter(Boolean).slice(0, RESTORE_TAB_LIMIT);
9081
9176
  } catch (error) {
9082
- console.warn(`failed to parse PI_WEBUI_RESTORE_TABS: ${sanitizeError(error)}`);
9177
+ console.warn(`failed to read private restore descriptor: ${sanitizeError(error)}`);
9083
9178
  return [];
9084
9179
  }
9085
9180
  }
@@ -9304,19 +9399,43 @@ function resolveSelectedPiCommand(piArgs) {
9304
9399
  };
9305
9400
  }
9306
9401
 
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
- };
9402
+ let canonicalPiRuntimePromise = null;
9403
+ let canonicalPiRuntimeProbeVersion = null;
9404
+
9405
+ async function canonicalPiRuntimeIdentity({ force = false, probeVersion = true } = {}) {
9406
+ if (force || canonicalPiRuntimeProbeVersion !== probeVersion) canonicalPiRuntimePromise = null;
9407
+ if (!canonicalPiRuntimePromise) {
9408
+ canonicalPiRuntimeProbeVersion = probeVersion;
9409
+ canonicalPiRuntimePromise = (async () => resolveCanonicalPiRuntime({
9410
+ explicitCommand: options.piBinExplicit ? options.piBin : "",
9411
+ bundledCli: await resolvedPiCliScript(),
9412
+ pathCommand: options.piBin || "pi",
9413
+ runCommand,
9414
+ timeoutMs: 10_000,
9415
+ probeVersion,
9416
+ }))().catch((error) => {
9417
+ canonicalPiRuntimePromise = null;
9418
+ throw error;
9419
+ });
9317
9420
  }
9421
+ return canonicalPiRuntimePromise;
9422
+ }
9318
9423
 
9319
- return resolveSelectedPiCommand(piArgs);
9424
+ function invalidateCanonicalPiRuntime() {
9425
+ canonicalPiRuntimePromise = null;
9426
+ canonicalPiRuntimeProbeVersion = null;
9427
+ }
9428
+
9429
+ async function resolvePiCommand(piArgs) {
9430
+ const resolution = await canonicalPiRuntimeIdentity({ probeVersion: false });
9431
+ const active = resolution.active;
9432
+ if (!active) throw new Error(resolution.refusal?.message || "No supported active Pi runtime could be verified.");
9433
+ const args = [...(active.invocation?.args || []), ...piArgs];
9434
+ return {
9435
+ command: active.invocation.command,
9436
+ args,
9437
+ displayCommand: formatCommandForDisplay(active.invocation.command, args),
9438
+ };
9320
9439
  }
9321
9440
 
9322
9441
  const tabs = new Map();
@@ -11256,17 +11375,19 @@ async function loadWebuiWorkspace(id, body = {}) {
11256
11375
  }
11257
11376
  }
11258
11377
 
11259
- function spawnRestartServer(restorableTabs, supervisorCursor) {
11378
+ async function spawnRestartServer(restorableTabs, supervisorCursor) {
11379
+ const restore = await createRestoreFile(agentDir, restorableTabs || []);
11260
11380
  const env = {
11261
11381
  ...process.env,
11262
- PI_WEBUI_RESTORE_TABS: JSON.stringify(restorableTabs || []),
11382
+ PI_WEBUI_RESTORE_FILE: restore.file,
11263
11383
  PI_WEBUI_START_DELAY_MS: "1200",
11264
11384
  };
11265
11385
  if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
11266
11386
  else delete env.PI_WEBUI_RPC_SUPERVISOR_CURSOR;
11267
11387
  if (webuiDevServer) env.PI_WEBUI_DEV = "1";
11268
11388
  else delete env.PI_WEBUI_DEV;
11269
- const child = spawn(process.execPath, process.argv.slice(1), {
11389
+ const launcher = path.join(packageRoot, "bin", "pi-webui-launcher.mjs");
11390
+ const child = spawn(process.execPath, [launcher, ...process.argv.slice(2)], {
11270
11391
  cwd: process.cwd(),
11271
11392
  env,
11272
11393
  detached: true,
@@ -11282,6 +11403,279 @@ let updateStatusCacheAt = 0;
11282
11403
  let piUpdateInProgress = false;
11283
11404
  const componentUpdateState = new ComponentUpdateState();
11284
11405
 
11406
+ async function canonicalUpdateIdentities({ forcePi = false } = {}) {
11407
+ const pi = await canonicalPiRuntimeIdentity({ force: forcePi });
11408
+ const webui = resolveWebuiRuntimeIdentity({
11409
+ packageRoot,
11410
+ packageName: WEBUI_PACKAGE,
11411
+ version: packageJson.version,
11412
+ owner: { manager: webuiDevServer ? "source" : "managed-bootstrap" },
11413
+ });
11414
+ return { pi, webui };
11415
+ }
11416
+
11417
+ function updateOwnerForTarget(target, identities) {
11418
+ if (target === "webui") {
11419
+ const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
11420
+ return sourceCheckout
11421
+ ? { manager: "unknown", packageRoot, ownerRoot: packageRoot, sourceCheckout: true }
11422
+ : { manager: "npm", packageRoot, ownerRoot: nodeModulesParentForPackageRoot(packageRoot), topLevel: true };
11423
+ }
11424
+ const active = identities.pi.active;
11425
+ const piRoot = active?.packageRoot || "";
11426
+ const installRoot = piRoot ? nodeModulesParentForPackageRoot(piRoot) : "";
11427
+ const bundled = piRoot && exactUpdatePathInside(path.join(packageRoot, "node_modules"), piRoot);
11428
+ if (bundled && webuiDevServer) return { manager: "unknown", packageRoot: piRoot, ownerRoot: packageRoot, sourceCheckout: true };
11429
+ if (bundled) return { manager: "npm", packageRoot: piRoot, ownerRoot: installRoot, topLevel: true };
11430
+ if ((active?.source === "explicit" || active?.source === "path") && piRoot) {
11431
+ return { manager: "pi", packageRoot: piRoot, ownerRoot: piRoot, topLevel: true };
11432
+ }
11433
+ return { manager: "unknown", packageRoot: piRoot, ownerRoot: "", topLevel: true };
11434
+ }
11435
+
11436
+ async function createServerOwnedUpdatePlan(targets) {
11437
+ if (privilegedUpdateInProgress()) throw makeHttpError(409, "Another privileged update is already running.");
11438
+ const identities = await canonicalUpdateIdentities({ forcePi: true });
11439
+ const transactionId = randomUUID();
11440
+ const statePaths = managedRuntimePaths(agentDir);
11441
+ const status = await getUpdateStatus({ force: true });
11442
+ for (const target of targets) {
11443
+ if (!status[target]?.checked || !status[target]?.latestVersion) throw makeHttpError(409, `${target} exact target metadata is unavailable.`);
11444
+ }
11445
+ const piRoot = identities.pi.active?.packageRoot || "";
11446
+ const bundledPi = Boolean(piRoot && exactUpdatePathInside(path.join(packageRoot, "node_modules"), piRoot));
11447
+ const requested = new Set(targets);
11448
+ const desiredPiVersion = requested.has("pi") ? status.pi.latestVersion : identities.pi.active?.version;
11449
+ const desiredWebuiVersion = requested.has("webui") ? status.webui.latestVersion : identities.webui.version;
11450
+ const separatePathPi = identities.pi.path?.canonicalId && identities.pi.path.canonicalId !== identities.pi.active?.canonicalId
11451
+ ? identities.pi.path
11452
+ : null;
11453
+ const managedRuntimeRoot = path.join(statePaths.runtimesDir, `txn-${transactionId}`);
11454
+ const candidates = [];
11455
+ for (const target of targets) {
11456
+ const identity = target === "pi" ? identities.pi.active : identities.webui;
11457
+ if (!identity) throw makeHttpError(409, identities.pi.refusal?.message || `The ${target} runtime identity could not be verified.`);
11458
+ const managedRuntime = target === "webui" || (target === "pi" && bundledPi);
11459
+ candidates.push({
11460
+ id: target,
11461
+ kind: target,
11462
+ packageName: target === "pi" ? PI_CODING_AGENT_PACKAGE : WEBUI_PACKAGE,
11463
+ currentVersion: identity.version,
11464
+ identityId: identity.canonicalId,
11465
+ requested: "latest",
11466
+ registry: NPM_REGISTRY_URL,
11467
+ strategy: managedRuntime ? "managed-side-by-side" : "delegate-exact-pi",
11468
+ owner: updateOwnerForTarget(target, identities),
11469
+ exactTargetVersion: status[target].latestVersion,
11470
+ managedRuntime,
11471
+ runtimeRoot: managedRuntime ? managedRuntimeRoot : "",
11472
+ commandForVersion: async (version, registry) => {
11473
+ if (!managedRuntime) {
11474
+ const invocation = identity.invocation;
11475
+ if (!invocation?.command) throw new Error("The exact active Pi executable cannot own its update.");
11476
+ return { command: invocation.command, args: [...(invocation.args || []), "update", "--self"] };
11477
+ }
11478
+ const piVersion = target === "pi" ? version : desiredPiVersion;
11479
+ const webuiVersion = target === "webui" ? version : desiredWebuiVersion;
11480
+ const npm = resolvedNpmCommandForExactUpdate([
11481
+ "install", "--prefix", managedRuntimeRoot, "--ignore-scripts", "--no-save", "--package-lock=false", "--registry", registry,
11482
+ `${WEBUI_PACKAGE}@${webuiVersion}`,
11483
+ `${PI_CODING_AGENT_PACKAGE}@${piVersion}`,
11484
+ ]);
11485
+ return { command: npm.command, args: npm.args };
11486
+ },
11487
+ });
11488
+ }
11489
+
11490
+ if (requested.has("pi") && requested.has("webui") && identities.pi.active) {
11491
+ const optionalStatuses = await optionalFeaturePackageStatuses(options.cwd);
11492
+ for (const feature of optionalStatuses.features) {
11493
+ if (!feature.configured || !feature.ready || !feature.installedVersion || !feature.installedRoot) continue;
11494
+ const latest = await checkLatestNpmPackageStatus(feature.packageName, feature.installedVersion);
11495
+ if (!latest.checked || !latest.updateAvailable || !latest.latestVersion) continue;
11496
+ const invocation = identities.pi.active.invocation;
11497
+ candidates.push({
11498
+ id: `optional:${feature.featureId}`,
11499
+ kind: "optional",
11500
+ packageName: feature.packageName,
11501
+ currentVersion: feature.installedVersion,
11502
+ identityId: identities.pi.active.canonicalId,
11503
+ requested: "latest",
11504
+ registry: NPM_REGISTRY_URL,
11505
+ strategy: "pi-owned-optional",
11506
+ owner: {
11507
+ manager: "pi",
11508
+ packageRoot: feature.installedRoot,
11509
+ ownerRoot: configuredAgentNpmRoot(),
11510
+ topLevel: true,
11511
+ optional: true,
11512
+ piOwned: true,
11513
+ },
11514
+ exactTargetVersion: latest.latestVersion,
11515
+ optionalFeature: true,
11516
+ featureId: feature.featureId,
11517
+ commandForVersion: async (version) => ({
11518
+ command: invocation.command,
11519
+ args: [...(invocation.args || []), "install", `npm:${feature.packageName}@${version}`],
11520
+ }),
11521
+ });
11522
+ }
11523
+ }
11524
+
11525
+ const plan = await createUpdatePlan({
11526
+ transactionId,
11527
+ registry: NPM_REGISTRY_URL,
11528
+ identities: [identities.pi.active, separatePathPi, identities.webui].filter(Boolean),
11529
+ candidates,
11530
+ resolveExactTarget: async ({ id, registry }) => {
11531
+ const candidate = candidates.find((item) => item.id === id);
11532
+ const targetVersion = candidate?.exactTargetVersion;
11533
+ if (!candidate || !targetVersion) throw new Error(`${id} exact target metadata is unavailable.`);
11534
+ let metadata = { delegatedExecutable: true };
11535
+ if (candidate.managedRuntime) {
11536
+ metadata = {
11537
+ managedRuntime: true,
11538
+ runtimeRoot: candidate.runtimeRoot,
11539
+ webuiVersion: id === "webui" ? targetVersion : desiredWebuiVersion,
11540
+ piVersion: id === "pi" ? targetVersion : desiredPiVersion,
11541
+ };
11542
+ } else if (candidate.optionalFeature) {
11543
+ metadata = { optionalFeature: true, featureId: candidate.featureId };
11544
+ }
11545
+ return { version: targetVersion, registry, metadata };
11546
+ },
11547
+ });
11548
+ await createUpdateJournal(agentDir, plan);
11549
+ return plan;
11550
+ }
11551
+
11552
+ async function activeIdentityForTarget(target) {
11553
+ const usesPiIdentity = target.id === "pi" || target.metadata?.optionalFeature === true;
11554
+ const identities = await canonicalUpdateIdentities({ forcePi: usesPiIdentity });
11555
+ return usesPiIdentity ? identities.pi.active : identities.webui;
11556
+ }
11557
+
11558
+ async function launchManagedActivation(journal, target, lock, outcome) {
11559
+ const runtimeRoot = path.resolve(target.metadata.runtimeRoot);
11560
+ const serverEntry = path.join(runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
11561
+ const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
11562
+ if (!probe.ok) throw new Error(probe.error || "Managed Web UI candidate probe failed.");
11563
+ if (target.metadata.webuiVersion !== packageJson.version) {
11564
+ const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-activation" });
11565
+ const featureIds = snapshot.features
11566
+ .filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
11567
+ .map(({ featureId }) => featureId);
11568
+ await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
11569
+ }
11570
+ const restore = await createRestoreFile(agentDir, await restorableTabsForRestart());
11571
+ const supervisorCursor = await prepareRpcSupervisorHandoff();
11572
+ const helper = path.join(packageRoot, "bin", "pi-webui-update-supervisor.mjs");
11573
+ const host = formatUrlHost(currentHost);
11574
+ const helperArgs = [
11575
+ helper,
11576
+ "--agent-dir", agentDir,
11577
+ "--runtime-root", runtimeRoot,
11578
+ "--server-entry", serverEntry,
11579
+ "--version", target.metadata.webuiVersion,
11580
+ "--pi-version", target.metadata.piVersion,
11581
+ "--outcome", outcome,
11582
+ "--transaction", journal.transactionId,
11583
+ "--url", `http://${host}:${options.port}/`,
11584
+ "--old-boot", bootIdentity,
11585
+ "--timeout-ms", String(UPDATE_HEALTH_GATE_MS),
11586
+ "--server-args", Buffer.from(JSON.stringify(process.argv.slice(2))).toString("base64url"),
11587
+ ];
11588
+ const env = { ...process.env, PI_WEBUI_RESTORE_FILE: restore.file, PI_WEBUI_START_DELAY_MS: "300", PI_WEBUI_UPDATE_LOCK_TOKEN: lock.token };
11589
+ if (supervisorCursor) env.PI_WEBUI_RPC_SUPERVISOR_CURSOR = JSON.stringify(supervisorCursor);
11590
+ const child = spawn(process.execPath, helperArgs, { cwd: process.cwd(), env, detached: true, stdio: "ignore", windowsHide: true });
11591
+ await new Promise((resolve, reject) => {
11592
+ child.once("spawn", resolve);
11593
+ child.once("error", reject);
11594
+ });
11595
+ await transferInstallLock(lock, child.pid);
11596
+ child.unref();
11597
+ return { pid: child.pid, runtimeRoot, serverEntry };
11598
+ }
11599
+
11600
+ async function applyServerOwnedUpdate(transactionId, planDigest) {
11601
+ if (privilegedUpdateInProgress()) throw makeHttpError(409, "Another privileged update is already running.");
11602
+ const journal = await readUpdateJournal(agentDir, transactionId);
11603
+ if (!journal) throw makeHttpError(404, "Update transaction was not found.");
11604
+ assertUpdatePlanDigest(journal.plan, planDigest);
11605
+ if (journal.state !== "planned") throw makeHttpError(409, `Update transaction is already ${journal.state}.`);
11606
+ piUpdateInProgress = true;
11607
+ let lock = null;
11608
+ let lockTransferred = false;
11609
+ let state = "planned";
11610
+ try {
11611
+ lock = await acquireInstallLock(agentDir);
11612
+ await transitionUpdateJournal(agentDir, transactionId, "applying");
11613
+ state = "applying";
11614
+ let installedManagedRuntime = "";
11615
+ const result = await executePlanTargets(journal.plan, {
11616
+ runner: async (command, args, { target }) => {
11617
+ if (target.metadata?.managedRuntime && installedManagedRuntime === target.metadata.runtimeRoot) {
11618
+ return { exitCode: 0, timedOut: false, error: "", stdout: "Managed runtime exact package set already staged by the preceding target.", stderr: "", skippedDuplicate: true };
11619
+ }
11620
+ const commandResult = await executeCommand(command, args, { cwd: target.metadata?.runtimeRoot || process.cwd(), timeoutMs: PACKAGE_UPDATE_TIMEOUT_MS, maxOutputLength: PACKAGE_UPDATE_OUTPUT_MAX_CHARS });
11621
+ if (target.metadata?.managedRuntime && commandResult.exitCode === 0 && !commandResult.timedOut && !commandResult.error) installedManagedRuntime = target.metadata.runtimeRoot;
11622
+ return commandResult;
11623
+ },
11624
+ beforeTarget: async (target) => {
11625
+ const active = await activeIdentityForTarget(target);
11626
+ assertPlanIdentity(target, active);
11627
+ if (target.metadata?.managedRuntime) {
11628
+ await mkdir(target.metadata.runtimeRoot, { recursive: true, mode: 0o700 });
11629
+ try {
11630
+ await writeFile(path.join(target.metadata.runtimeRoot, "package.json"), `${JSON.stringify({ private: true })}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
11631
+ } catch (error) {
11632
+ if (error?.code !== "EEXIST") throw error;
11633
+ }
11634
+ }
11635
+ },
11636
+ verifyTarget: async (target, command) => {
11637
+ if (target.metadata?.optionalFeature) {
11638
+ const [afterIdentity, afterStatus] = await Promise.all([
11639
+ activeIdentityForTarget(target),
11640
+ optionalFeaturePackageStatus(target.metadata.featureId, options.cwd),
11641
+ ]);
11642
+ return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity, beforeVersion: target.currentVersion, afterVersion: afterStatus.ready ? afterStatus.installedVersion : "", command });
11643
+ }
11644
+ if (target.metadata?.managedRuntime) {
11645
+ const serverEntry = path.join(target.metadata.runtimeRoot, "node_modules", ...WEBUI_PACKAGE.split("/"), "bin", "pi-webui.mjs");
11646
+ const probe = await probeCandidateRuntime(serverEntry, { expectedVersion: target.metadata.webuiVersion, expectedPiVersion: target.metadata.piVersion });
11647
+ const afterVersion = target.id === "pi" ? probe.data?.piVersion : probe.data?.version;
11648
+ return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: { canonicalId: target.identityId }, beforeVersion: target.currentVersion, afterVersion: probe.ok ? afterVersion : "", command });
11649
+ }
11650
+ const after = await activeIdentityForTarget(target);
11651
+ return verifyTargetResult(target, { beforeIdentity: { canonicalId: target.identityId }, afterIdentity: after, beforeVersion: target.currentVersion, afterVersion: after?.version, command });
11652
+ },
11653
+ });
11654
+ await transitionUpdateJournal(agentDir, transactionId, "verifying", { outcome: result.outcome, receipts: result.receipts });
11655
+ state = "verifying";
11656
+ const managedTargets = journal.plan.targets.filter((target) => target.metadata?.managedRuntime);
11657
+ const managedTargetsVerified = managedTargets.length > 0 && managedTargets.every((target) => result.receipts.find((receipt) => receipt.targetId === target.id)?.status === "success");
11658
+ const activationTarget = managedTargetsVerified ? managedTargets[0] : null;
11659
+ if (activationTarget) {
11660
+ const activation = await launchManagedActivation(journal, activationTarget, lock, result.outcome);
11661
+ lockTransferred = true;
11662
+ return { transactionId, planDigest, state: "activating", outcome: result.outcome, receipts: result.receipts, activation };
11663
+ }
11664
+ const terminal = result.outcome === "success" ? "success" : result.outcome === "partial" ? "partial" : "failed";
11665
+ const completed = await transitionUpdateJournal(agentDir, transactionId, terminal, { outcome: result.outcome, receipts: result.receipts });
11666
+ return completed;
11667
+ } catch (error) {
11668
+ if (state === "applying" || state === "verifying") await transitionUpdateJournal(agentDir, transactionId, "failed", { error: sanitizeComponentUpdateError(error), outcome: "failed" }).catch(() => {});
11669
+ throw error;
11670
+ } finally {
11671
+ if (lock && !lockTransferred) await releaseInstallLock(lock);
11672
+ piUpdateInProgress = false;
11673
+ invalidateCanonicalPiRuntime();
11674
+ updateStatusCache = null;
11675
+ updateStatusCacheAt = 0;
11676
+ }
11677
+ }
11678
+
11285
11679
  function webuiComponentUpdateUnavailableReason() {
11286
11680
  if (webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules")) {
11287
11681
  return "Automatic Web UI update is unavailable from a source or development checkout.";
@@ -11322,8 +11716,17 @@ function basePackageUpdateStatus(packageName, currentVersion) {
11322
11716
  };
11323
11717
  }
11324
11718
 
11719
+ async function currentPiRuntimeVersion() {
11720
+ try {
11721
+ return (await canonicalUpdateIdentities({ forcePi: true })).pi.active?.version || "unknown";
11722
+ } catch {
11723
+ return "unknown";
11724
+ }
11725
+ }
11726
+
11325
11727
  async function checkLatestPiReleaseStatus() {
11326
- const status = basePackageUpdateStatus(PI_CODING_AGENT_PACKAGE, piPackageJson.version);
11728
+ const currentVersion = await currentPiRuntimeVersion();
11729
+ const status = basePackageUpdateStatus(PI_CODING_AGENT_PACKAGE, currentVersion);
11327
11730
  const skippedReason = updateChecksSkippedReason();
11328
11731
  if (skippedReason) {
11329
11732
  status.skipped = true;
@@ -11333,7 +11736,7 @@ async function checkLatestPiReleaseStatus() {
11333
11736
  try {
11334
11737
  const data = await fetchJsonWithTimeout(PI_LATEST_VERSION_URL, {
11335
11738
  headers: {
11336
- "User-Agent": `pi-webui/${packageJson.version} pi/${piPackageJson.version || "unknown"}`,
11739
+ "User-Agent": `pi-webui/${packageJson.version} pi/${currentVersion || "unknown"}`,
11337
11740
  accept: "application/json",
11338
11741
  },
11339
11742
  });
@@ -11401,464 +11804,28 @@ async function getUpdateStatus({ force = false } = {}) {
11401
11804
  checkedAt: new Date(now).toISOString(),
11402
11805
  updateAvailable,
11403
11806
  restartRequired: true,
11404
- command: piUpdateCommandText(),
11405
- allCommand: piUpdateCommandText({ all: true, supportsAll: true }),
11406
- allFallbackCommand: piUpdateCommandText({ all: true }),
11807
+ planEndpoint: "/api/update/plan",
11808
+ applyEndpoint: "/api/update/apply",
11407
11809
  webuiDev: webuiDevServer,
11408
11810
  pi: piStatus,
11409
11811
  webui: webuiStatus,
11410
11812
  packages: {
11411
11813
  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."
11814
+ note: "Automatic updates use only persisted exact-target plans. Unsupported or unproven owners are reported as refusals and never scanned or mutated."
11413
11815
  },
11414
11816
  };
11415
11817
  updateStatusCacheAt = now;
11416
11818
  return updateStatusCache;
11417
11819
  }
11418
11820
 
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}`);
11427
- }
11428
-
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();
11821
+ function resolvedNpmCommandForExactUpdate(args) {
11822
+ const invocation = resolveNpmCommandInvocation(args);
11823
+ return { command: invocation.command, args: invocation.args };
11486
11824
  }
11487
11825
 
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
- }
11826
+ function exactUpdatePathInside(root, candidate) {
11827
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
11828
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
11862
11829
  }
11863
11830
 
11864
11831
  function rememberClosedRestorableTab(tab, state = null) {
@@ -13628,9 +13595,15 @@ async function moveFileSystemEntryData(tab, body = {}) {
13628
13595
  }
13629
13596
 
13630
13597
  function defaultEditorCommand(targetPath) {
13598
+ if (process.env.PI_WEBUI_OPEN_COMMAND) {
13599
+ const override = process.env.PI_WEBUI_OPEN_COMMAND;
13600
+ return [".js", ".cjs", ".mjs"].includes(path.extname(override).toLowerCase())
13601
+ ? { command: process.execPath, args: [override, targetPath] }
13602
+ : { command: override, args: [targetPath] };
13603
+ }
13631
13604
  if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
13632
13605
  if (platform() === "darwin") return { command: "open", args: [targetPath] };
13633
- return { command: process.env.PI_WEBUI_OPEN_COMMAND || "xdg-open", args: [targetPath] };
13606
+ return { command: "xdg-open", args: [targetPath] };
13634
13607
  }
13635
13608
 
13636
13609
  function firstCommandOutputLine(value = "") {
@@ -15228,6 +15201,33 @@ const server = createServer(async (req, res) => {
15228
15201
  return;
15229
15202
  }
15230
15203
 
15204
+ const samplingParametersRoute = /^\/api\/tabs\/([^/]+)\/sampling-parameters$/.exec(url.pathname);
15205
+ if (samplingParametersRoute && (req.method === "GET" || req.method === "PUT")) {
15206
+ const tabId = decodeURIComponent(samplingParametersRoute[1]);
15207
+ const tab = tabs.get(tabId);
15208
+ if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${tabId}`);
15209
+ if (req.method === "GET") {
15210
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "sampling-state") }, { "cache-control": "private, no-store" });
15211
+ return;
15212
+ }
15213
+ let samplingParams;
15214
+ try {
15215
+ samplingParams = await readJsonBody(req, {
15216
+ limitBytes: SAMPLING_PARAMS_HTTP_MAX_BYTES,
15217
+ emptyError: "Sampling parameters body must be a JSON object.",
15218
+ });
15219
+ } catch (error) {
15220
+ if (error instanceof SyntaxError) throw makeHttpError(400, "Sampling parameters body must be valid JSON.");
15221
+ throw error;
15222
+ }
15223
+ const action = samplingParams && typeof samplingParams === "object" && !Array.isArray(samplingParams) && Object.keys(samplingParams).length === 0
15224
+ ? "sampling-reset"
15225
+ : "sampling-set";
15226
+ const payload = action === "sampling-set" ? { samplingParams } : {};
15227
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, action, payload) }, { "cache-control": "private, no-store" });
15228
+ return;
15229
+ }
15230
+
15231
15231
  if (url.pathname === "/api/workspaces" && req.method === "GET") {
15232
15232
  sendJson(res, 200, { ok: true, data: { workspaces: await listWebuiWorkspaces() } });
15233
15233
  return;
@@ -15446,6 +15446,7 @@ const server = createServer(async (req, res) => {
15446
15446
  const status = await webuiStatus({ includeAuthPin: isLocalRequest(req) });
15447
15447
  sendJson(res, optionalFeatureStartupReady ? 200 : 503, {
15448
15448
  ok: optionalFeatureStartupReady,
15449
+ bootIdentity,
15449
15450
  startupPhase: optionalFeatureAuditCoordinator.current().phase,
15450
15451
  webuiVersion: status.webuiVersion,
15451
15452
  piVersion: status.piVersion,
@@ -15465,7 +15466,7 @@ const server = createServer(async (req, res) => {
15465
15466
  }
15466
15467
 
15467
15468
  if (url.pathname === "/api/pi-release-notes" && req.method === "GET") {
15468
- sendJson(res, 200, { ok: true, data: await installedPiReleaseNotes() }, { "cache-control": "private, no-store" });
15469
+ sendJson(res, 200, { ok: true, data: await piReleaseNotes() }, { "cache-control": "private, no-store" });
15469
15470
  return;
15470
15471
  }
15471
15472
 
@@ -15593,33 +15594,70 @@ const server = createServer(async (req, res) => {
15593
15594
  requireLocalhostRoute(req, url.pathname);
15594
15595
  const restorableTabs = await restorableTabsForRestart();
15595
15596
  const supervisorCursor = await prepareRpcSupervisorHandoff();
15596
- const child = spawnRestartServer(restorableTabs, supervisorCursor);
15597
+ const child = await spawnRestartServer(restorableTabs, supervisorCursor);
15597
15598
  sendJson(res, 200, { ok: true, message: "Pi Web UI restarting", webuiPid: process.pid, nextWebuiPid: child.pid, restorableTabCount: restorableTabs.length });
15598
15599
  setTimeout(() => { void shutdown("api restart", { preserveSessions: true }); }, 20).unref();
15599
15600
  return;
15600
15601
  }
15601
15602
 
15602
- if (url.pathname === "/api/component-update" && req.method === "POST") {
15603
+ if (url.pathname === "/api/update/plan" && req.method === "POST") {
15603
15604
  requireLocalhostRoute(req, url.pathname);
15604
- const body = await readJsonBody(req);
15605
- const validation = validateComponentUpdateRequest(body);
15605
+ const validation = validateUpdatePlanRequest(await readJsonBody(req));
15606
15606
  if (!validation.ok) throw makeHttpError(400, validation.error);
15607
- startComponentUpdate(validation.target);
15608
- sendJson(res, 202, { ok: true, data: componentUpdatesForRequest(req)[validation.target] });
15607
+ const plan = await createServerOwnedUpdatePlan(validation.targets);
15608
+ sendJson(res, 201, { ok: true, data: { plan } });
15609
15609
  return;
15610
15610
  }
15611
15611
 
15612
- if (url.pathname === "/api/update" && req.method === "POST") {
15612
+ if (url.pathname === "/api/update/apply" && req.method === "POST") {
15613
15613
  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();
15614
+ const validation = validateUpdateApplyRequest(await readJsonBody(req));
15615
+ if (!validation.ok) throw makeHttpError(400, validation.error);
15616
+ const data = await applyServerOwnedUpdate(validation.transactionId, validation.planDigest);
15617
+ sendJson(res, data.state === "activating" ? 202 : 200, { ok: true, data });
15618
+ if (data.state === "activating") setTimeout(() => { void shutdown("managed Web UI activation", { preserveSessions: true }); }, 20).unref();
15620
15619
  return;
15621
15620
  }
15622
15621
 
15622
+ const updateTransactionRoute = url.pathname.match(/^\/api\/update\/transactions\/([A-Za-z0-9._-]{1,128})$/);
15623
+ if (updateTransactionRoute && req.method === "GET") {
15624
+ requireLocalhost(req, "Viewing update transactions is only allowed from localhost");
15625
+ const journal = await readUpdateJournal(agentDir, updateTransactionRoute[1]);
15626
+ if (!journal) throw makeHttpError(404, "Update transaction was not found.");
15627
+ sendJson(res, 200, { ok: true, data: journal });
15628
+ return;
15629
+ }
15630
+
15631
+ if (url.pathname === "/api/update/rollback" && req.method === "POST") {
15632
+ requireLocalhostRoute(req, url.pathname);
15633
+ const validation = validateUpdateApplyRequest(await readJsonBody(req));
15634
+ if (!validation.ok) throw makeHttpError(400, validation.error);
15635
+ const journal = await readUpdateJournal(agentDir, validation.transactionId);
15636
+ if (!journal) throw makeHttpError(404, "Update transaction was not found.");
15637
+ assertUpdatePlanDigest(journal.plan, validation.planDigest);
15638
+ const webuiTarget = journal.plan.targets.find((target) => target.id === "webui");
15639
+ if (journal.state !== "success" || !webuiTarget) throw makeHttpError(409, "Only a successfully activated Web UI transaction can be rolled back manually.");
15640
+ const currentPointer = await readRuntimePointer(agentDir, "current");
15641
+ if (!currentPointer || currentPointer.version !== webuiTarget.targetVersion) throw makeHttpError(409, "The active managed runtime no longer matches this rollback receipt.");
15642
+ const lock = await acquireInstallLock(agentDir);
15643
+ let pointer;
15644
+ let child;
15645
+ try {
15646
+ pointer = await rollbackRuntimePointer(agentDir);
15647
+ child = await spawnRestartServer(await restorableTabsForRestart(), await prepareRpcSupervisorHandoff());
15648
+ await transitionUpdateJournal(agentDir, journal.transactionId, "rolled-back", { outcome: "rolled-back", rollback: { manual: true, at: new Date().toISOString(), pointer } });
15649
+ } finally {
15650
+ await releaseInstallLock(lock);
15651
+ }
15652
+ sendJson(res, 202, { ok: true, data: { outcome: "rolled-back", pointer, nextWebuiPid: child.pid } });
15653
+ setTimeout(() => { void shutdown("manual update rollback", { preserveSessions: true }); }, 20).unref();
15654
+ return;
15655
+ }
15656
+
15657
+ if ((url.pathname === "/api/component-update" || url.pathname === "/api/update") && req.method === "POST") {
15658
+ throw makeHttpError(410, "Legacy update mutation is disabled. Create an exact server-owned plan and apply its transactionId plus planDigest.");
15659
+ }
15660
+
15623
15661
  if (url.pathname === "/api/shutdown" && req.method === "POST") {
15624
15662
  requireLocalhostRoute(req, url.pathname);
15625
15663
  sendJson(res, 200, { ok: true, message: "Pi Web UI shutting down", webuiPid: process.pid });
@@ -16105,8 +16143,8 @@ const server = createServer(async (req, res) => {
16105
16143
  }
16106
16144
 
16107
16145
  if (url.pathname === "/api/safety-guard/config" && req.method === "GET") {
16108
- getRequestedTab(req, url);
16109
- sendJson(res, 200, { ok: true, data: await safetyGuardConfigData() });
16146
+ const tab = getRequestedTab(req, url);
16147
+ sendJson(res, 200, { ok: true, data: await safetyGuardConfigData(tab) });
16110
16148
  return;
16111
16149
  }
16112
16150
 
@@ -16114,7 +16152,7 @@ const server = createServer(async (req, res) => {
16114
16152
  const body = await readJsonBody(req);
16115
16153
  const tab = getRequestedTab(req, url, body);
16116
16154
  ensureNaturalConversationRouteAllowed(tab, "safety guard setup changes are blocked");
16117
- sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(body) });
16155
+ sendJson(res, 200, { ok: true, data: await saveSafetyGuardConfigData(tab, body) });
16118
16156
  return;
16119
16157
  }
16120
16158
 
@@ -16528,6 +16566,7 @@ const server = createServer(async (req, res) => {
16528
16566
  });
16529
16567
 
16530
16568
  server.on("error", (error) => {
16569
+ if (error?.code === "EADDRINUSE" && !server.listening) return;
16531
16570
  if (networkRebindInProgress) {
16532
16571
  console.error("Web UI network rebind failed:", sanitizeError(error));
16533
16572
  return;
@@ -16544,19 +16583,7 @@ function sweepWebuiTempArtifacts() {
16544
16583
  sweepWebuiTempArtifacts();
16545
16584
  setInterval(sweepWebuiTempArtifacts, TEMP_ARTIFACT_SWEEP_INTERVAL_MS).unref();
16546
16585
 
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
- });
16586
+ await listenWithRetry(server, { port: options.port, host: currentHost, attempts: 40, initialDelayMs: 250 });
16560
16587
 
16561
16588
  const urlHost = formatUrlHost(currentHost);
16562
16589
  console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
@@ -16565,6 +16592,17 @@ if (!isLocalHost(currentHost)) {
16565
16592
  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
16593
  }
16567
16594
 
16595
+ await sweepRestoreFiles(agentDir).catch(() => {});
16596
+ await collectManagedRuntimes(agentDir).catch((error) => console.warn(`managed runtime retention failed: ${sanitizeError(error)}`));
16597
+ if (!process.env.PI_WEBUI_ACTIVATION_TRANSACTION) {
16598
+ await reconcileInterruptedUpdates(agentDir, {
16599
+ recover: async (journal) => {
16600
+ if (journal.state !== "activating") return { state: "failed", error: "Update was interrupted before verification completed." };
16601
+ const pointer = await rollbackRuntimePointer(agentDir);
16602
+ return { state: "rolled-back", pointer, error: "Activation was interrupted; the previous runtime pointer was restored." };
16603
+ },
16604
+ }).catch((error) => console.warn(`update reconciliation failed: ${sanitizeError(error)}`));
16605
+ }
16568
16606
  const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
16569
16607
  if (options.migrationDryRun) {
16570
16608
  console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);