@firstpick/pi-package-webui 0.8.2 → 0.8.4

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 (52) hide show
  1. package/README.md +76 -19
  2. package/bin/pi-webui.mjs +864 -140
  3. package/lib/WEBUI_TUI_NATIVE_PARITY.json +26 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/optional-feature-catalog.mjs +29 -0
  6. package/lib/optional-feature-migration.mjs +410 -0
  7. package/lib/session-summary-core.mjs +320 -0
  8. package/lib/session-summary-preferences.mjs +267 -0
  9. package/lib/thinking-stream-recovery.mjs +156 -0
  10. package/lib/ui-layout-settings.mjs +254 -0
  11. package/package.json +5 -40
  12. package/public/app.js +2898 -92
  13. package/public/index.html +77 -14
  14. package/public/service-worker.js +1 -1
  15. package/public/styles.css +669 -2
  16. package/session-summary.ts +403 -0
  17. package/tests/aur-review-widget-static.test.mjs +3 -2
  18. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  19. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  20. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  21. package/tests/browser/interaction-continuity.spec.mjs +29 -0
  22. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  23. package/tests/browser/session-summary.spec.mjs +271 -0
  24. package/tests/codex-fast-mode-static.test.mjs +10 -9
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/fast-mode-client-static.test.mjs +2 -2
  27. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  28. package/tests/fixtures/fake-pi.mjs +51 -1
  29. package/tests/git-workflow-preferences.test.mjs +4 -2
  30. package/tests/http-endpoints-harness.test.mjs +507 -4
  31. package/tests/interaction-state-stability-static.test.mjs +3 -0
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +118 -103
  36. package/tests/native-parity-harness.test.mjs +9 -1
  37. package/tests/native-parity.test.mjs +23 -1
  38. package/tests/open-issue-wizard-static.test.mjs +1 -1
  39. package/tests/optional-feature-migration-frontend.test.mjs +72 -0
  40. package/tests/optional-feature-migration.test.mjs +142 -0
  41. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  42. package/tests/questionnaire-dialog.test.mjs +511 -0
  43. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  44. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  45. package/tests/session-summary-core.test.mjs +491 -0
  46. package/tests/session-summary-preferences.test.mjs +103 -0
  47. package/tests/side-panel-resize-static.test.mjs +1 -0
  48. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  49. package/tests/subagent-launch-slots.test.mjs +1 -1
  50. package/tests/thinking-stream-recovery.test.mjs +88 -0
  51. package/tests/ui-layout-settings.test.mjs +92 -0
  52. package/tests/webui-settings-locking.test.mjs +159 -0
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,
@@ -33,6 +38,7 @@ import {
33
38
  } from "../lib/session-actions.mjs";
34
39
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
35
40
  import { terminateProcessTree } from "../lib/process-tree.mjs";
41
+ import { ThinkingStreamRecovery } from "../lib/thinking-stream-recovery.mjs";
36
42
  import {
37
43
  classifyGitPathFailure,
38
44
  findWindowsReservedGitPath,
@@ -40,6 +46,11 @@ import {
40
46
  } from "../lib/git-command-errors.mjs";
41
47
  import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
42
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";
43
54
  import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
44
55
  import {
45
56
  GIT_WORKFLOW_DEFAULT_VARIANTS,
@@ -61,6 +72,12 @@ import {
61
72
  writeGitWorkflowPreferences,
62
73
  writeWebuiSettings,
63
74
  } from "../lib/git-workflow-preferences.mjs";
75
+ import {
76
+ UI_LAYOUT_REQUEST_MAX_BYTES,
77
+ mergeUiLayout,
78
+ uiLayoutRevision,
79
+ validateUiLayoutPatch,
80
+ } from "../lib/ui-layout-settings.mjs";
64
81
  import {
65
82
  SUBAGENT_LAUNCH_SLOT_LIMITS,
66
83
  SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
@@ -123,6 +140,7 @@ const require = createRequire(import.meta.url);
123
140
  const packageRoot = path.resolve(__dirname, "..");
124
141
  const publicDir = path.join(packageRoot, "public");
125
142
  const webuiHelperExtensionPath = path.join(packageRoot, "webui-rpc-helper.mjs");
143
+ const sessionSummaryExtensionPath = path.join(packageRoot, "session-summary.ts");
126
144
  const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
127
145
  const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT";
128
146
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
@@ -181,6 +199,16 @@ const CLAUDE_USAGE_OUTPUT_MAX_CHARS = 60_000;
181
199
  const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
182
200
  const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
183
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"]);
184
212
  const RECOVERY_ENDPOINT_PATH = "/api/recovery/plan";
185
213
  const RECOVERY_BODY_LIMIT_BYTES = 256 * 1024;
186
214
  const RECOVERY_PROMPT_MAX_CHARS = 200_000;
@@ -369,37 +397,13 @@ function parseSlashCommand(message) {
369
397
  return parseNativeSlashCommand(message, NATIVE_SLASH_COMMAND_NAMES);
370
398
  }
371
399
  const NATURAL_CONVERSATION_FEATURE_ID = "naturalConversation";
372
- const OPTIONAL_FEATURE_PACKAGES = new Map([
373
- ["bangCommandAutocomplete", "@firstpick/pi-extension-bang-command-autocomplete"],
374
- ["fishUserBash", "@firstpick/pi-extension-fish-user-bash"],
375
- ["btwCommand", "@firstpick/pi-extension-btw"],
376
- ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
377
- ["releaseNpm", "@firstpick/pi-extension-release-npm"],
378
- ["releaseAur", "@firstpick/pi-extension-release-aur"],
379
- ["aurReview", "@firstpick/pi-extension-aur-review"],
380
- ["workflows", "@firstpick/pi-extension-workflows"],
381
- ["safetyGuard", "@firstpick/pi-extension-safety-guard"],
382
- ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills"],
383
- ["todoProgressWidget", "@firstpick/pi-extension-todo-progress"],
384
- ["tuiToolsCommand", "@firstpick/pi-extension-tools"],
385
- ["remoteWebui", "@firstpick/pi-package-remote-webui"],
386
- ["naturalConversation", "@firstpick/pi-package-natural-conversation"],
387
- ["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
388
- ["statsCommand", "@firstpick/pi-extension-stats"],
389
- ["codexFastMode", "@firstpick/pi-extension-codex-fast-mode"],
390
- ["themeBundle", "@firstpick/pi-themes-bundle"],
391
- ]);
392
- const WEBUI_CONTROLLED_PACKAGES = new Set([
393
- WEBUI_PACKAGE,
394
- ...[...OPTIONAL_FEATURE_PACKAGES.entries()]
395
- .filter(([featureId]) => featureId !== NATURAL_CONVERSATION_FEATURE_ID)
396
- .map(([, packageName]) => packageName),
397
- ]);
398
- const UPDATE_PACKAGE_NAMES = [...new Set([
399
- ...CORE_UPDATE_PACKAGE_NAMES,
400
- ...WEBUI_CONTROLLED_PACKAGES,
401
- ...OPTIONAL_FEATURE_PACKAGES.values(),
402
- ])].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();
403
407
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
404
408
  const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
405
409
  // Codex subscription Fast mode is owned by the optional @firstpick/pi-extension-codex-fast-mode
@@ -431,6 +435,8 @@ Options:
431
435
  --remote-auth Enable startup PIN authentication for non-local clients
432
436
  --no-remote-auth Disable startup PIN authentication
433
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
434
440
  -h, --help Show this help
435
441
  -v, --version Print version
436
442
 
@@ -480,6 +486,8 @@ function parseArgs(argv) {
480
486
  remoteAuthExplicit: process.env.PI_WEBUI_REMOTE_AUTH !== undefined,
481
487
  outputMode: undefined,
482
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,
483
491
  piArgs: [],
484
492
  help: false,
485
493
  version: false,
@@ -539,6 +547,14 @@ function parseArgs(argv) {
539
547
  i++;
540
548
  continue;
541
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
+ }
542
558
  if (arg === "--remote-auth") {
543
559
  options.remoteAuth = true;
544
560
  options.remoteAuthExplicit = true;
@@ -1881,38 +1897,11 @@ function declaredDependencySpec(pkg, packageName) {
1881
1897
  );
1882
1898
  }
1883
1899
 
1884
- async function installRootDeclaresPackage(root, packageName) {
1885
- const pkg = await readJsonFileIfExists(path.join(root, "package.json"));
1886
- return declaredDependencySpec(pkg, packageName) !== undefined;
1887
- }
1888
-
1889
- async function installRootContainsPackage(root, packageName) {
1890
- return directoryExists(packageNodeModulesPath(path.join(root, "node_modules"), packageName));
1891
- }
1892
-
1893
1900
  function configuredAgentNpmRoot() {
1894
1901
  const root = process.env.PI_CODING_AGENT_DIR ? path.resolve(expandUserPath(process.env.PI_CODING_AGENT_DIR)) : agentDir;
1895
1902
  return path.join(root, "npm");
1896
1903
  }
1897
1904
 
1898
- async function optionalDependencyInstallRoot() {
1899
- const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
1900
- if (configuredRoot) return path.resolve(expandUserPath(configuredRoot));
1901
-
1902
- const installRoot = nodeModulesParentForPackageRoot(packageRoot);
1903
- if (await installRootDeclaresPackage(installRoot, "@firstpick/pi-package-webui") || await installRootContainsPackage(installRoot, "@firstpick/pi-package-webui")) return installRoot;
1904
-
1905
- const agentNpmRoot = configuredAgentNpmRoot();
1906
- if (installRoot !== agentNpmRoot && (await installRootDeclaresPackage(agentNpmRoot, "@firstpick/pi-package-webui") || await installRootContainsPackage(agentNpmRoot, "@firstpick/pi-package-webui"))) return agentNpmRoot;
1907
-
1908
- if (webuiDevServer) return installRoot;
1909
-
1910
- throw makeHttpError(
1911
- 500,
1912
- `Could not determine a safe optional feature install root. Set ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} to the Pi package root.`,
1913
- );
1914
- }
1915
-
1916
1905
  function minimumPackageVersionFromSpec(spec) {
1917
1906
  const match = String(spec || "").match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/);
1918
1907
  return match?.[0] || "";
@@ -1976,33 +1965,124 @@ async function resolveInstalledPackageSubpath(packageName, subpath = "") {
1976
1965
  }
1977
1966
  }
1978
1967
 
1979
- function optionalFeatureDeclaredSpec(packageName) {
1980
- 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);
1981
+ }
1982
+
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;
1981
2037
  }
1982
2038
 
1983
- async function optionalFeaturePackageStatus(featureId) {
1984
- const packageName = OPTIONAL_FEATURE_PACKAGES.get(featureId);
1985
- if (!packageName) throw makeHttpError(400, `Unknown optional feature: ${featureId}`);
1986
- const declaredSpec = optionalFeatureDeclaredSpec(packageName);
1987
- const installedRoot = await resolveInstalledPackageRoot(packageName);
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);
1988
2048
  const manifest = installedRoot ? await readJsonFileIfExists(path.join(installedRoot, "package.json")) : null;
1989
2049
  const installedVersion = typeof manifest?.version === "string" ? manifest.version : "";
1990
- 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));
1991
2060
  return {
1992
2061
  featureId,
1993
2062
  packageName,
1994
- declaredSpec,
1995
- installed: !!installedRoot,
2063
+ expectedSpec,
2064
+ declaredSpec: expectedSpec,
2065
+ installed,
2066
+ configured,
2067
+ locallyConfigured,
2068
+ resourceConflict,
2069
+ ready,
1996
2070
  installedVersion,
1997
2071
  installedRoot,
2072
+ topLevelResources,
2073
+ legacyEvidence,
2074
+ disabled,
1998
2075
  updateAvailable,
1999
- updateReason: updateAvailable ? `installed ${installedVersion} is older than Web UI expects (${declaredSpec})` : "",
2076
+ updateReason: updateAvailable ? `installed ${installedVersion} is older than Web UI expects (${expectedSpec})` : "",
2000
2077
  };
2001
2078
  }
2002
2079
 
2003
- async function optionalFeaturePackageStatuses() {
2080
+ async function optionalFeaturePackageStatuses(cwd = options.cwd) {
2004
2081
  const features = [];
2005
- 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
+ }
2006
2086
  return { features };
2007
2087
  }
2008
2088
 
@@ -2015,28 +2095,28 @@ function optionalFeatureInstallOutputTail(result, maxLength = 4000) {
2015
2095
  function optionalFeatureInstallFailureKind(result, message = "") {
2016
2096
  const combined = `${message}\n${result?.error || ""}\n${result?.stderr || ""}\n${result?.stdout || ""}`;
2017
2097
  if (result?.timedOut) return "timeout";
2018
- 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";
2019
2099
  if (/\b(?:EACCES|EPERM|permission denied|access denied)\b/i.test(combined)) return "permission";
2020
2100
  if (/\b(?:EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT|network timeout|registry\.npmjs\.org|fetch failed)\b/i.test(combined)) return "network";
2021
- return "npm-exit";
2101
+ return "pi-exit";
2022
2102
  }
2023
2103
 
2024
- function optionalFeatureInstallFailureHint(kind, { command, installRoot } = {}) {
2104
+ function optionalFeatureInstallFailureHint(kind, { command } = {}) {
2025
2105
  switch (kind) {
2026
- case "install-root":
2027
- return `Set ${OPTIONAL_FEATURE_INSTALL_ROOT_ENV} to the Pi/Web UI npm package root, then retry.`;
2028
- case "npm-not-found":
2029
- 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.";
2030
2108
  case "permission":
2031
- 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.";
2032
2110
  case "network":
2033
- 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.";
2034
2112
  case "timeout":
2035
- 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.";
2036
2116
  case "status-check":
2037
- 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.";
2038
2118
  default:
2039
- 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.";
2040
2120
  }
2041
2121
  }
2042
2122
 
@@ -2057,27 +2137,26 @@ function makeOptionalFeatureInstallError(statusCode, message, details = {}) {
2057
2137
  return error;
2058
2138
  }
2059
2139
 
2060
- async function installOptionalFeaturePackage(featureId) {
2061
- const beforeStatus = await optionalFeaturePackageStatus(featureId);
2140
+ async function installOptionalFeaturePackage(featureId, cwd = options.cwd) {
2141
+ const beforeStatus = await optionalFeaturePackageStatus(featureId, cwd);
2062
2142
  const packageName = beforeStatus.packageName;
2063
-
2064
- let installRoot;
2065
- try {
2066
- installRoot = await optionalDependencyInstallRoot();
2067
- } catch (error) {
2068
- const message = formatCliError(error);
2069
- throw makeOptionalFeatureInstallError(error?.statusCode || 500, message, {
2070
- 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",
2071
2150
  featureId,
2072
2151
  packageName,
2073
- hint: optionalFeatureInstallFailureHint("install-root"),
2152
+ command: `pi install ${source}`,
2153
+ hint: optionalFeatureInstallFailureHint("local-resource-conflict"),
2074
2154
  });
2075
2155
  }
2076
-
2077
- const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, packageName]);
2078
- const command = npmCommand.displayCommand;
2079
- const result = await runCommand(npmCommand.command, npmCommand.args, {
2080
- 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,
2081
2160
  timeoutMs: 5 * 60 * 1000,
2082
2161
  maxOutputLength: 80000,
2083
2162
  });
@@ -2093,40 +2172,167 @@ async function installOptionalFeaturePackage(featureId) {
2093
2172
  kind,
2094
2173
  featureId,
2095
2174
  packageName,
2096
- installRoot,
2097
2175
  command,
2098
2176
  exitCode: result.exitCode,
2099
2177
  timedOut: result.timedOut,
2100
2178
  outputTail: optionalFeatureInstallOutputTail(result),
2101
2179
  });
2102
2180
  }
2181
+
2103
2182
  let afterStatus;
2104
2183
  try {
2105
- 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
+ }
2106
2188
  } catch (error) {
2107
2189
  const message = `Optional feature install finished, but status verification failed: ${formatCliError(error)}`;
2108
2190
  throw makeOptionalFeatureInstallError(error?.statusCode || 500, message, {
2109
2191
  kind: "status-check",
2110
2192
  featureId,
2111
2193
  packageName,
2112
- installRoot,
2113
2194
  command,
2114
2195
  outputTail: optionalFeatureInstallOutputTail(result),
2115
2196
  });
2116
2197
  }
2117
- const operation = beforeStatus.installed ? "Updated" : "Installed";
2198
+
2199
+ const operation = beforeStatus.ready ? "Updated" : beforeStatus.installed ? "Registered" : "Installed";
2118
2200
  return {
2119
2201
  featureId,
2120
2202
  packageName,
2121
- installRoot,
2203
+ source,
2122
2204
  command,
2123
2205
  stdout: result.stdout,
2124
2206
  stderr: result.stderr,
2125
2207
  status: afterStatus,
2126
- 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.`,
2127
2209
  };
2128
2210
  }
2129
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,
2272
+ };
2273
+ }
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
+
2130
2336
  function displayPath(cwd) {
2131
2337
  const normalized = cwd.replace(/\\/g, "/");
2132
2338
  const home = (process.env.USERPROFILE || process.env.HOME || "").replace(/\\/g, "/");
@@ -2284,6 +2490,15 @@ function requireWorkflowPolicyJsonRequest(req) {
2284
2490
  }
2285
2491
  }
2286
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
+
2287
2502
  function workflowPolicySaveBody(body) {
2288
2503
  if (!body || typeof body !== "object" || Array.isArray(body)) {
2289
2504
  throw makeHttpError(400, "Workflow policy save body must be an object with only policy and expectedRevision.");
@@ -2549,6 +2764,172 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
2549
2764
  return gitWorkflowPreferencesData(tab);
2550
2765
  }
2551
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
+
2552
2933
  function gitWorkflowGenerationPrompt(kind, preferences) {
2553
2934
  switch (kind) {
2554
2935
  case "commit":
@@ -8461,7 +8842,7 @@ function parseNodeModulesPackageRef(manifestEntry) {
8461
8842
 
8462
8843
  async function resolveStartedWebuiManifestResource(manifestEntry) {
8463
8844
  const nodeModulesRef = parseNodeModulesPackageRef(manifestEntry);
8464
- if (nodeModulesRef && WEBUI_CONTROLLED_PACKAGES.has(nodeModulesRef.packageName)) {
8845
+ if (nodeModulesRef && WEBUI_RESOURCE_EXCLUDED_PACKAGES.has(nodeModulesRef.packageName)) {
8465
8846
  const installedCandidate = await resolveInstalledPackageSubpath(nodeModulesRef.packageName, nodeModulesRef.subpath);
8466
8847
  if (installedCandidate) return installedCandidate;
8467
8848
  }
@@ -8510,10 +8891,15 @@ async function resolvedNormalPiResourcesForTab(cwd) {
8510
8891
  async function normalPiResourcePathsForTab(resolved, resourceType) {
8511
8892
  if (piArgsDisableResourceDiscovery(resourceType)) return [];
8512
8893
  const resourcePaths = [];
8894
+ const auditExcludedPackages = optionalFeatureAuditCoordinator?.excludedPackageNames?.() || new Set();
8895
+ const coreOnly = optionalFeatureAuditCoordinator?.current?.().phase === "checking" || optionalFeatureAuditCoordinator?.current?.().phase === "degraded";
8513
8896
  for (const resource of resolved[resourceType] || []) {
8514
8897
  if (!resource.enabled) continue;
8515
8898
  const packageName = await packageNameForResourcePath(resource.path);
8516
- if (packageName && WEBUI_CONTROLLED_PACKAGES.has(packageName)) continue;
8899
+ if (packageName && WEBUI_RESOURCE_EXCLUDED_PACKAGES.has(packageName)) continue;
8900
+ if (packageName && auditExcludedPackages.has(packageName)) {
8901
+ if (coreOnly || resource.metadata?.origin !== "package") continue;
8902
+ }
8517
8903
  resourcePaths.push(resource.path);
8518
8904
  }
8519
8905
  return resourcePaths;
@@ -8538,6 +8924,11 @@ async function buildPiArgsForTab(tabIndex, title, tabCwd = options.cwd) {
8538
8924
  await appendCuratedResourceArgs(args, normalResources, "prompts", "--prompt-template");
8539
8925
  await appendCuratedResourceArgs(args, normalResources, "themes", "--theme");
8540
8926
 
8927
+ // The package manifest is resolved above, but keep session-summary explicit:
8928
+ // curated child discovery intentionally excludes package-owned resources in
8929
+ // some installations. Avoid a duplicate when the manifest path was retained.
8930
+ if (!args.includes(sessionSummaryExtensionPath)) args.push("--extension", sessionSummaryExtensionPath);
8931
+
8541
8932
  // Load a browser-safe RPC helper into every Web UI tab. It exposes hidden
8542
8933
  // extension commands for Web UI-native /tools and /skills selectors without
8543
8934
  // depending on TUI-only extension UIs.
@@ -8927,6 +9318,133 @@ function clearExtensionWidgets(tab) {
8927
9318
  tab?.extensionWidgets?.clear();
8928
9319
  }
8929
9320
 
9321
+ function normalizedSessionSummaryTitle(value) {
9322
+ if (typeof value !== "string" || value.length > SESSION_SUMMARY_TITLE_MAX_CHARS) return "";
9323
+ const title = value.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
9324
+ return title.length <= SESSION_SUMMARY_TITLE_MAX_CHARS ? title : "";
9325
+ }
9326
+
9327
+ function normalizedSessionSummaryRpcDetails(value) {
9328
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.version !== SESSION_SUMMARY_PROTOCOL_VERSION) return null;
9329
+ const kind = String(value.kind || "");
9330
+ if (!SESSION_SUMMARY_KINDS.has(kind)) return null;
9331
+ const details = { version: SESSION_SUMMARY_PROTOCOL_VERSION, kind };
9332
+ if (value.sessionId !== undefined) {
9333
+ if (typeof value.sessionId !== "string" || value.sessionId.length > 128) return null;
9334
+ details.sessionId = value.sessionId;
9335
+ }
9336
+ if (value.title !== undefined) {
9337
+ const title = normalizedSessionSummaryTitle(value.title);
9338
+ if (!title) return null;
9339
+ details.title = title;
9340
+ }
9341
+ if (value.summaryMarkdown !== undefined) {
9342
+ if (typeof value.summaryMarkdown !== "string" || !value.summaryMarkdown.trim() || value.summaryMarkdown.length > SESSION_SUMMARY_MARKDOWN_MAX_CHARS) return null;
9343
+ details.summaryMarkdown = value.summaryMarkdown.trim();
9344
+ }
9345
+ if (value.message !== undefined) {
9346
+ if (typeof value.message !== "string" || value.message.length > SESSION_SUMMARY_FAILURE_MAX_CHARS) return null;
9347
+ details.message = value.message.replace(/[\r\n]+/g, " ").trim();
9348
+ }
9349
+ for (const key of ["configured", "enabled", "durable"]) {
9350
+ if (value[key] !== undefined) {
9351
+ if (typeof value[key] !== "boolean") return null;
9352
+ details[key] = value[key];
9353
+ }
9354
+ }
9355
+ if ((kind === "success" && !details.summaryMarkdown) || (kind === "failure" && !details.message) || (kind === "title" && !details.title)) return null;
9356
+ return details;
9357
+ }
9358
+
9359
+ function publicSessionSummaryState(tab) {
9360
+ const value = tab?.sessionSummary;
9361
+ if (!value) return null;
9362
+ return {
9363
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
9364
+ status: value.status || "idle",
9365
+ configured: value.configured === true,
9366
+ enabled: value.enabled === true,
9367
+ durable: value.durable === true,
9368
+ ...(value.sessionId ? { sessionId: value.sessionId } : {}),
9369
+ ...(value.title ? { title: value.title } : {}),
9370
+ ...(value.summaryMarkdown ? { summaryMarkdown: value.summaryMarkdown } : {}),
9371
+ ...(value.message ? { message: value.message } : {}),
9372
+ updatedAt: value.updatedAt || new Date(0).toISOString(),
9373
+ };
9374
+ }
9375
+
9376
+ function broadcastSessionSummaryState(tab, kind) {
9377
+ broadcastTabEvent(tab, {
9378
+ type: "webui_session_summary",
9379
+ kind,
9380
+ tabId: tab.id,
9381
+ tabTitle: tab.title,
9382
+ summary: publicSessionSummaryState(tab),
9383
+ });
9384
+ }
9385
+
9386
+ function applySessionSummaryRpcDetails(tab, details) {
9387
+ const previous = tab.sessionSummary?.sessionId && details.sessionId && tab.sessionSummary.sessionId !== details.sessionId
9388
+ ? null
9389
+ : tab.sessionSummary;
9390
+ const next = {
9391
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
9392
+ status: previous?.status || "idle",
9393
+ configured: previous?.configured === true,
9394
+ enabled: previous?.enabled === true,
9395
+ durable: previous?.durable === true,
9396
+ sessionId: details.sessionId || previous?.sessionId || "",
9397
+ title: previous?.title || "",
9398
+ summaryMarkdown: previous?.summaryMarkdown || "",
9399
+ message: "",
9400
+ updatedAt: new Date().toISOString(),
9401
+ };
9402
+ if (details.configured !== undefined) next.configured = details.configured;
9403
+ if (details.enabled !== undefined) next.enabled = details.enabled;
9404
+ if (details.durable !== undefined) next.durable = details.durable;
9405
+ if (details.kind === "state") {
9406
+ next.status = details.summaryMarkdown ? "success" : "idle";
9407
+ next.title = details.title || "";
9408
+ next.summaryMarkdown = details.summaryMarkdown || "";
9409
+ } else if (details.kind === "setup") {
9410
+ next.status = "idle";
9411
+ } else if (details.kind === "generating") {
9412
+ next.status = "generating";
9413
+ } else if (details.kind === "success") {
9414
+ next.status = "success";
9415
+ next.title = details.title || next.title;
9416
+ next.summaryMarkdown = details.summaryMarkdown;
9417
+ } else if (details.kind === "failure") {
9418
+ next.status = "failure";
9419
+ next.message = details.message;
9420
+ } else if (details.kind === "title") {
9421
+ next.title = details.title;
9422
+ if (tab.titleSource === "default" || tab.titleSource === "auto") {
9423
+ renameTab(tab, details.title, { source: "auto", maxLength: SESSION_SUMMARY_TITLE_MAX_CHARS });
9424
+ }
9425
+ }
9426
+ tab.sessionSummary = next;
9427
+ broadcastSessionSummaryState(tab, details.kind);
9428
+ }
9429
+
9430
+ function consumeSessionSummaryRpcEvent(tab, event) {
9431
+ const message = event?.message;
9432
+ if ((event?.type !== "message_start" && event?.type !== "message_end") || message?.role !== "custom") return false;
9433
+ if (message.customType === SESSION_SUMMARY_DISPLAY_TYPE) return true;
9434
+ if (message.customType !== SESSION_SUMMARY_RPC_TYPE) return false;
9435
+ if (event.type === "message_end") {
9436
+ const details = normalizedSessionSummaryRpcDetails(message.details);
9437
+ if (details) applySessionSummaryRpcDetails(tab, details);
9438
+ }
9439
+ return true;
9440
+ }
9441
+
9442
+ function filterSessionSummaryTranscriptMessages(messages) {
9443
+ return (Array.isArray(messages) ? messages : []).filter((message) => !(
9444
+ message?.role === "custom" && (message.customType === SESSION_SUMMARY_RPC_TYPE || message.customType === SESSION_SUMMARY_DISPLAY_TYPE)
9445
+ ));
9446
+ }
9447
+
8930
9448
  function clearWebuiSubagents(tab) {
8931
9449
  if (tab) tab.webuiSubagents = null;
8932
9450
  }
@@ -9796,8 +10314,9 @@ async function primeTabRpc(tab) {
9796
10314
  function attachRpcToTab(tab, rpc) {
9797
10315
  tab.rpcUnsubscribe?.();
9798
10316
  tab.rpc = rpc;
9799
- tab.rpcUnsubscribe = rpc.onEvent((event) => {
9800
- if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
10317
+ tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
10318
+ const event = tab.thinkingStreamRecovery.ingest(rawEvent);
10319
+ if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event) || consumeSessionSummaryRpcEvent(tab, event)) return;
9801
10320
  updateTabActivityFromEvent(tab, event);
9802
10321
  let scopedEvent = eventForTabClients(tab, event);
9803
10322
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
@@ -9836,12 +10355,14 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9836
10355
  gitWorkspace: gitWorkspace || null,
9837
10356
  lastState: null,
9838
10357
  pendingThinkingLevel: undefined,
10358
+ thinkingStreamRecovery: new ThinkingStreamRecovery(),
9839
10359
  gitWorkflowGenerationRestore: null,
9840
10360
  gitWorkflowMessageGeneration: null,
9841
10361
  activity: createTabActivity(createdAt),
9842
10362
  pendingExtensionUiRequests: new Map(),
9843
10363
  extensionStatuses: new Map(),
9844
10364
  extensionWidgets: new Map(),
10365
+ sessionSummary: null,
9845
10366
  webuiSubagents: null,
9846
10367
  subagentDisplayTitle: undefined,
9847
10368
  subagentDisplayTitlePromise: undefined,
@@ -10000,6 +10521,7 @@ function tabMeta(tab) {
10000
10521
  activity: tabActivitySnapshot(tab),
10001
10522
  appRunner: publicAppRunnerState(tab.appRunner),
10002
10523
  conversationMode: naturalConversationModeSnapshot(tab),
10524
+ sessionSummary: publicSessionSummaryState(tab),
10003
10525
  };
10004
10526
  }
10005
10527
 
@@ -10612,6 +11134,7 @@ function packageNodeModulesPath(nodeModulesRoot, packageName) {
10612
11134
 
10613
11135
  function isWebuiOrPiPackageName(packageName) {
10614
11136
  const name = String(packageName || "").trim();
11137
+ if (OPTIONAL_FEATURE_PACKAGE_NAMES.has(name)) return false;
10615
11138
  return UPDATE_PACKAGE_NAMES.includes(name)
10616
11139
  || /^@firstpick\/pi(?:-|$)/.test(name)
10617
11140
  || /^@earendil-works\/pi(?:-|$)/.test(name)
@@ -10928,8 +11451,18 @@ function componentUpdateSuccessMessage(target) {
10928
11451
  return "Web UI update completed. Restart the Web UI to use the update.";
10929
11452
  }
10930
11453
 
11454
+ async function persistOptionalFeaturePendingUpgrade() {
11455
+ optionalFeatureAuditCoordinator.assertIdle();
11456
+ const snapshot = await optionalFeatureAuditCoordinator.recheck({ reason: "pre-update" });
11457
+ const featureIds = snapshot.features
11458
+ .filter(({ state }) => !["missing", "unknown", "disabled"].includes(state))
11459
+ .map(({ featureId }) => featureId);
11460
+ await optionalFeatureMigrationStore.markPendingUpgrade({ fromVersion: packageJson.version, featureIds });
11461
+ }
11462
+
10931
11463
  async function runComponentUpdate(target) {
10932
11464
  try {
11465
+ if (target === "webui") await persistOptionalFeaturePendingUpgrade();
10933
11466
  const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
10934
11467
  if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
10935
11468
  const command = updateTasks.map(updateTaskDisplay).join(" && ");
@@ -10963,6 +11496,7 @@ async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
10963
11496
  piUpdateInProgress = true;
10964
11497
  let restartPrepared = false;
10965
11498
  try {
11499
+ if (all) await persistOptionalFeaturePendingUpgrade();
10966
11500
  const restorableTabs = await restorableTabsForRestart();
10967
11501
  const updateTasks = await resolveUpdateTasks({ all });
10968
11502
  if (!updateTasks.length) throw makeHttpError(500, "No Pi update command could be resolved.");
@@ -11266,7 +11800,14 @@ function fallbackRpcResponse(tab, command, error) {
11266
11800
 
11267
11801
  async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
11268
11802
  try {
11269
- return rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
11803
+ const response = rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
11804
+ if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
11805
+ response.data = {
11806
+ ...response.data,
11807
+ messages: filterSessionSummaryTranscriptMessages(tab.thinkingStreamRecovery.applyToMessages(response.data.messages)),
11808
+ };
11809
+ }
11810
+ return response;
11270
11811
  } catch (error) {
11271
11812
  const message = sanitizeError(error);
11272
11813
  if (/Pi RPC process is not running/i.test(message)) return responseWithPendingThinking(tab, fallbackRpcResponse(tab, command, error));
@@ -13587,12 +14128,16 @@ const serverStartedAt = new Date().toISOString();
13587
14128
  const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
13588
14129
  let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
13589
14130
  let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
13590
- rpcSupervisor = await initializeRpcSupervisor();
13591
- rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
13592
- installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
13593
- const initialTabs = await createInitialTabs();
13594
- await finishRpcSupervisorStartup(initialTabs);
13595
- const initialTab = initialTabs[0];
14131
+ optionalFeatureMigrationStore = new OptionalFeatureMigrationStore({
14132
+ filePath: process.env.PI_WEBUI_OPTIONAL_FEATURE_MIGRATION_FILE || path.join(agentDir, "webui", "optional-feature-migration.json"),
14133
+ });
14134
+ optionalFeatureAuditCoordinator = new OptionalFeatureAuditCoordinator({
14135
+ catalog: OPTIONAL_FEATURE_CATALOG,
14136
+ collectStatuses: async () => (await optionalFeaturePackageStatuses(options.cwd)).features,
14137
+ store: optionalFeatureMigrationStore,
14138
+ webuiVersion: packageJson.version,
14139
+ onEvent: (event) => broadcastServerEvent(event),
14140
+ });
13596
14141
  let currentHost = options.host;
13597
14142
  let networkRebindInProgress = false;
13598
14143
  let networkRebindTargetHost = null;
@@ -13724,18 +14269,73 @@ async function saveOutputModeDefault(value) {
13724
14269
  return outputModeMetadata();
13725
14270
  }
13726
14271
 
14272
+ function interfacePreferencesResponse(settings) {
14273
+ return {
14274
+ preferences: settings.interfacePreferences,
14275
+ layout: settings.uiLayout,
14276
+ layoutRevision: uiLayoutRevision(settings.uiLayout),
14277
+ };
14278
+ }
14279
+
14280
+ function interfacePreferencesRequestError(error, operation) {
14281
+ if (error?.statusCode) return error;
14282
+ if (error?.code === "UI_LAYOUT_INVALID" || error instanceof TypeError) return makeHttpError(400, formatCliError(error));
14283
+ if (error?.code === "UI_LAYOUT_STALE_REVISION") return makeHttpError(409, "The interface layout changed after it was read; refresh and retry.");
14284
+ const message = error?.code === "WEBUI_SETTINGS_LOCK_TIMEOUT"
14285
+ ? "Interface preferences are busy; retry shortly."
14286
+ : `Could not ${operation} interface preferences.`;
14287
+ const wrapped = makeHttpError(error?.code === "WEBUI_SETTINGS_LOCK_TIMEOUT" ? 503 : 500, message);
14288
+ wrapped.userMessage = message;
14289
+ return wrapped;
14290
+ }
14291
+
14292
+ function requireInterfacePreferencesJsonRequest(req) {
14293
+ const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
14294
+ if (contentType !== "application/json") throw makeHttpError(415, "Interface preference saves require Content-Type: application/json.");
14295
+ }
14296
+
14297
+ function validateInterfacePreferencesBody(body) {
14298
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw makeHttpError(400, "Interface preference save body must be an object.");
14299
+ const allowed = new Set(["sidePanelWidth", "layout", "expectedLayoutRevision"]);
14300
+ const unknown = Object.keys(body).filter((key) => !allowed.has(key));
14301
+ if (unknown.length) throw makeHttpError(400, `Interface preference save contains unsupported field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`);
14302
+ const hasWidth = Object.hasOwn(body, "sidePanelWidth");
14303
+ const hasLayout = Object.hasOwn(body, "layout");
14304
+ if (!hasWidth && !hasLayout) throw makeHttpError(400, "Interface preference save must include sidePanelWidth or layout.");
14305
+ if (hasWidth) {
14306
+ if (typeof body.sidePanelWidth !== "number" || !Number.isFinite(body.sidePanelWidth) || body.sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || body.sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
14307
+ throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
14308
+ }
14309
+ }
14310
+ if (hasLayout) {
14311
+ if (!Object.hasOwn(body, "expectedLayoutRevision") || typeof body.expectedLayoutRevision !== "string" || !/^[a-f0-9]{64}$/u.test(body.expectedLayoutRevision)) {
14312
+ throw makeHttpError(400, "layout saves require the latest layoutRevision as expectedLayoutRevision.");
14313
+ }
14314
+ validateUiLayoutPatch(body.layout);
14315
+ } else if (Object.hasOwn(body, "expectedLayoutRevision")) {
14316
+ throw makeHttpError(400, "expectedLayoutRevision is only valid with a layout save.");
14317
+ }
14318
+ return { hasWidth, hasLayout };
14319
+ }
14320
+
13727
14321
  async function interfacePreferencesData() {
13728
- const settings = await readWebuiSettings();
13729
- return { preferences: settings.interfacePreferences };
14322
+ return interfacePreferencesResponse(await readWebuiSettings());
13730
14323
  }
13731
14324
 
13732
14325
  async function saveInterfacePreferences(body = {}) {
13733
- const sidePanelWidth = Number(body.sidePanelWidth);
13734
- if (!Number.isFinite(sidePanelWidth) || sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
13735
- throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
13736
- }
13737
- const settings = await writeWebuiSettings({ interfacePreferences: { sidePanelWidth: Math.round(sidePanelWidth) } });
13738
- return { preferences: settings.interfacePreferences };
14326
+ const { hasWidth, hasLayout } = validateInterfacePreferencesBody(body);
14327
+ const settings = await updateWebuiSettings((current) => {
14328
+ if (hasLayout && body.expectedLayoutRevision !== uiLayoutRevision(current.uiLayout)) {
14329
+ const error = new Error("stale interface layout revision");
14330
+ error.code = "UI_LAYOUT_STALE_REVISION";
14331
+ throw error;
14332
+ }
14333
+ const patch = {};
14334
+ if (hasWidth) patch.interfacePreferences = { sidePanelWidth: Math.round(body.sidePanelWidth) };
14335
+ if (hasLayout) patch.uiLayout = mergeUiLayout(current.uiLayout, body.layout);
14336
+ return patch;
14337
+ });
14338
+ return interfacePreferencesResponse(settings);
13739
14339
  }
13740
14340
 
13741
14341
  const remoteAuth = {
@@ -14181,6 +14781,30 @@ const server = createServer(async (req, res) => {
14181
14781
  return;
14182
14782
  }
14183
14783
 
14784
+ if (url.pathname === "/api/session-summary/preferences" && req.method === "GET") {
14785
+ const tab = getRequestedTab(req, url);
14786
+ sendJson(res, 200, { ok: true, data: await sessionSummaryPreferencesData(tab) }, { "cache-control": "private, no-store" });
14787
+ return;
14788
+ }
14789
+
14790
+ if (url.pathname === "/api/session-summary/preferences" && req.method === "PUT") {
14791
+ requireSessionSummaryJsonRequest(req);
14792
+ const body = await readJsonBody(req, { limitBytes: SESSION_SUMMARY_REQUEST_MAX_BYTES });
14793
+ const tab = getRequestedTab(req, url, body);
14794
+ sendJson(res, 200, { ok: true, data: await saveSessionSummaryPreferencesData(tab, body) }, { "cache-control": "private, no-store" });
14795
+ return;
14796
+ }
14797
+
14798
+ if (url.pathname === "/api/session-summary/generate" && req.method === "POST") {
14799
+ requireSessionSummaryJsonRequest(req);
14800
+ const body = await readJsonBody(req, { limitBytes: SESSION_SUMMARY_REQUEST_MAX_BYTES });
14801
+ requiredSessionSummaryObject(body, "request", ["refresh", "tab"]);
14802
+ if (body.refresh !== undefined && typeof body.refresh !== "boolean") throw makeHttpError(400, "refresh must be true or false");
14803
+ const tab = getRequestedTab(req, url, body);
14804
+ sendJson(res, 200, { ok: true, data: await triggerSessionSummary(tab, { refresh: body.refresh === true }) }, { "cache-control": "private, no-store" });
14805
+ return;
14806
+ }
14807
+
14184
14808
  if (url.pathname === "/api/workflow-policy" && req.method === "GET") {
14185
14809
  requireLocalhost(req, "Workflow policy setup is only allowed from localhost.");
14186
14810
  try {
@@ -14240,12 +14864,28 @@ const server = createServer(async (req, res) => {
14240
14864
  }
14241
14865
 
14242
14866
  if (url.pathname === "/api/interface-preferences" && req.method === "GET") {
14243
- sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
14867
+ try {
14868
+ sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
14869
+ } catch (error) {
14870
+ throw interfacePreferencesRequestError(error, "read");
14871
+ }
14244
14872
  return;
14245
14873
  }
14246
14874
 
14247
14875
  if (url.pathname === "/api/interface-preferences" && req.method === "PUT") {
14248
- sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(await readJsonBody(req)) });
14876
+ requireInterfacePreferencesJsonRequest(req);
14877
+ try {
14878
+ let body;
14879
+ try {
14880
+ body = await readJsonBody(req, { limitBytes: UI_LAYOUT_REQUEST_MAX_BYTES });
14881
+ } catch (error) {
14882
+ if (error instanceof SyntaxError) throw makeHttpError(400, "Interface preference save body must be valid JSON.");
14883
+ throw error;
14884
+ }
14885
+ sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(body) });
14886
+ } catch (error) {
14887
+ throw interfacePreferencesRequestError(error, "save");
14888
+ }
14249
14889
  return;
14250
14890
  }
14251
14891
 
@@ -14354,6 +14994,7 @@ const server = createServer(async (req, res) => {
14354
14994
  }
14355
14995
 
14356
14996
  if (url.pathname === "/api/tabs" && req.method === "POST") {
14997
+ if (!optionalFeatureStartupReady) throw makeHttpError(503, "Optional feature startup audit is still checking; retry after /api/health is ready");
14357
14998
  const body = await readJsonBody(req);
14358
14999
  const tab = await createTab({ title: body.title, cwd: body.cwd });
14359
15000
  sendJson(res, 201, { ok: true, data: { tab: tabMeta(tab), tabs: listTabs() } });
@@ -14448,6 +15089,16 @@ const server = createServer(async (req, res) => {
14448
15089
  }
14449
15090
  replayExtensionStatuses(tab, client);
14450
15091
  replayExtensionWidgets(tab, client);
15092
+ if (tab.sessionSummary) {
15093
+ sendSseToClient(client, {
15094
+ type: "webui_session_summary",
15095
+ kind: "replay",
15096
+ tabId: tab.id,
15097
+ tabTitle: tab.title,
15098
+ summary: publicSessionSummaryState(tab),
15099
+ replayed: true,
15100
+ });
15101
+ }
14451
15102
  replayPendingExtensionUiRequests(tab, client);
14452
15103
  const keepAlive = setInterval(() => writeSseFrame(client, ": keepalive\n\n"), 15000);
14453
15104
  req.on("close", () => {
@@ -14459,8 +15110,9 @@ const server = createServer(async (req, res) => {
14459
15110
 
14460
15111
  if (url.pathname === "/api/health" && req.method === "GET") {
14461
15112
  const status = await webuiStatus({ includeAuthPin: isLocalRequest(req) });
14462
- sendJson(res, 200, {
14463
- ok: true,
15113
+ sendJson(res, optionalFeatureStartupReady ? 200 : 503, {
15114
+ ok: optionalFeatureStartupReady,
15115
+ startupPhase: optionalFeatureAuditCoordinator.current().phase,
14464
15116
  webuiVersion: status.webuiVersion,
14465
15117
  piVersion: status.piVersion,
14466
15118
  webuiDev: status.webuiDev,
@@ -15002,7 +15654,7 @@ const server = createServer(async (req, res) => {
15002
15654
  }
15003
15655
 
15004
15656
  if (url.pathname === "/api/optional-features" && req.method === "GET") {
15005
- sendJson(res, 200, { ok: true, data: await optionalFeaturePackageStatuses() });
15657
+ sendJson(res, 200, { ok: true, data: optionalFeatureAuditCoordinator.current() });
15006
15658
  return;
15007
15659
  }
15008
15660
 
@@ -15011,7 +15663,48 @@ const server = createServer(async (req, res) => {
15011
15663
  const body = await readJsonBody(req);
15012
15664
  const tab = getRequestedTab(req, url, body);
15013
15665
  ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
15014
- const data = await installOptionalFeaturePackage(String(body.featureId || ""));
15666
+ const revision = optionalFeatureAuditCoordinator.current().revision;
15667
+ const data = await optionalFeatureAuditCoordinator.runMutation(revision, async () => {
15668
+ try {
15669
+ return await installOptionalFeaturePackage(String(body.featureId || ""), tab.cwd);
15670
+ } finally {
15671
+ await optionalFeatureAuditCoordinator.recheck({ reason: "post-install" });
15672
+ }
15673
+ });
15674
+ sendJson(res, 200, { ok: true, data });
15675
+ return;
15676
+ }
15677
+
15678
+ if (url.pathname === "/api/optional-feature-install-batch" && req.method === "POST") {
15679
+ requireLocalhost(req, "Installing optional Web UI features is only allowed from localhost");
15680
+ const body = await readJsonBody(req);
15681
+ const tab = getRequestedTab(req, url, body);
15682
+ ensureNaturalConversationRouteAllowed(tab, "optional feature installs are blocked");
15683
+ const data = await runOptionalFeatureBatchMutation({
15684
+ revision: body.revision,
15685
+ featureIds: body.featureIds,
15686
+ cwd: tab.cwd,
15687
+ migration: body.migration === true,
15688
+ tab,
15689
+ install: () => installOptionalFeaturePackages(body.featureIds, tab.cwd),
15690
+ });
15691
+ sendJson(res, 200, { ok: true, data });
15692
+ return;
15693
+ }
15694
+
15695
+ if (url.pathname === "/api/optional-feature-migration/recheck" && req.method === "POST") {
15696
+ requireLocalhostRoute(req, url.pathname);
15697
+ await readJsonBody(req);
15698
+ optionalFeatureAuditCoordinator.assertIdle();
15699
+ const data = await optionalFeatureAuditCoordinator.recheck({ reason: "manual" });
15700
+ sendJson(res, 200, { ok: true, data });
15701
+ return;
15702
+ }
15703
+
15704
+ if (url.pathname === "/api/optional-feature-migration/dismiss" && req.method === "POST") {
15705
+ requireLocalhostRoute(req, url.pathname);
15706
+ const body = await readJsonBody(req);
15707
+ const data = await optionalFeatureAuditCoordinator.dismiss(body.revision);
15015
15708
  sendJson(res, 200, { ok: true, data });
15016
15709
  return;
15017
15710
  }
@@ -15499,18 +16192,49 @@ function sweepWebuiTempArtifacts() {
15499
16192
  sweepWebuiTempArtifacts();
15500
16193
  setInterval(sweepWebuiTempArtifacts, TEMP_ARTIFACT_SWEEP_INTERVAL_MS).unref();
15501
16194
 
15502
- server.listen(options.port, currentHost, () => {
15503
- const urlHost = formatUrlHost(currentHost);
15504
- console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
15505
- console.log(`Working directory: ${options.cwd}`);
15506
- if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
15507
- else console.log("Pi RPC: waiting for CWD selection in the Web UI");
15508
- if (restoreTabs.length) console.log(`Restored Web UI tabs: ${initialTabs.length}`);
15509
- if (!isLocalHost(currentHost)) {
15510
- console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
15511
- }
16195
+ await new Promise((resolve, reject) => {
16196
+ const onError = (error) => {
16197
+ server.off("listening", onListening);
16198
+ reject(error);
16199
+ };
16200
+ const onListening = () => {
16201
+ server.off("error", onError);
16202
+ resolve();
16203
+ };
16204
+ server.once("error", onError);
16205
+ server.once("listening", onListening);
16206
+ server.listen(options.port, currentHost);
15512
16207
  });
15513
16208
 
16209
+ const urlHost = formatUrlHost(currentHost);
16210
+ console.log(`Pi Web UI: http://${urlHost}:${options.port}/`);
16211
+ console.log(`Working directory: ${options.cwd}`);
16212
+ if (!isLocalHost(currentHost)) {
16213
+ console.warn(`WARNING: Web UI is exposed to the network. Remote PIN auth is ${remoteAuth.pin ? "enabled" : "OFF"}; only expose it on trusted networks.`);
16214
+ }
16215
+
16216
+ const startupAudit = await optionalFeatureAuditCoordinator.recheck({ reason: "startup" });
16217
+ if (options.migrationDryRun) {
16218
+ console.log(`Optional feature migration dry run:\n${JSON.stringify(startupAudit, null, 2)}`);
16219
+ } else if (options.migrateOptionalFeatures) {
16220
+ const featureIds = startupAudit.features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId);
16221
+ if (featureIds.length) {
16222
+ const result = await runOptionalFeatureBatchMutation({ revision: startupAudit.revision, featureIds, cwd: options.cwd, migration: true });
16223
+ console.log(`Optional feature migration: ${result.succeeded} succeeded, ${result.failed} failed.`);
16224
+ }
16225
+ }
16226
+
16227
+ rpcSupervisor = await initializeRpcSupervisor();
16228
+ rpcSupervisorSnapshot = rpcSupervisor?.snapshot || null;
16229
+ installRpcSupervisorEventDispatch(rpcSupervisorSnapshot);
16230
+ const initialTabs = await createInitialTabs();
16231
+ await finishRpcSupervisorStartup(initialTabs);
16232
+ const initialTab = initialTabs[0] || null;
16233
+ optionalFeatureStartupReady = true;
16234
+ if (initialTab) console.log(`Pi RPC: ${initialTab.rpc.displayCommand}`);
16235
+ else console.log("Pi RPC: waiting for CWD selection in the Web UI");
16236
+ if (restoreTabs.length) console.log(`Restored Web UI tabs: ${initialTabs.length}`);
16237
+
15514
16238
  let shutdownInProgress = false;
15515
16239
 
15516
16240
  async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {}) {