@firstpick/pi-package-webui 0.8.3 → 0.8.5

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 (35) hide show
  1. package/README.md +67 -16
  2. package/bin/pi-webui.mjs +777 -131
  3. package/lib/WEBUI_TUI_NATIVE_PARITY.json +26 -0
  4. package/lib/optional-feature-catalog.mjs +29 -0
  5. package/lib/optional-feature-migration.mjs +410 -0
  6. package/lib/session-summary-core.mjs +320 -0
  7. package/lib/session-summary-preferences.mjs +267 -0
  8. package/package.json +5 -42
  9. package/public/app.js +1325 -51
  10. package/public/index.html +43 -1
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +345 -1
  13. package/session-summary.ts +403 -0
  14. package/tests/aur-review-widget-static.test.mjs +3 -2
  15. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  16. package/tests/browser/session-summary.spec.mjs +271 -0
  17. package/tests/codex-fast-mode-static.test.mjs +10 -9
  18. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  19. package/tests/fast-mode-client-static.test.mjs +1 -1
  20. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  21. package/tests/http-endpoints-harness.test.mjs +429 -3
  22. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  23. package/tests/mobile-foundation-static.test.mjs +2 -2
  24. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  25. package/tests/mobile-static.test.mjs +91 -92
  26. package/tests/native-parity-harness.test.mjs +9 -1
  27. package/tests/native-parity.test.mjs +23 -1
  28. package/tests/open-issue-wizard-static.test.mjs +1 -1
  29. package/tests/optional-feature-migration-frontend.test.mjs +75 -0
  30. package/tests/optional-feature-migration.test.mjs +142 -0
  31. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  32. package/tests/questionnaire-dialog.test.mjs +2 -2
  33. package/tests/session-summary-core.test.mjs +491 -0
  34. package/tests/session-summary-preferences.test.mjs +103 -0
  35. package/tests/side-panel-section-reorder-static.test.mjs +2 -2
package/bin/pi-webui.mjs CHANGED
@@ -15,6 +15,11 @@ import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendi
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
16
  import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
17
  import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
18
+ import {
19
+ readSessionSummaryPreferences,
20
+ supportedSessionSummaryThinkingLevels,
21
+ writeSessionSummaryPreferences,
22
+ } from "../lib/session-summary-preferences.mjs";
18
23
  import {
19
24
  deleteWebuiWorkspace,
20
25
  getWebuiWorkspace,
@@ -41,6 +46,11 @@ import {
41
46
  } from "../lib/git-command-errors.mjs";
42
47
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
43
48
  import { ComponentUpdateState, validateComponentUpdateRequest } from "../lib/component-update-state.mjs";
49
+ import { OPTIONAL_FEATURE_BY_ID, OPTIONAL_FEATURE_CATALOG } from "../lib/optional-feature-catalog.mjs";
50
+ import {
51
+ OptionalFeatureAuditCoordinator,
52
+ OptionalFeatureMigrationStore,
53
+ } from "../lib/optional-feature-migration.mjs";
44
54
  import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
45
55
  import {
46
56
  GIT_WORKFLOW_DEFAULT_VARIANTS,
@@ -130,6 +140,7 @@ const require = createRequire(import.meta.url);
130
140
  const packageRoot = path.resolve(__dirname, "..");
131
141
  const publicDir = path.join(packageRoot, "public");
132
142
  const webuiHelperExtensionPath = path.join(packageRoot, "webui-rpc-helper.mjs");
143
+ const sessionSummaryExtensionPath = path.join(packageRoot, "session-summary.ts");
133
144
  const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
134
145
  const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT";
135
146
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
@@ -188,6 +199,16 @@ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
188
199
  const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
189
200
  const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
190
201
  const BODY_LIMIT_BYTES = 1024 * 1024;
202
+ const SESSION_SUMMARY_REQUEST_MAX_BYTES = 32 * 1024;
203
+ const SESSION_SUMMARY_RPC_TYPE = "firstpick:session-summary-rpc";
204
+ const SESSION_SUMMARY_DISPLAY_TYPE = "firstpick:session-summary-display";
205
+ const SESSION_SUMMARY_PROTOCOL_VERSION = 1;
206
+ const SESSION_SUMMARY_TITLE_MAX_CHARS = 44;
207
+ const SESSION_SUMMARY_MARKDOWN_MAX_CHARS = 16 * 1024;
208
+ const SESSION_SUMMARY_PROMPT_MAX_CHARS = 8 * 1024;
209
+ const SESSION_SUMMARY_FAILURE_MAX_CHARS = 512;
210
+ const SESSION_SUMMARY_GENERATE_TIMEOUT_MS = 105 * 1000;
211
+ const SESSION_SUMMARY_KINDS = new Set(["setup", "state", "generating", "success", "failure", "title"]);
191
212
  const RECOVERY_ENDPOINT_PATH = "/api/recovery/plan";
192
213
  const RECOVERY_BODY_LIMIT_BYTES = 256 * 1024;
193
214
  const RECOVERY_PROMPT_MAX_CHARS = 200_000;
@@ -376,38 +397,13 @@ function parseSlashCommand(message) {
376
397
  return parseNativeSlashCommand(message, NATIVE_SLASH_COMMAND_NAMES);
377
398
  }
378
399
  const NATURAL_CONVERSATION_FEATURE_ID = "naturalConversation";
379
- const OPTIONAL_FEATURE_PACKAGES = new Map([
380
- ["bangCommandAutocomplete", "@firstpick/pi-extension-bang-command-autocomplete"],
381
- ["fishUserBash", "@firstpick/pi-extension-fish-user-bash"],
382
- ["btwCommand", "@firstpick/pi-extension-btw"],
383
- ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
384
- ["releaseNpm", "@firstpick/pi-extension-release-npm"],
385
- ["releaseAur", "@firstpick/pi-extension-release-aur"],
386
- ["aurReview", "@firstpick/pi-extension-aur-review"],
387
- ["workflows", "@firstpick/pi-extension-workflows"],
388
- ["safetyGuard", "@firstpick/pi-extension-safety-guard"],
389
- ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills"],
390
- ["todoProgressWidget", "@firstpick/pi-extension-todo-progress"],
391
- ["tuiToolsCommand", "@firstpick/pi-extension-tools"],
392
- ["remoteWebui", "@firstpick/pi-package-remote-webui"],
393
- ["questionnaire", "@firstpick/pi-package-questionnaire"],
394
- ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
395
- ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
396
- ["statsCommand", "@firstpick/pi-extension-stats"],
397
- ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode"],
398
- ["themeBundle", "@firstpick/pi-themes-bundle"],
399
- ]);
400
- const WEBUI_CONTROLLED_PACKAGES = new Set([
401
- WEBUI_PACKAGE,
402
- ...[...OPTIONAL_FEATURE_PACKAGES.entries()]
403
- .filter(([featureId]) => featureId !== NATURAL_CONVERSATION_FEATURE_ID)
404
- .map(([, packageName]) => packageName),
405
- ]);
406
- const UPDATE_PACKAGE_NAMES = [...new Set([
407
- ...CORE_UPDATE_PACKAGE_NAMES,
408
- ...WEBUI_CONTROLLED_PACKAGES,
409
- ...OPTIONAL_FEATURE_PACKAGES.values(),
410
- ])].sort();
400
+ const OPTIONAL_FEATURE_PACKAGES = new Map(OPTIONAL_FEATURE_CATALOG.map(({ featureId, packageName }) => [featureId, packageName]));
401
+ const OPTIONAL_FEATURE_PACKAGE_NAMES = new Set(OPTIONAL_FEATURE_PACKAGES.values());
402
+ const WEBUI_RESOURCE_EXCLUDED_PACKAGES = new Set([WEBUI_PACKAGE]);
403
+ let optionalFeatureMigrationStore;
404
+ let optionalFeatureAuditCoordinator;
405
+ let optionalFeatureStartupReady = false;
406
+ const UPDATE_PACKAGE_NAMES = [...CORE_UPDATE_PACKAGE_NAMES].sort();
411
407
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
412
408
  const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
413
409
  // Codex subscription Fast mode is owned by the optional @firstpick/pi-extension-codex-fast-mode
@@ -439,6 +435,8 @@ Options:
439
435
  --remote-auth Enable startup PIN authentication for non-local clients
440
436
  --no-remote-auth Disable startup PIN authentication
441
437
  --output-mode <mode> Web UI output default: normal or compact-v1
438
+ --migrate-optional-features Migrate audit-selected legacy optional features
439
+ --migration-dry-run Print the startup migration plan without package mutation
442
440
  -h, --help Show this help
443
441
  -v, --version Print version
444
442
 
@@ -488,6 +486,8 @@ function parseArgs(argv) {
488
486
  remoteAuthExplicit: process.env.PI_WEBUI_REMOTE_AUTH !== undefined,
489
487
  outputMode: undefined,
490
488
  envOutputMode: process.env.PI_WEBUI_OUTPUT_MODE === undefined ? undefined : requiredOutputMode(process.env.PI_WEBUI_OUTPUT_MODE, "PI_WEBUI_OUTPUT_MODE"),
489
+ migrateOptionalFeatures: false,
490
+ migrationDryRun: false,
491
491
  piArgs: [],
492
492
  help: false,
493
493
  version: false,
@@ -547,6 +547,14 @@ function parseArgs(argv) {
547
547
  i++;
548
548
  continue;
549
549
  }
550
+ if (arg === "--migrate-optional-features") {
551
+ options.migrateOptionalFeatures = true;
552
+ continue;
553
+ }
554
+ if (arg === "--migration-dry-run") {
555
+ options.migrationDryRun = true;
556
+ continue;
557
+ }
550
558
  if (arg === "--remote-auth") {
551
559
  options.remoteAuth = true;
552
560
  options.remoteAuthExplicit = true;
@@ -1889,38 +1897,11 @@ function declaredDependencySpec(pkg, packageName) {
1889
1897
  );
1890
1898
  }
1891
1899
 
1892
- async function installRootDeclaresPackage(root, packageName) {
1893
- const pkg = await readJsonFileIfExists(path.join(root, "package.json"));
1894
- return declaredDependencySpec(pkg, packageName) !== undefined;
1895
- }
1896
-
1897
- async function installRootContainsPackage(root, packageName) {
1898
- return directoryExists(packageNodeModulesPath(path.join(root, "node_modules"), packageName));
1899
- }
1900
-
1901
1900
  function configuredAgentNpmRoot() {
1902
1901
  const root = process.env.PI_CODING_AGENT_DIR ? path.resolve(expandUserPath(process.env.PI_CODING_AGENT_DIR)) : agentDir;
1903
1902
  return path.join(root, "npm");
1904
1903
  }
1905
1904
 
1906
- async function optionalDependencyInstallRoot() {
1907
- const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
1908
- if (configuredRoot) return path.resolve(expandUserPath(configuredRoot));
1909
-
1910
- const installRoot = nodeModulesParentForPackageRoot(packageRoot);
1911
- if (await installRootDeclaresPackage(installRoot, "@firstpick/pi-package-webui") || await installRootContainsPackage(installRoot, "@firstpick/pi-package-webui")) return installRoot;
1912
-
1913
- const agentNpmRoot = configuredAgentNpmRoot();
1914
- if (installRoot !== agentNpmRoot && (await installRootDeclaresPackage(agentNpmRoot, "@firstpick/pi-package-webui") || await installRootContainsPackage(agentNpmRoot, "@firstpick/pi-package-webui"))) return agentNpmRoot;
1915
-
1916
- if (webuiDevServer) return installRoot;
1917
-
1918
- throw makeHttpError(
1919
- 500,
1920
- `Could not determine a safe optional feature install root. Set ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} to the Pi package root.`,
1921
- );
1922
- }
1923
-
1924
1905
  function minimumPackageVersionFromSpec(spec) {
1925
1906
  const match = String(spec || "").match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/);
1926
1907
  return match?.[0] || "";
@@ -1984,33 +1965,124 @@ async function resolveInstalledPackageSubpath(packageName, subpath = "") {
1984
1965
  }
1985
1966
  }
1986
1967
 
1987
- function optionalFeatureDeclaredSpec(packageName) {
1988
- return declaredDependencySpec(packageJson, packageName) || "";
1968
+ function npmPackageNameFromPiSource(source) {
1969
+ const spec = String(source || "").trim();
1970
+ if (!spec.startsWith("npm:")) return "";
1971
+ const npmSpec = spec.slice("npm:".length);
1972
+ if (!npmSpec) return "";
1973
+ if (npmSpec.startsWith("@")) {
1974
+ const slashIndex = npmSpec.indexOf("/");
1975
+ if (slashIndex < 2) return "";
1976
+ const versionIndex = npmSpec.indexOf("@", slashIndex);
1977
+ return versionIndex === -1 ? npmSpec : npmSpec.slice(0, versionIndex);
1978
+ }
1979
+ const versionIndex = npmSpec.indexOf("@");
1980
+ return versionIndex === -1 ? npmSpec : npmSpec.slice(0, versionIndex);
1989
1981
  }
1990
1982
 
1991
- async function optionalFeaturePackageStatus(featureId) {
1992
- const packageName = OPTIONAL_FEATURE_PACKAGES.get(featureId);
1993
- if (!packageName) throw makeHttpError(400, `Unknown optional feature: ${featureId}`);
1994
- const declaredSpec = optionalFeatureDeclaredSpec(packageName);
1995
- const installedRoot = await resolveInstalledPackageRoot(packageName);
1983
+ async function configuredOptionalFeaturePackages(packageName, cwd = options.cwd) {
1984
+ const settingsManager = SettingsManager.create(cwd, agentDir);
1985
+ const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
1986
+ const matches = [];
1987
+ for (const configuredPackage of packageManager.listConfiguredPackages()) {
1988
+ if (npmPackageNameFromPiSource(configuredPackage.source) === packageName) {
1989
+ matches.push(configuredPackage);
1990
+ continue;
1991
+ }
1992
+ const manifest = configuredPackage.installedPath
1993
+ ? await readJsonFileIfExists(path.join(configuredPackage.installedPath, "package.json"))
1994
+ : null;
1995
+ if (manifest?.name === packageName) matches.push(configuredPackage);
1996
+ }
1997
+ return matches;
1998
+ }
1999
+
2000
+ async function topLevelOptionalFeatureResourceIndex(cwd = options.cwd) {
2001
+ const settingsManager = SettingsManager.create(cwd, agentDir);
2002
+ const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
2003
+ const resolved = await packageManager.resolve(async () => "skip");
2004
+ const resourcesByPackage = new Map();
2005
+ for (const resourceType of ["extensions", "skills", "prompts", "themes"]) {
2006
+ for (const resource of resolved[resourceType] || []) {
2007
+ if (!resource.enabled || resource.metadata?.origin === "package") continue;
2008
+ let ownershipPath = resource.path;
2009
+ try {
2010
+ ownershipPath = await realpath(resource.path);
2011
+ } catch {
2012
+ // Keep the reported path when the resource disappears during status collection.
2013
+ }
2014
+ const packageName = await packageNameForResourcePath(ownershipPath);
2015
+ if (!packageName) continue;
2016
+ const resourcePaths = resourcesByPackage.get(packageName) || [];
2017
+ resourcePaths.push(resource.path);
2018
+ resourcesByPackage.set(packageName, resourcePaths);
2019
+ }
2020
+ }
2021
+ return resourcesByPackage;
2022
+ }
2023
+
2024
+ async function topLevelOptionalFeatureResources(packageName, cwd = options.cwd, resourceIndex) {
2025
+ const resourcesByPackage = resourceIndex || await topLevelOptionalFeatureResourceIndex(cwd);
2026
+ return [...new Set(resourcesByPackage.get(packageName) || [])];
2027
+ }
2028
+
2029
+ async function installedOptionalFeatureRoot(packageName, configuredPackages) {
2030
+ const discoveredRoot = await resolveInstalledPackageRoot(packageName);
2031
+ const candidates = [discoveredRoot, ...configuredPackages.map(({ installedPath }) => installedPath)].filter(Boolean);
2032
+ for (const candidate of candidates) {
2033
+ const manifest = await readJsonFileIfExists(path.join(candidate, "package.json"));
2034
+ if (manifest?.name === packageName) return candidate;
2035
+ }
2036
+ return null;
2037
+ }
2038
+
2039
+ async function optionalFeaturePackageStatus(featureId, cwd = options.cwd, topLevelResourceIndex) {
2040
+ const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
2041
+ if (!feature) throw makeHttpError(400, `Unknown optional feature: ${featureId}`);
2042
+ const { packageName, expectedSpec } = feature;
2043
+ const [configuredPackages, topLevelResources] = await Promise.all([
2044
+ configuredOptionalFeaturePackages(packageName, cwd),
2045
+ topLevelOptionalFeatureResources(packageName, cwd, topLevelResourceIndex),
2046
+ ]);
2047
+ const installedRoot = await installedOptionalFeatureRoot(packageName, configuredPackages);
1996
2048
  const manifest = installedRoot ? await readJsonFileIfExists(path.join(installedRoot, "package.json")) : null;
1997
2049
  const installedVersion = typeof manifest?.version === "string" ? manifest.version : "";
1998
- const updateAvailable = !!(installedVersion && packageVersionBelowSpec(installedVersion, declaredSpec));
2050
+ const installed = !!installedRoot;
2051
+ const configured = configuredPackages.length > 0;
2052
+ const locallyConfigured = topLevelResources.length > 0;
2053
+ const legacyRoot = path.join(packageRoot, "node_modules", ...packageName.split("/"));
2054
+ const legacyManifest = await readJsonFileIfExists(path.join(legacyRoot, "package.json"));
2055
+ const legacyEvidence = legacyManifest?.name === packageName;
2056
+ const disabled = configuredPackages.length > 0 && configuredPackages.every((entry) => entry.enabled === false);
2057
+ const resourceConflict = configured && locallyConfigured;
2058
+ const ready = installed && (configured || locallyConfigured) && !resourceConflict;
2059
+ const updateAvailable = !!(installedVersion && packageVersionBelowSpec(installedVersion, expectedSpec));
1999
2060
  return {
2000
2061
  featureId,
2001
2062
  packageName,
2002
- declaredSpec,
2003
- installed: !!installedRoot,
2063
+ expectedSpec,
2064
+ declaredSpec: expectedSpec,
2065
+ installed,
2066
+ configured,
2067
+ locallyConfigured,
2068
+ resourceConflict,
2069
+ ready,
2004
2070
  installedVersion,
2005
2071
  installedRoot,
2072
+ topLevelResources,
2073
+ legacyEvidence,
2074
+ disabled,
2006
2075
  updateAvailable,
2007
- updateReason: updateAvailable ? `installed ${installedVersion} is older than Web UI expects (${declaredSpec})` : "",
2076
+ updateReason: updateAvailable ? `installed ${installedVersion} is older than Web UI expects (${expectedSpec})` : "",
2008
2077
  };
2009
2078
  }
2010
2079
 
2011
- async function optionalFeaturePackageStatuses() {
2080
+ async function optionalFeaturePackageStatuses(cwd = options.cwd) {
2012
2081
  const features = [];
2013
- for (const featureId of OPTIONAL_FEATURE_PACKAGES.keys()) features.push(await optionalFeaturePackageStatus(featureId));
2082
+ const topLevelResourceIndex = await topLevelOptionalFeatureResourceIndex(cwd);
2083
+ for (const { featureId } of OPTIONAL_FEATURE_CATALOG) {
2084
+ features.push(await optionalFeaturePackageStatus(featureId, cwd, topLevelResourceIndex));
2085
+ }
2014
2086
  return { features };
2015
2087
  }
2016
2088
 
@@ -2023,28 +2095,28 @@ function optionalFeatureInstallOutputTail(result, maxLength = 4000) {
2023
2095
  function optionalFeatureInstallFailureKind(result, message = "") {
2024
2096
  const combined = `${message}\n${result?.error || ""}\n${result?.stderr || ""}\n${result?.stdout || ""}`;
2025
2097
  if (result?.timedOut) return "timeout";
2026
- if (/\b(?:ENOENT|command not found|not recognized|spawn\s+\S+\s+ENOENT)\b/i.test(combined)) return "npm-not-found";
2098
+ if (/\b(?:ENOENT|command not found|not recognized|spawn\s+\S+\s+ENOENT)\b/i.test(combined)) return "pi-not-found";
2027
2099
  if (/\b(?:EACCES|EPERM|permission denied|access denied)\b/i.test(combined)) return "permission";
2028
2100
  if (/\b(?:EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT|network timeout|registry\.npmjs\.org|fetch failed)\b/i.test(combined)) return "network";
2029
- return "npm-exit";
2101
+ return "pi-exit";
2030
2102
  }
2031
2103
 
2032
- function optionalFeatureInstallFailureHint(kind, { command, installRoot } = {}) {
2104
+ function optionalFeatureInstallFailureHint(kind, { command } = {}) {
2033
2105
  switch (kind) {
2034
- case "install-root":
2035
- return `Set ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} to the Pi/Web UI npm package root, then retry.`;
2036
- case "npm-not-found":
2037
- return "npm could not be started. Install npm or set PI_WEBUI_NPM_BIN to an absolute npm-compatible executable path.";
2106
+ case "pi-not-found":
2107
+ return "The selected Pi CLI could not be started. Check --pi or PI_WEBUI_PI_BIN, then restart the Web UI.";
2038
2108
  case "permission":
2039
- return `The Web UI process cannot write to ${installRoot || "the selected npm prefix"}. Retry from the owning user or use ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} with a writable package root.`;
2109
+ return "Pi could not update its user package root or settings. Retry as the owning user or run the copied command manually.";
2040
2110
  case "network":
2041
- return "npm could not reach the registry reliably. Check network/proxy/registry settings, then retry or run the copied command manually.";
2111
+ return "Pi could not reach the npm registry reliably. Check network/proxy/registry settings, then retry or run the copied command manually.";
2042
2112
  case "timeout":
2043
- return "npm did not finish within 5 minutes. Check for a stuck package manager, lock contention, or slow network, then retry manually.";
2113
+ return "Pi did not finish within 5 minutes. Check for a stuck package manager, lock contention, or slow network, then retry manually.";
2114
+ case "local-resource-conflict":
2115
+ return "This companion is already enabled as a top-level Pi resource. Keep that local resource, or disable/remove its extensions/skills/prompts/themes alias before registering the npm package.";
2044
2116
  case "status-check":
2045
- return "npm finished, but Web UI could not verify the package status. Reload the Web UI and recheck Optional features.";
2117
+ return "Pi finished, but Web UI could not verify both installation and registration. Reload the Web UI and recheck Optional features.";
2046
2118
  default:
2047
- return command ? "Run the copied npm command manually on the Web UI host to see full package-manager diagnostics." : "Check the activity log and npm output, then retry.";
2119
+ return command ? "Run the copied Pi command manually on the Web UI host to see full diagnostics." : "Check the activity log and Pi output, then retry.";
2048
2120
  }
2049
2121
  }
2050
2122
 
@@ -2065,27 +2137,26 @@ function makeOptionalFeatureInstallError(statusCode, message, details = {}) {
2065
2137
  return error;
2066
2138
  }
2067
2139
 
2068
- async function installOptionalFeaturePackage(featureId) {
2069
- const beforeStatus = await optionalFeaturePackageStatus(featureId);
2140
+ async function installOptionalFeaturePackage(featureId, cwd = options.cwd) {
2141
+ const beforeStatus = await optionalFeaturePackageStatus(featureId, cwd);
2070
2142
  const packageName = beforeStatus.packageName;
2071
-
2072
- let installRoot;
2073
- try {
2074
- installRoot = await optionalDependencyInstallRoot();
2075
- } catch (error) {
2076
- const message = formatCliError(error);
2077
- throw makeOptionalFeatureInstallError(error?.statusCode || 500, message, {
2078
- kind: "install-root",
2143
+ const source = `npm:${packageName}`;
2144
+ if (beforeStatus.locallyConfigured) {
2145
+ const message = beforeStatus.resourceConflict
2146
+ ? `${packageName} is configured both as a Pi package and as a top-level resource; installing it again would preserve the duplicate-load conflict`
2147
+ : `${packageName} is already enabled as a top-level Pi resource; installing the npm package would load it twice`;
2148
+ throw makeOptionalFeatureInstallError(409, message, {
2149
+ kind: "local-resource-conflict",
2079
2150
  featureId,
2080
2151
  packageName,
2081
- hint: optionalFeatureInstallFailureHint("install-root"),
2152
+ command: `pi install ${source}`,
2153
+ hint: optionalFeatureInstallFailureHint("local-resource-conflict"),
2082
2154
  });
2083
2155
  }
2084
-
2085
- const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, packageName]);
2086
- const command = npmCommand.displayCommand;
2087
- const result = await runCommand(npmCommand.command, npmCommand.args, {
2088
- cwd: installRoot,
2156
+ const piCommand = await resolvePiCommand(["install", source]);
2157
+ const command = piCommand.displayCommand;
2158
+ const result = await runCommand(piCommand.command, piCommand.args, {
2159
+ cwd,
2089
2160
  timeoutMs: 5 * 60 * 1000,
2090
2161
  maxOutputLength: 80000,
2091
2162
  });
@@ -2101,40 +2172,167 @@ async function installOptionalFeaturePackage(featureId) {
2101
2172
  kind,
2102
2173
  featureId,
2103
2174
  packageName,
2104
- installRoot,
2105
2175
  command,
2106
2176
  exitCode: result.exitCode,
2107
2177
  timedOut: result.timedOut,
2108
2178
  outputTail: optionalFeatureInstallOutputTail(result),
2109
2179
  });
2110
2180
  }
2181
+
2111
2182
  let afterStatus;
2112
2183
  try {
2113
- afterStatus = await optionalFeaturePackageStatus(featureId);
2184
+ afterStatus = await optionalFeaturePackageStatus(featureId, cwd);
2185
+ if (!afterStatus.ready) {
2186
+ throw new Error(`Pi did not leave ${packageName} both installed and registered`);
2187
+ }
2114
2188
  } catch (error) {
2115
2189
  const message = `Optional feature install finished, but status verification failed: ${formatCliError(error)}`;
2116
2190
  throw makeOptionalFeatureInstallError(error?.statusCode || 500, message, {
2117
2191
  kind: "status-check",
2118
2192
  featureId,
2119
2193
  packageName,
2120
- installRoot,
2121
2194
  command,
2122
2195
  outputTail: optionalFeatureInstallOutputTail(result),
2123
2196
  });
2124
2197
  }
2125
- const operation = beforeStatus.installed ? "Updated" : "Installed";
2198
+
2199
+ const operation = beforeStatus.ready ? "Updated" : beforeStatus.installed ? "Registered" : "Installed";
2126
2200
  return {
2127
2201
  featureId,
2128
2202
  packageName,
2129
- installRoot,
2203
+ source,
2130
2204
  command,
2131
2205
  stdout: result.stdout,
2132
2206
  stderr: result.stderr,
2133
2207
  status: afterStatus,
2134
- message: `${operation} optional feature package ${packageName}${afterStatus.installedVersion ? ` to ${afterStatus.installedVersion}` : ""}. Reload the active Pi tab to load new resources.`,
2208
+ message: `${operation} optional feature package ${packageName}${afterStatus.installedVersion ? ` at ${afterStatus.installedVersion}` : ""} with Pi. Reload the active Pi tab to load new resources.`,
2209
+ };
2210
+ }
2211
+
2212
+ function validateOptionalFeatureBatch(featureIds) {
2213
+ if (!Array.isArray(featureIds)) throw makeHttpError(400, "featureIds must be an array");
2214
+ if (featureIds.length > OPTIONAL_FEATURE_CATALOG.length) {
2215
+ throw makeHttpError(400, `featureIds must contain at most ${OPTIONAL_FEATURE_CATALOG.length} entries`);
2216
+ }
2217
+ const deduplicated = [];
2218
+ const seen = new Set();
2219
+ for (const value of featureIds) {
2220
+ if (typeof value !== "string" || !OPTIONAL_FEATURE_BY_ID.has(value)) {
2221
+ throw makeHttpError(400, `Unknown optional feature: ${String(value || "")}`);
2222
+ }
2223
+ if (seen.has(value)) continue;
2224
+ seen.add(value);
2225
+ deduplicated.push(value);
2226
+ }
2227
+ return deduplicated;
2228
+ }
2229
+
2230
+ async function installOptionalFeaturePackages(featureIds, cwd = options.cwd) {
2231
+ const requestedFeatureIds = validateOptionalFeatureBatch(featureIds);
2232
+ const results = [];
2233
+ const startedAtMs = Date.now();
2234
+ const startedAt = new Date(startedAtMs).toISOString();
2235
+ const migration = optionalFeatureAuditCoordinator.current().progress?.migration === true;
2236
+ let index = 0;
2237
+ for (const featureId of requestedFeatureIds) {
2238
+ const packageName = OPTIONAL_FEATURE_BY_ID.get(featureId)?.packageName || "";
2239
+ optionalFeatureAuditCoordinator.setProgress({
2240
+ phase: "migrating",
2241
+ migration,
2242
+ startedAt,
2243
+ elapsedMs: Date.now() - startedAtMs,
2244
+ currentFeatureId: featureId,
2245
+ currentPackageName: packageName,
2246
+ index: index + 1,
2247
+ total: requestedFeatureIds.length,
2248
+ completed: index,
2249
+ remaining: requestedFeatureIds.length - index,
2250
+ results: results.map(optionalFeatureProgressResult),
2251
+ });
2252
+ try {
2253
+ results.push({ ok: true, featureId, data: await installOptionalFeaturePackage(featureId, cwd) });
2254
+ } catch (error) {
2255
+ results.push({
2256
+ ok: false,
2257
+ featureId,
2258
+ packageName,
2259
+ error: formatCliError(error),
2260
+ optionalFeatureInstall: error?.optionalFeatureInstall || null,
2261
+ });
2262
+ }
2263
+ index++;
2264
+ }
2265
+ const succeeded = results.filter((result) => result.ok).length;
2266
+ return {
2267
+ featureIds: requestedFeatureIds,
2268
+ results,
2269
+ total: results.length,
2270
+ succeeded,
2271
+ failed: results.length - succeeded,
2135
2272
  };
2136
2273
  }
2137
2274
 
2275
+ function optionalFeatureProgressResult(result) {
2276
+ return {
2277
+ featureId: result.featureId,
2278
+ packageName: result.packageName || result.data?.packageName || "",
2279
+ ok: result.ok,
2280
+ kind: result.optionalFeatureInstall?.kind || "",
2281
+ message: result.ok ? result.data?.message || "Installed and verified" : "Installation failed; see the localhost response for details",
2282
+ };
2283
+ }
2284
+
2285
+ async function runOptionalFeatureBatchMutation({ revision, featureIds, cwd = options.cwd, migration = false, tab = null, install = null }) {
2286
+ return optionalFeatureAuditCoordinator.runMutation(revision, async () => {
2287
+ optionalFeatureAuditCoordinator.setProgress({ phase: "migrating", migration, startedAt: new Date().toISOString(), completed: 0, remaining: Array.isArray(featureIds) ? featureIds.length : 0, total: Array.isArray(featureIds) ? featureIds.length : 0, results: [] });
2288
+ const batch = install ? await install() : await installOptionalFeaturePackages(featureIds, cwd);
2289
+ if (migration && batch.failed === 0) await optionalFeatureMigrationStore.completeMigration();
2290
+ await optionalFeatureAuditCoordinator.recheck({ reason: migration ? "post-migration" : "post-install" });
2291
+ const restart = { autoRestarted: false, restartDeferred: false };
2292
+ if (batch.failed === 0 && batch.total > 0 && tab) {
2293
+ const busy = tab.activity?.isWorking === true
2294
+ || pendingExtensionUiRequests(tab).length > 0
2295
+ || (tab.browserPromptRequests?.size || 0) > 0
2296
+ || (tab.bashQueue?.length || 0) > 0
2297
+ || (tab.compactionQueue?.length || 0) > 0;
2298
+ if (busy) {
2299
+ restart.restartDeferred = true;
2300
+ } else {
2301
+ try {
2302
+ await restartTabRpc(tab, "optional-feature-migration");
2303
+ restart.autoRestarted = true;
2304
+ } catch (error) {
2305
+ restart.restartDeferred = true;
2306
+ restart.reason = error?.statusCode === 409 ? "tab-busy" : "restart-failed";
2307
+ }
2308
+ }
2309
+ broadcastTabEvent(tab, {
2310
+ type: restart.autoRestarted ? "webui_optional_feature_restart_completed" : "webui_optional_feature_restart_deferred",
2311
+ tabId: tab.id,
2312
+ tabTitle: tab.title,
2313
+ ...restart,
2314
+ });
2315
+ }
2316
+ batch.restart = restart;
2317
+ optionalFeatureAuditCoordinator.setProgress({
2318
+ phase: batch.failed ? "partial" : "complete",
2319
+ migration,
2320
+ completedAt: new Date().toISOString(),
2321
+ currentFeatureId: null,
2322
+ currentPackageName: null,
2323
+ index: batch.total,
2324
+ total: batch.total,
2325
+ completed: batch.total,
2326
+ remaining: 0,
2327
+ succeeded: batch.succeeded,
2328
+ failed: batch.failed,
2329
+ results: batch.results.map(optionalFeatureProgressResult),
2330
+ ...restart,
2331
+ });
2332
+ return batch;
2333
+ });
2334
+ }
2335
+
2138
2336
  function displayPath(cwd) {
2139
2337
  const normalized = cwd.replace(/\\/g, "/");
2140
2338
  const home = (process.env.USERPROFILE || process.env.HOME || "").replace(/\\/g, "/");
@@ -2292,6 +2490,15 @@ function requireWorkflowPolicyJsonRequest(req) {
2292
2490
  }
2293
2491
  }
2294
2492
 
2493
+ function requireSessionSummaryJsonRequest(req) {
2494
+ const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
2495
+ if (contentType !== "application/json") throw makeHttpError(415, "Session summary changes require Content-Type: application/json.");
2496
+ const fetchSite = String(req.headers["sec-fetch-site"] || "").trim().toLowerCase();
2497
+ if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none") {
2498
+ throw makeHttpError(403, "Cross-origin session summary changes are blocked.");
2499
+ }
2500
+ }
2501
+
2295
2502
  function workflowPolicySaveBody(body) {
2296
2503
  if (!body || typeof body !== "object" || Array.isArray(body)) {
2297
2504
  throw makeHttpError(400, "Workflow policy save body must be an object with only policy and expectedRevision.");
@@ -2557,6 +2764,172 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
2557
2764
  return gitWorkflowPreferencesData(tab);
2558
2765
  }
2559
2766
 
2767
+ function sessionSummaryModelKey(model) {
2768
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
2769
+ }
2770
+
2771
+ async function availableSessionSummaryModels(tab) {
2772
+ const models = await availableGitWorkflowModels(tab);
2773
+ return models.map((model) => ({
2774
+ provider: model.provider,
2775
+ id: model.id,
2776
+ ...(model.name ? { name: String(model.name).slice(0, 240) } : {}),
2777
+ reasoning: model.reasoning === true,
2778
+ ...(model.thinkingLevelMap && typeof model.thinkingLevelMap === "object" ? { thinkingLevelMap: model.thinkingLevelMap } : {}),
2779
+ }));
2780
+ }
2781
+
2782
+ function publicSessionSummaryPreferences(value) {
2783
+ return {
2784
+ version: 1,
2785
+ configured: value?.configured === true,
2786
+ enabled: value?.enabled === true,
2787
+ model: {
2788
+ provider: String(value?.model?.provider || ""),
2789
+ modelId: String(value?.model?.modelId || ""),
2790
+ thinkingLevel: String(value?.model?.thinkingLevel || "off"),
2791
+ },
2792
+ prompts: {
2793
+ title: String(value?.prompts?.title || "").slice(0, SESSION_SUMMARY_PROMPT_MAX_CHARS),
2794
+ summary: String(value?.prompts?.summary || "").slice(0, SESSION_SUMMARY_PROMPT_MAX_CHARS),
2795
+ },
2796
+ input: { scope: "text-and-tool-names" },
2797
+ context: { injectLatest: value?.context?.injectLatest === true },
2798
+ title: {
2799
+ enabled: value?.title?.enabled !== false,
2800
+ minSettledTurns: Number.isInteger(value?.title?.minSettledTurns) ? value.title.minSettledTurns : 3,
2801
+ },
2802
+ };
2803
+ }
2804
+
2805
+ async function sessionSummaryPreferencesData(tab) {
2806
+ const [storedPreferences, models] = await Promise.all([
2807
+ readSessionSummaryPreferences(),
2808
+ availableSessionSummaryModels(tab),
2809
+ ]);
2810
+ return {
2811
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2812
+ preferences: publicSessionSummaryPreferences(storedPreferences),
2813
+ models,
2814
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [sessionSummaryModelKey(model), supportedSessionSummaryThinkingLevels(model)])),
2815
+ disclosure: {
2816
+ scope: "Active-branch user text, final assistant text, and tool names only. Thinking, images, tool arguments/results, credentials, and prior summary messages are excluded.",
2817
+ cost: "Automatic generation makes one request to the selected model after each eligible settled refresh. There is no provider fallback or automatic provider retry.",
2818
+ persistence: "Preferences and generated output are stored locally. Main-agent context injection is off unless explicitly enabled.",
2819
+ },
2820
+ summary: publicSessionSummaryState(tab),
2821
+ };
2822
+ }
2823
+
2824
+ function requiredSessionSummaryObject(value, label, allowedKeys) {
2825
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw makeHttpError(400, `${label} must be an object`);
2826
+ const unexpected = Object.keys(value).filter((key) => !allowedKeys.includes(key));
2827
+ if (unexpected.length) throw makeHttpError(400, `${label} contains unsupported field${unexpected.length === 1 ? "" : "s"}: ${unexpected.join(", ")}`);
2828
+ return value;
2829
+ }
2830
+
2831
+ function requiredSessionSummaryBoolean(value, label) {
2832
+ if (typeof value !== "boolean") throw makeHttpError(400, `${label} must be true or false`);
2833
+ return value;
2834
+ }
2835
+
2836
+ function requiredSessionSummaryPrompt(value, label) {
2837
+ if (typeof value !== "string") throw makeHttpError(400, `${label} must be a string`);
2838
+ const prompt = value.trim();
2839
+ if (!prompt) throw makeHttpError(400, `${label} must not be empty`);
2840
+ if (prompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS) throw makeHttpError(400, `${label} must not exceed 8 KiB`);
2841
+ return prompt;
2842
+ }
2843
+
2844
+ async function saveSessionSummaryPreferencesData(tab, body = {}) {
2845
+ requiredSessionSummaryObject(body, "request", ["confirmed", "preferences", "tab"]);
2846
+ if (body.confirmed !== true) throw makeHttpError(409, "Session summary setup requires explicit privacy and cost confirmation (confirmed: true).");
2847
+ const submitted = requiredSessionSummaryObject(body.preferences, "preferences", ["enabled", "model", "prompts", "input", "context", "title"]);
2848
+ const submittedModel = requiredSessionSummaryObject(submitted.model, "preferences.model", ["provider", "modelId", "thinkingLevel"]);
2849
+ const submittedPrompts = requiredSessionSummaryObject(submitted.prompts, "preferences.prompts", ["title", "summary"]);
2850
+ const submittedInput = requiredSessionSummaryObject(submitted.input, "preferences.input", ["scope"]);
2851
+ const submittedContext = requiredSessionSummaryObject(submitted.context, "preferences.context", ["injectLatest"]);
2852
+ const submittedTitle = requiredSessionSummaryObject(submitted.title, "preferences.title", ["enabled", "minSettledTurns"]);
2853
+ const provider = String(submittedModel.provider || "").trim();
2854
+ const modelId = String(submittedModel.modelId || "").trim();
2855
+ const thinkingLevel = String(submittedModel.thinkingLevel || "").trim();
2856
+ if (!provider || provider.length > 160 || !modelId || modelId.length > 512) throw makeHttpError(400, "Select an available session summary model");
2857
+ const models = await availableSessionSummaryModels(tab);
2858
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
2859
+ if (!model) throw makeHttpError(400, `Selected session summary model is not currently available: ${provider}/${modelId}`);
2860
+ const supportedLevels = supportedSessionSummaryThinkingLevels(model);
2861
+ if (!supportedLevels.includes(thinkingLevel)) throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${thinkingLevel}`);
2862
+ if (submittedInput.scope !== "text-and-tool-names") throw makeHttpError(400, "input.scope must be text-and-tool-names");
2863
+ const minSettledTurns = Number(submittedTitle.minSettledTurns);
2864
+ if (!Number.isInteger(minSettledTurns) || minSettledTurns < 1 || minSettledTurns > 20) throw makeHttpError(400, "title.minSettledTurns must be an integer from 1 to 20");
2865
+
2866
+ const saved = await writeSessionSummaryPreferences({
2867
+ configured: true,
2868
+ enabled: requiredSessionSummaryBoolean(submitted.enabled, "enabled"),
2869
+ model: { provider, modelId, thinkingLevel },
2870
+ prompts: {
2871
+ title: requiredSessionSummaryPrompt(submittedPrompts.title, "prompts.title"),
2872
+ summary: requiredSessionSummaryPrompt(submittedPrompts.summary, "prompts.summary"),
2873
+ },
2874
+ input: { scope: "text-and-tool-names" },
2875
+ context: { injectLatest: requiredSessionSummaryBoolean(submittedContext.injectLatest, "context.injectLatest") },
2876
+ title: {
2877
+ enabled: requiredSessionSummaryBoolean(submittedTitle.enabled, "title.enabled"),
2878
+ minSettledTurns,
2879
+ },
2880
+ });
2881
+ tab.sessionSummary = {
2882
+ ...(tab.sessionSummary || {}),
2883
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2884
+ status: tab.sessionSummary?.status || "idle",
2885
+ configured: true,
2886
+ enabled: saved.enabled === true,
2887
+ durable: tab.sessionSummary?.durable === true,
2888
+ updatedAt: new Date().toISOString(),
2889
+ };
2890
+ broadcastSessionSummaryState(tab, "setup");
2891
+ return sessionSummaryPreferencesData(tab);
2892
+ }
2893
+
2894
+ async function triggerSessionSummary(tab, { refresh = false } = {}) {
2895
+ const preferences = await readSessionSummaryPreferences();
2896
+ if (!preferences.configured) throw makeHttpError(409, "Session summary setup must be confirmed before generation.");
2897
+ const commands = await safeRpcData(tab, { type: "get_commands" }, STATUS_RPC_TIMEOUT_MS);
2898
+ const available = Array.isArray(commands.data?.commands) && commands.data.commands.some((command) => String(command?.name || "").replace(/:\d+$/, "") === "summary");
2899
+ if (!commands.ok || !available) throw makeHttpError(409, "The /summary extension command is not loaded in this Pi tab. Reload the tab and retry.");
2900
+ tab.sessionSummary = {
2901
+ ...(tab.sessionSummary || {}),
2902
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2903
+ status: "generating",
2904
+ configured: true,
2905
+ message: "",
2906
+ updatedAt: new Date().toISOString(),
2907
+ };
2908
+ broadcastSessionSummaryState(tab, "generating");
2909
+ try {
2910
+ const response = await tab.rpc.send(
2911
+ { type: "prompt", message: refresh ? "/summary refresh" : "/summary" },
2912
+ SESSION_SUMMARY_GENERATE_TIMEOUT_MS,
2913
+ );
2914
+ if (response.success === false) throw makeHttpError(400, response.error || "Session summary generation failed");
2915
+ return { requested: true, refresh: refresh === true, summary: publicSessionSummaryState(tab), tab: tabMeta(tab) };
2916
+ } catch (error) {
2917
+ const message = (sanitizeError(error) || "Session summary generation failed")
2918
+ .replace(/[\r\n]+/g, " ")
2919
+ .slice(0, SESSION_SUMMARY_FAILURE_MAX_CHARS)
2920
+ .trim();
2921
+ tab.sessionSummary = {
2922
+ ...(tab.sessionSummary || {}),
2923
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
2924
+ status: "failure",
2925
+ message: message || "Session summary generation failed",
2926
+ updatedAt: new Date().toISOString(),
2927
+ };
2928
+ broadcastSessionSummaryState(tab, "failure");
2929
+ throw error;
2930
+ }
2931
+ }
2932
+
2560
2933
  function gitWorkflowGenerationPrompt(kind, preferences) {
2561
2934
  switch (kind) {
2562
2935
  case "commit":
@@ -8398,7 +8771,14 @@ function readSupervisorCursorFromEnv() {
8398
8771
  }
8399
8772
 
8400
8773
  async function packageNameForResourcePath(resourcePath) {
8401
- let current = path.dirname(resourcePath);
8774
+ let canonicalResourcePath = resourcePath;
8775
+ try {
8776
+ canonicalResourcePath = await realpath(resourcePath);
8777
+ } catch {
8778
+ // Keep lexical lookup for missing or virtual resources.
8779
+ }
8780
+
8781
+ let current = path.dirname(canonicalResourcePath);
8402
8782
  while (current && current !== path.dirname(current)) {
8403
8783
  if (PACKAGE_NAME_CACHE.has(current)) return PACKAGE_NAME_CACHE.get(current) || undefined;
8404
8784
  try {
@@ -8469,7 +8849,7 @@ function parseNodeModulesPackageRef(manifestEntry) {
8469
8849
 
8470
8850
  async function resolveStartedWebuiManifestResource(manifestEntry) {
8471
8851
  const nodeModulesRef = parseNodeModulesPackageRef(manifestEntry);
8472
- if (nodeModulesRef && WEBUI_CONTROLLED_PACKAGES.has(nodeModulesRef.packageName)) {
8852
+ if (nodeModulesRef && WEBUI_RESOURCE_EXCLUDED_PACKAGES.has(nodeModulesRef.packageName)) {
8473
8853
  const installedCandidate = await resolveInstalledPackageSubpath(nodeModulesRef.packageName, nodeModulesRef.subpath);
8474
8854
  if (installedCandidate) return installedCandidate;
8475
8855
  }
@@ -8518,10 +8898,15 @@ async function resolvedNormalPiResourcesForTab(cwd) {
8518
8898
  async function normalPiResourcePathsForTab(resolved, resourceType) {
8519
8899
  if (piArgsDisableResourceDiscovery(resourceType)) return [];
8520
8900
  const resourcePaths = [];
8901
+ const auditExcludedPackages = optionalFeatureAuditCoordinator?.excludedPackageNames?.() || new Set();
8902
+ const coreOnly = optionalFeatureAuditCoordinator?.current?.().phase === "checking" || optionalFeatureAuditCoordinator?.current?.().phase === "degraded";
8521
8903
  for (const resource of resolved[resourceType] || []) {
8522
8904
  if (!resource.enabled) continue;
8523
8905
  const packageName = await packageNameForResourcePath(resource.path);
8524
- if (packageName && WEBUI_CONTROLLED_PACKAGES.has(packageName)) continue;
8906
+ if (packageName && WEBUI_RESOURCE_EXCLUDED_PACKAGES.has(packageName)) continue;
8907
+ if (packageName && auditExcludedPackages.has(packageName)) {
8908
+ if (coreOnly || resource.metadata?.origin !== "package") continue;
8909
+ }
8525
8910
  resourcePaths.push(resource.path);
8526
8911
  }
8527
8912
  return resourcePaths;
@@ -8546,6 +8931,11 @@ async function buildPiArgsForTab(tabIndex, title, tabCwd = options.cwd) {
8546
8931
  await appendCuratedResourceArgs(args, normalResources, "prompts", "--prompt-template");
8547
8932
  await appendCuratedResourceArgs(args, normalResources, "themes", "--theme");
8548
8933
 
8934
+ // The package manifest is resolved above, but keep session-summary explicit:
8935
+ // curated child discovery intentionally excludes package-owned resources in
8936
+ // some installations. Avoid a duplicate when the manifest path was retained.
8937
+ if (!args.includes(sessionSummaryExtensionPath)) args.push("--extension", sessionSummaryExtensionPath);
8938
+
8549
8939
  // Load a browser-safe RPC helper into every Web UI tab. It exposes hidden
8550
8940
  // extension commands for Web UI-native /tools and /skills selectors without
8551
8941
  // depending on TUI-only extension UIs.
@@ -8935,6 +9325,133 @@ function clearExtensionWidgets(tab) {
8935
9325
  tab?.extensionWidgets?.clear();
8936
9326
  }
8937
9327
 
9328
+ function normalizedSessionSummaryTitle(value) {
9329
+ if (typeof value !== "string" || value.length > SESSION_SUMMARY_TITLE_MAX_CHARS) return "";
9330
+ const title = value.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
9331
+ return title.length <= SESSION_SUMMARY_TITLE_MAX_CHARS ? title : "";
9332
+ }
9333
+
9334
+ function normalizedSessionSummaryRpcDetails(value) {
9335
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.version !== SESSION_SUMMARY_PROTOCOL_VERSION) return null;
9336
+ const kind = String(value.kind || "");
9337
+ if (!SESSION_SUMMARY_KINDS.has(kind)) return null;
9338
+ const details = { version: SESSION_SUMMARY_PROTOCOL_VERSION, kind };
9339
+ if (value.sessionId !== undefined) {
9340
+ if (typeof value.sessionId !== "string" || value.sessionId.length > 128) return null;
9341
+ details.sessionId = value.sessionId;
9342
+ }
9343
+ if (value.title !== undefined) {
9344
+ const title = normalizedSessionSummaryTitle(value.title);
9345
+ if (!title) return null;
9346
+ details.title = title;
9347
+ }
9348
+ if (value.summaryMarkdown !== undefined) {
9349
+ if (typeof value.summaryMarkdown !== "string" || !value.summaryMarkdown.trim() || value.summaryMarkdown.length > SESSION_SUMMARY_MARKDOWN_MAX_CHARS) return null;
9350
+ details.summaryMarkdown = value.summaryMarkdown.trim();
9351
+ }
9352
+ if (value.message !== undefined) {
9353
+ if (typeof value.message !== "string" || value.message.length > SESSION_SUMMARY_FAILURE_MAX_CHARS) return null;
9354
+ details.message = value.message.replace(/[\r\n]+/g, " ").trim();
9355
+ }
9356
+ for (const key of ["configured", "enabled", "durable"]) {
9357
+ if (value[key] !== undefined) {
9358
+ if (typeof value[key] !== "boolean") return null;
9359
+ details[key] = value[key];
9360
+ }
9361
+ }
9362
+ if ((kind === "success" && !details.summaryMarkdown) || (kind === "failure" && !details.message) || (kind === "title" && !details.title)) return null;
9363
+ return details;
9364
+ }
9365
+
9366
+ function publicSessionSummaryState(tab) {
9367
+ const value = tab?.sessionSummary;
9368
+ if (!value) return null;
9369
+ return {
9370
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
9371
+ status: value.status || "idle",
9372
+ configured: value.configured === true,
9373
+ enabled: value.enabled === true,
9374
+ durable: value.durable === true,
9375
+ ...(value.sessionId ? { sessionId: value.sessionId } : {}),
9376
+ ...(value.title ? { title: value.title } : {}),
9377
+ ...(value.summaryMarkdown ? { summaryMarkdown: value.summaryMarkdown } : {}),
9378
+ ...(value.message ? { message: value.message } : {}),
9379
+ updatedAt: value.updatedAt || new Date(0).toISOString(),
9380
+ };
9381
+ }
9382
+
9383
+ function broadcastSessionSummaryState(tab, kind) {
9384
+ broadcastTabEvent(tab, {
9385
+ type: "webui_session_summary",
9386
+ kind,
9387
+ tabId: tab.id,
9388
+ tabTitle: tab.title,
9389
+ summary: publicSessionSummaryState(tab),
9390
+ });
9391
+ }
9392
+
9393
+ function applySessionSummaryRpcDetails(tab, details) {
9394
+ const previous = tab.sessionSummary?.sessionId && details.sessionId && tab.sessionSummary.sessionId !== details.sessionId
9395
+ ? null
9396
+ : tab.sessionSummary;
9397
+ const next = {
9398
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
9399
+ status: previous?.status || "idle",
9400
+ configured: previous?.configured === true,
9401
+ enabled: previous?.enabled === true,
9402
+ durable: previous?.durable === true,
9403
+ sessionId: details.sessionId || previous?.sessionId || "",
9404
+ title: previous?.title || "",
9405
+ summaryMarkdown: previous?.summaryMarkdown || "",
9406
+ message: "",
9407
+ updatedAt: new Date().toISOString(),
9408
+ };
9409
+ if (details.configured !== undefined) next.configured = details.configured;
9410
+ if (details.enabled !== undefined) next.enabled = details.enabled;
9411
+ if (details.durable !== undefined) next.durable = details.durable;
9412
+ if (details.kind === "state") {
9413
+ next.status = details.summaryMarkdown ? "success" : "idle";
9414
+ next.title = details.title || "";
9415
+ next.summaryMarkdown = details.summaryMarkdown || "";
9416
+ } else if (details.kind === "setup") {
9417
+ next.status = "idle";
9418
+ } else if (details.kind === "generating") {
9419
+ next.status = "generating";
9420
+ } else if (details.kind === "success") {
9421
+ next.status = "success";
9422
+ next.title = details.title || next.title;
9423
+ next.summaryMarkdown = details.summaryMarkdown;
9424
+ } else if (details.kind === "failure") {
9425
+ next.status = "failure";
9426
+ next.message = details.message;
9427
+ } else if (details.kind === "title") {
9428
+ next.title = details.title;
9429
+ if (tab.titleSource === "default" || tab.titleSource === "auto") {
9430
+ renameTab(tab, details.title, { source: "auto", maxLength: SESSION_SUMMARY_TITLE_MAX_CHARS });
9431
+ }
9432
+ }
9433
+ tab.sessionSummary = next;
9434
+ broadcastSessionSummaryState(tab, details.kind);
9435
+ }
9436
+
9437
+ function consumeSessionSummaryRpcEvent(tab, event) {
9438
+ const message = event?.message;
9439
+ if ((event?.type !== "message_start" && event?.type !== "message_end") || message?.role !== "custom") return false;
9440
+ if (message.customType === SESSION_SUMMARY_DISPLAY_TYPE) return true;
9441
+ if (message.customType !== SESSION_SUMMARY_RPC_TYPE) return false;
9442
+ if (event.type === "message_end") {
9443
+ const details = normalizedSessionSummaryRpcDetails(message.details);
9444
+ if (details) applySessionSummaryRpcDetails(tab, details);
9445
+ }
9446
+ return true;
9447
+ }
9448
+
9449
+ function filterSessionSummaryTranscriptMessages(messages) {
9450
+ return (Array.isArray(messages) ? messages : []).filter((message) => !(
9451
+ message?.role === "custom" && (message.customType === SESSION_SUMMARY_RPC_TYPE || message.customType === SESSION_SUMMARY_DISPLAY_TYPE)
9452
+ ));
9453
+ }
9454
+
8938
9455
  function clearWebuiSubagents(tab) {
8939
9456
  if (tab) tab.webuiSubagents = null;
8940
9457
  }
@@ -9806,7 +10323,7 @@ function attachRpcToTab(tab, rpc) {
9806
10323
  tab.rpc = rpc;
9807
10324
  tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
9808
10325
  const event = tab.thinkingStreamRecovery.ingest(rawEvent);
9809
- if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
10326
+ if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event) || consumeSessionSummaryRpcEvent(tab, event)) return;
9810
10327
  updateTabActivityFromEvent(tab, event);
9811
10328
  let scopedEvent = eventForTabClients(tab, event);
9812
10329
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
@@ -9852,6 +10369,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9852
10369
  pendingExtensionUiRequests: new Map(),
9853
10370
  extensionStatuses: new Map(),
9854
10371
  extensionWidgets: new Map(),
10372
+ sessionSummary: null,
9855
10373
  webuiSubagents: null,
9856
10374
  subagentDisplayTitle: undefined,
9857
10375
  subagentDisplayTitlePromise: undefined,
@@ -10010,6 +10528,7 @@ function tabMeta(tab) {
10010
10528
  activity: tabActivitySnapshot(tab),
10011
10529
  appRunner: publicAppRunnerState(tab.appRunner),
10012
10530
  conversationMode: naturalConversationModeSnapshot(tab),
10531
+ sessionSummary: publicSessionSummaryState(tab),
10013
10532
  };
10014
10533
  }
10015
10534
 
@@ -10622,6 +11141,7 @@ function packageNodeModulesPath(nodeModulesRoot, packageName) {
10622
11141
 
10623
11142
  function isWebuiOrPiPackageName(packageName) {
10624
11143
  const name = String(packageName || "").trim();
11144
+ if (OPTIONAL_FEATURE_PACKAGE_NAMES.has(name)) return false;
10625
11145
  return UPDATE_PACKAGE_NAMES.includes(name)
10626
11146
  || /^@firstpick\/pi(?:-|$)/.test(name)
10627
11147
  || /^@earendil-works\/pi(?:-|$)/.test(name)
@@ -10938,8 +11458,18 @@ function componentUpdateSuccessMessage(target) {
10938
11458
  return "Web UI update completed. Restart the Web UI to use the update.";
10939
11459
  }
10940
11460
 
11461
+ async function persistOptionalFeaturePendingUpgrade() {
11462
+ optionalFeatureAuditCoordinator.assertIdle();
11463
+ const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-update" });
11464
+ const featureIds = snapshot.features
11465
+ .filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
11466
+ .map(({ featureId }) => featureId);
11467
+ await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
11468
+ }
11469
+
10941
11470
  async function runComponentUpdate(target) {
10942
11471
  try {
11472
+ if (target === "webui") await persistOptionalFeaturePendingUpgrade();
10943
11473
  const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
10944
11474
  if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
10945
11475
  const command = updateTasks.map(updateTaskDisplay).join(" && ");
@@ -10973,6 +11503,7 @@ async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
10973
11503
  piUpdateInProgress = true;
10974
11504
  let restartPrepared = false;
10975
11505
  try {
11506
+ if (all) await persistOptionalFeaturePendingUpgrade();
10976
11507
  const restorableTabs = await restorableTabsForRestart();
10977
11508
  const updateTasks = await resolveUpdateTasks({ all });
10978
11509
  if (!updateTasks.length) throw makeHttpError(500, "No Pi update command could be resolved.");
@@ -11278,7 +11809,10 @@ async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
11278
11809
  try {
11279
11810
  const response = rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
11280
11811
  if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
11281
- response.data = { ...response.data, messages: tab.thinkingStreamRecovery.applyToMessages(response.data.messages) };
11812
+ response.data = {
11813
+ ...response.data,
11814
+ messages: filterSessionSummaryTranscriptMessages(tab.thinkingStreamRecovery.applyToMessages(response.data.messages)),
11815
+ };
11282
11816
  }
11283
11817
  return response;
11284
11818
  } catch (error) {
@@ -13601,12 +14135,16 @@ const serverStartedAt = new Date().toISOString();
13601
14135
  const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
13602
14136
  let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
13603
14137
  let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
13604
- rpcSupervisor = await initializeRpcSupervisor();
13605
- rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
13606
- installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
13607
- const initialTabs = await createInitialTabs();
13608
- await finishRpcSupervisorStartup(initialTabs);
13609
- const initialTab = initialTabs[0];
14138
+ optionalFeatureMigrationStore = new OptionalFeatureMigrationStore({
14139
+ filePath: process.env.PI_WEBUI_OPTIONAL_FEATURE_MIGRATION_FILE || path.join(agentDir, "webui", "optional-feature-migration.json"),
14140
+ });
14141
+ optionalFeatureAuditCoordinator = new OptionalFeatureAuditCoordinator({
14142
+ catalog: OPTIONAL_FEATURE_CATALOG,
14143
+ collectStatuses: async () => (await optionalFeaturePackageStatuses(options.cwd)).features,
14144
+ store: optionalFeatureMigrationStore,
14145
+ webuiVersion: packageJson.version,
14146
+ onEvent: (event) => broadcastServerEvent(event),
14147
+ });
13610
14148
  let currentHost = options.host;
13611
14149
  let networkRebindInProgress = false;
13612
14150
  let networkRebindTargetHost = null;
@@ -14250,6 +14788,30 @@ const server = createServer(async (req, res) => {
14250
14788
  return;
14251
14789
  }
14252
14790
 
14791
+ if (url.pathname === "/api/session-summary/preferences" && req.method === "GET") {
14792
+ const tab = getRequestedTab(req, url);
14793
+ sendJson(res, 200, { ok: true, data: await sessionSummaryPreferencesData(tab) }, { "cache-control": "private, no-store" });
14794
+ return;
14795
+ }
14796
+
14797
+ if (url.pathname === "/api/session-summary/preferences" && req.method === "PUT") {
14798
+ requireSessionSummaryJsonRequest(req);
14799
+ const body = await readJsonBody(req, { limitBytes: SESSION_SUMMARY_REQUEST_MAX_BYTES });
14800
+ const tab = getRequestedTab(req, url, body);
14801
+ sendJson(res, 200, { ok: true, data: await saveSessionSummaryPreferencesData(tab, body) }, { "cache-control": "private, no-store" });
14802
+ return;
14803
+ }
14804
+
14805
+ if (url.pathname === "/api/session-summary/generate" && req.method === "POST") {
14806
+ requireSessionSummaryJsonRequest(req);
14807
+ const body = await readJsonBody(req, { limitBytes: SESSION_SUMMARY_REQUEST_MAX_BYTES });
14808
+ requiredSessionSummaryObject(body, "request", ["refresh", "tab"]);
14809
+ if (body.refresh !== undefined && typeof body.refresh !== "boolean") throw makeHttpError(400, "refresh must be true or false");
14810
+ const tab = getRequestedTab(req, url, body);
14811
+ sendJson(res, 200, { ok: true, data: await triggerSessionSummary(tab, { refresh: body.refresh === true }) }, { "cache-control": "private, no-store" });
14812
+ return;
14813
+ }
14814
+
14253
14815
  if (url.pathname === "/api/workflow-policy" && req.method === "GET") {
14254
14816
  requireLocalhost(req, "Workflow policy setup is only allowed from localhost.");
14255
14817
  try {
@@ -14439,6 +15001,7 @@ const server = createServer(async (req, res) => {
14439
15001
  }
14440
15002
 
14441
15003
  if (url.pathname === "/api/tabs" && req.method === "POST") {
15004
+ if (!optionalFeatureStartupReady) throw makeHttpError(503, "Optional feature startup audit is still checking; retry after /api/health is ready");
14442
15005
  const body = await readJsonBody(req);
14443
15006
  const tab = await createTab({ title: body.title, cwd: body.cwd });
14444
15007
  sendJson(res, 201, { ok: true, data: { tab: tabMeta(tab), tabs: listTabs() } });
@@ -14533,6 +15096,16 @@ const server = createServer(async (req, res) => {
14533
15096
  }
14534
15097
  replayExtensionStatuses(tab, client);
14535
15098
  replayExtensionWidgets(tab, client);
15099
+ if (tab.sessionSummary) {
15100
+ sendSseToClient(client, {
15101
+ type: "webui_session_summary",
15102
+ kind: "replay",
15103
+ tabId: tab.id,
15104
+ tabTitle: tab.title,
15105
+ summary: publicSessionSummaryState(tab),
15106
+ replayed: true,
15107
+ });
15108
+ }
14536
15109
  replayPendingExtensionUiRequests(tab, client);
14537
15110
  const keepAlive = setInterval(() => writeSseFrame(client, ": keepalive\n\n"), 15000);
14538
15111
  req.on("close", () => {
@@ -14544,8 +15117,9 @@ const server = createServer(async (req, res) => {
14544
15117
 
14545
15118
  if (url.pathname === "/api/health" && req.method === "GET") {
14546
15119
  const status = await webuiStatus({ includeAuthPin: isLocalRequest(req) });
14547
- sendJson(res, 200, {
14548
- ok: true,
15120
+ sendJson(res, optionalFeatureStartupReady ? 200 : 503, {
15121
+ ok: optionalFeatureStartupReady,
15122
+ startupPhase: optionalFeatureAuditCoordinator.current().phase,
14549
15123
  webuiVersion: status.webuiVersion,
14550
15124
  piVersion: status.piVersion,
14551
15125
  webuiDev: status.webuiDev,
@@ -15087,7 +15661,7 @@ const server = createServer(async (req, res) => {
15087
15661
  }
15088
15662
 
15089
15663
  if (url.pathname === "/api/optional-features" && req.method === "GET") {
15090
- sendJson(res, 200, { ok: true, data: await optionalFeaturePackageStatuses() });
15664
+ sendJson(res, 200, { ok: true, data: optionalFeatureAuditCoordinator.current() });
15091
15665
  return;
15092
15666
  }
15093
15667
 
@@ -15096,7 +15670,48 @@ const server = createServer(async (req, res) => {
15096
15670
  const body = await readJsonBody(req);
15097
15671
  const tab = getRequestedTab(req, url, body);
15098
15672
  ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
15099
- const data = await installOptionalFeaturePackage(String(body.featureId || ""));
15673
+ const revision = optionalFeatureAuditCoordinator.current().revision;
15674
+ const data = await optionalFeatureAuditCoordinator.runMutation(revision, async () => {
15675
+ try {
15676
+ return await installOptionalFeaturePackage(String(body.featureId || ""), tab.cwd);
15677
+ } finally {
15678
+ await optionalFeatureAuditCoordinator.recheck({ reason: "post-install" });
15679
+ }
15680
+ });
15681
+ sendJson(res, 200, { ok: true, data });
15682
+ return;
15683
+ }
15684
+
15685
+ if (url.pathname === "/api/optional-feature-install-batch" && req.method === "POST") {
15686
+ requireLocalhost(req, "Installing optional Web UI features is only allowed from localhost");
15687
+ const body = await readJsonBody(req);
15688
+ const tab = getRequestedTab(req, url, body);
15689
+ ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
15690
+ const data = await runOptionalFeatureBatchMutation({
15691
+ revision: body.revision,
15692
+ featureIds: body.featureIds,
15693
+ cwd: tab.cwd,
15694
+ migration: body.migration === true,
15695
+ tab,
15696
+ install: () => installOptionalFeaturePackages(body.featureIds, tab.cwd),
15697
+ });
15698
+ sendJson(res, 200, { ok: true, data });
15699
+ return;
15700
+ }
15701
+
15702
+ if (url.pathname === "/api/optional-feature-migration/recheck" && req.method === "POST") {
15703
+ requireLocalhostRoute(req, url.pathname);
15704
+ await readJsonBody(req);
15705
+ optionalFeatureAuditCoordinator.assertIdle();
15706
+ const data = await optionalFeatureAuditCoordinator.recheck({ reason: "manual" });
15707
+ sendJson(res, 200, { ok: true, data });
15708
+ return;
15709
+ }
15710
+
15711
+ if (url.pathname === "/api/optional-feature-migration/dismiss" && req.method === "POST") {
15712
+ requireLocalhostRoute(req, url.pathname);
15713
+ const body = await readJsonBody(req);
15714
+ const data = await optionalFeatureAuditCoordinator.dismiss(body.revision);
15100
15715
  sendJson(res, 200, { ok: true, data });
15101
15716
  return;
15102
15717
  }
@@ -15584,18 +16199,49 @@ function sweepWebuiTempArtifacts() {
15584
16199
  sweepWebuiTempArtifacts();
15585
16200
  setInterval(sweepWebuiTempArtifacts, TEMP_ARTIFACT_SWEEP_INTERVAL_MS).unref();
15586
16201
 
15587
- server.listen(options.port, currentHost, () => {
15588
- const urlHost = formatUrlHost(currentHost);
15589
- console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
15590
- console.log(`Working directory: ${options.cwd}`);
15591
- if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
15592
- else console.log("Pi RPC: waiting for CWD selection in the Web UI");
15593
- if (restoreTabs.length) console.log(`Restored Web UI tabs: ${initialTabs.length}`);
15594
- if (!isLocalHost(currentHost)) {
15595
- console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
15596
- }
16202
+ await new Promise((resolve, reject) => {
16203
+ const onError = (error) => {
16204
+ server.off("listening", onListening);
16205
+ reject(error);
16206
+ };
16207
+ const onListening = () => {
16208
+ server.off("error", onError);
16209
+ resolve();
16210
+ };
16211
+ server.once("error", onError);
16212
+ server.once("listening", onListening);
16213
+ server.listen(options.port, currentHost);
15597
16214
  });
15598
16215
 
16216
+ const urlHost = formatUrlHost(currentHost);
16217
+ console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
16218
+ console.log(`Working directory: ${options.cwd}`);
16219
+ if (!isLocalHost(currentHost)) {
16220
+ console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
16221
+ }
16222
+
16223
+ const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
16224
+ if (options.migrationDryRun) {
16225
+ console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);
16226
+ } else if (options.migrateOptionalFeatures) {
16227
+ const featureIds = startupAudit.features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId);
16228
+ if (featureIds.length) {
16229
+ const result = await runOptionalFeatureBatchMutation({ revision: startupAudit.revision, featureIds, cwd: options.cwd, migration: true });
16230
+ console.log(`Optional feature migration: ${result.succeeded} succeeded, ${result.failed} failed.`);
16231
+ }
16232
+ }
16233
+
16234
+ rpcSupervisor = await initializeRpcSupervisor();
16235
+ rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
16236
+ installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
16237
+ const initialTabs = await createInitialTabs();
16238
+ await finishRpcSupervisorStartup(initialTabs);
16239
+ const initialTab = initialTabs[0] || null;
16240
+ optionalFeatureStartupReady = true;
16241
+ if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
16242
+ else console.log("Pi RPC: waiting for CWD selection in the Web UI");
16243
+ if (restoreTabs.length) console.log(`Restored Web UI tabs: ${initialTabs.length}`);
16244
+
15599
16245
  let shutdownInProgress = false;
15600
16246
 
15601
16247
  async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {}) {