@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/public/app.js CHANGED
@@ -20,6 +20,7 @@ const elements = {
20
20
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
21
21
  splitTabButton: $("#splitTabButton"),
22
22
  workspaceSaveButton: $("#workspaceSaveButton"),
23
+ summaryHeaderButton: $("#summaryHeaderButton"),
23
24
  newTabMenu: $("#newTabMenu"),
24
25
  newTabButton: $("#newTabButton"),
25
26
  newTabMenuPanel: $("#newTabMenuPanel"),
@@ -139,6 +140,7 @@ const elements = {
139
140
  remoteMicStreamingConsentButton: $("#remoteMicStreamingConsentButton"),
140
141
  newSessionButton: $("#newSessionButton"),
141
142
  compactButton: $("#compactButton"),
143
+ summaryActionButton: $("#summaryActionButton"),
142
144
  workflowModeControls: $("#workflowModeControls"),
143
145
  workflowModeButton: $("#workflowModeButton"),
144
146
  workflowOverlayOpenButton: $("#workflowOverlayOpenButton"),
@@ -165,6 +167,7 @@ const elements = {
165
167
  optionsNameButton: $("#optionsNameButton"),
166
168
  optionsCloneButton: $("#optionsCloneButton"),
167
169
  optionsSettingsButton: $("#optionsSettingsButton"),
170
+ optionsSummarySetupButton: $("#optionsSummarySetupButton"),
168
171
  optionsWorkflowSetupButton: $("#optionsWorkflowSetupButton"),
169
172
  optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
170
173
  optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
@@ -238,6 +241,17 @@ const elements = {
238
241
  agentDoneNotificationsToggle: $("#agentDoneNotificationsToggle"),
239
242
  agentDoneNotificationsStatus: $("#agentDoneNotificationsStatus"),
240
243
  optionalFeaturesBox: $("#optionalFeaturesBox"),
244
+ optionalFeatureMigrationSurface: $("#optionalFeatureMigrationSurface"),
245
+ optionalFeatureMigrationDialog: $("#optionalFeatureMigrationDialog"),
246
+ optionalFeatureMigrationDialogTitle: $("#optionalFeatureMigrationDialogTitle"),
247
+ optionalFeatureMigrationDialogMessage: $("#optionalFeatureMigrationDialogMessage"),
248
+ optionalFeatureMigrationDialogSummary: $("#optionalFeatureMigrationDialogSummary"),
249
+ optionalFeatureMigrationChooseDetails: $("#optionalFeatureMigrationChooseDetails"),
250
+ optionalFeatureMigrationChoices: $("#optionalFeatureMigrationChoices"),
251
+ optionalFeatureMigrationDialogError: $("#optionalFeatureMigrationDialogError"),
252
+ optionalFeatureMigrationCancelButton: $("#optionalFeatureMigrationCancelButton"),
253
+ optionalFeatureMigrationLaterButton: $("#optionalFeatureMigrationLaterButton"),
254
+ optionalFeatureMigrationConfirmButton: $("#optionalFeatureMigrationConfirmButton"),
241
255
  codexUsageBox: $("#codexUsageBox"),
242
256
  refreshCodexUsageButton: $("#refreshCodexUsageButton"),
243
257
  codexFastModeSelect: $("#codexFastModeSelect"),
@@ -354,6 +368,14 @@ const elements = {
354
368
  attachmentTextStatus: $("#attachmentTextStatus"),
355
369
  attachmentTextCancelButton: $("#attachmentTextCancelButton"),
356
370
  attachmentTextSaveButton: $("#attachmentTextSaveButton"),
371
+ sessionSummaryOverlay: $("#sessionSummaryOverlay"),
372
+ sessionSummaryOverlayTitle: $("#sessionSummaryOverlayTitle"),
373
+ sessionSummaryOverlayMeta: $("#sessionSummaryOverlayMeta"),
374
+ sessionSummaryOverlayStatus: $("#sessionSummaryOverlayStatus"),
375
+ sessionSummaryOverlayBody: $("#sessionSummaryOverlayBody"),
376
+ sessionSummaryOverlayCloseButton: $("#sessionSummaryOverlayCloseButton"),
377
+ sessionSummaryOverlayCopyButton: $("#sessionSummaryOverlayCopyButton"),
378
+ sessionSummaryOverlayRefreshButton: $("#sessionSummaryOverlayRefreshButton"),
357
379
  commandSearchInput: $("#commandSearchInput"),
358
380
  commandsBox: $("#commandsBox"),
359
381
  eventLog: $("#eventLog"),
@@ -600,6 +622,9 @@ let gitChangesRequestSerial = 0;
600
622
  const gitChangesUntrackedContentRequests = new Set();
601
623
  let nativeCommandTabId = null;
602
624
  let nativeSettingsDirty = false;
625
+ let sessionSummaryOverlayTabId = null;
626
+ let sessionSummaryOverlayFocusReturn = null;
627
+ const sessionSummaryByTab = new Map();
603
628
  let pathPickerState = null;
604
629
  let firstTerminalCwdPromptShown = false;
605
630
  let pathFastPicks = [];
@@ -2799,7 +2824,11 @@ const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
2799
2824
  HIDDEN_COMMAND_NAMES.add("stats-webui");
2800
2825
  HIDDEN_COMMAND_NAMES.add("btw-status");
2801
2826
  HIDDEN_COMMAND_NAMES.add("btw-transfer");
2802
- const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "workflow-setup", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
2827
+ const SESSION_SUMMARY_PROTOCOL_VERSION = 1;
2828
+ const SESSION_SUMMARY_MARKDOWN_MAX_CHARS = 16 * 1024;
2829
+ const SESSION_SUMMARY_PROMPT_MAX_CHARS = 8 * 1024;
2830
+ const SESSION_SUMMARY_REQUEST_TIMEOUT_MS = 110 * 1000;
2831
+ const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "summary", "summary-setup", "workflow-setup", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
2803
2832
  const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
2804
2833
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
2805
2834
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
@@ -2827,6 +2856,29 @@ const optionalFeaturePackageStatuses = new Map();
2827
2856
  const optionalFeatureInstallMessages = new Map();
2828
2857
  const optionalFeatureInstallStates = new Map();
2829
2858
  const optionalFeatureInstallProgressTimers = new Map();
2859
+ const optionalFeatureMigrationResultEvents = new Set();
2860
+ const OPTIONAL_FEATURE_READY_AUTO_DISMISS_MS = 5_000;
2861
+ let optionalFeatureBatchState = null;
2862
+ let optionalFeatureMigrationSnapshot = {
2863
+ phase: "checking",
2864
+ revision: "pending",
2865
+ installKind: "unknown",
2866
+ summary: { ready: 0, migratable: 0, missing: 0, conflicts: 0, disabled: 0, unknown: 0 },
2867
+ features: [],
2868
+ progress: null,
2869
+ completedAt: null,
2870
+ diagnostic: null,
2871
+ };
2872
+ let optionalFeatureMigrationCheckingStartedAt = Date.now();
2873
+ let optionalFeatureMigrationRenderTimer = null;
2874
+ let optionalFeatureMigrationReadyDismissTimer = null;
2875
+ let optionalFeatureMigrationPendingReadyDismissKey = "";
2876
+ let optionalFeatureMigrationDismissedReadyKey = "";
2877
+ let optionalFeatureMigrationDialogState = null;
2878
+ let optionalFeatureMigrationLastPhase = "";
2879
+ let optionalFeatureMigrationCompletionFocusKey = "";
2880
+ let optionalFeatureRestartNotice = null;
2881
+ let optionalFeaturePackageStatusesLoaded = false;
2830
2882
  let optionalFeaturePackageStatusError = "";
2831
2883
  const gitFooterPayloadRefreshInFlightByTab = new Set();
2832
2884
  const gitFooterPayloadStateByTab = new Map();
@@ -7137,8 +7189,8 @@ function renderUpdateNotification(status = latestUpdateStatus, { force = false }
7137
7189
  if (elements.updateNotificationMessage) {
7138
7190
  let message = "Updates are available. Direct Web UI updates are only enabled from localhost on the host machine.";
7139
7191
  if (canRunUpdate) {
7140
- if (hasPiUpdate && hasPackageUpdate) message = "Run pi update --self for Pi only, or update all to use pi update --all when supported and include Web UI, Optional Features, configured Pi packages, and detected Pi package roots, then restart this Web UI server automatically.";
7141
- else if (hasPackageUpdate) message = "Update all checks for pi update --all support, then refreshes Web UI/package entries, Optional Features, configured Pi packages, and detected Pi package roots before restarting this Web UI server automatically.";
7192
+ if (hasPiUpdate && hasPackageUpdate) message = "Run pi update --self for Pi only, or update all to use Pi for configured packages and Optional Features while refreshing detected core Pi/Web UI package roots, then restart this Web UI server automatically.";
7193
+ else if (hasPackageUpdate) message = "Update all uses Pi for configured packages and Optional Features, then refreshes detected core Pi/Web UI package roots before restarting this Web UI server automatically.";
7142
7194
  else message = "Run pi update --self for Pi only, then restart this Web UI server automatically.";
7143
7195
  }
7144
7196
  elements.updateNotificationMessage.textContent = message;
@@ -7380,8 +7432,8 @@ function piUpdateConfirmationText({ all = false } = {}) {
7380
7432
  const workingWarning = hasWorkingTab() ? "\n\nOne or more Pi tabs look busy or blocked. Finish or abort in-flight work before updating if you need to preserve it." : "";
7381
7433
  const versionText = items.length ? `\n\nDetected update: ${items.join(" · ")}.` : "";
7382
7434
  const commandText = all ? '"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"' : '"pi update --self"';
7383
- const scope = all ? "Pi, configured packages, Optional Features, and detected Pi package roots" : "Pi only";
7384
- const extra = all ? " It will also run npm/bun package updates for detected Web UI, Optional Feature, agent, project, and global Pi package roots." : "";
7435
+ const scope = all ? "Pi, configured packages including Optional Features, and detected core Pi/Web UI package roots" : "Pi only";
7436
+ const extra = all ? " Pi owns configured Optional Feature updates; direct npm/bun updates are limited to detected core Pi/Web UI package roots." : "";
7385
7437
  return `Run ${scope} now?${versionText}\n\nThis will run ${commandText} on the Web UI host.${extra} After it finishes, Pi Web UI will restart itself. Browser clients will briefly disconnect, and managed Pi tabs/RPC processes will be restarted from saved session state when possible.${workingWarning}`;
7386
7438
  }
7387
7439
 
@@ -9213,6 +9265,7 @@ async function handleVoiceConversationTurnEnd(tabContext = activeTabContext()) {
9213
9265
 
9214
9266
  function renderOptionalFeatureDependentDisplays() {
9215
9267
  renderOptionalFeatureControls();
9268
+ if (elements.optionalFeatureMigrationDialog?.open) renderOptionalFeatureMigrationDialog();
9216
9269
  renderThemeSelect();
9217
9270
  renderWidgets();
9218
9271
  renderStatus();
@@ -9720,10 +9773,12 @@ function setActiveTabId(tabId, { remember = false } = {}) {
9720
9773
  if (nextTabId !== activeTabId) {
9721
9774
  activeTabGeneration += 1;
9722
9775
  closeFeatureDecisionDialog({ restoreFocus: false });
9776
+ closeSessionSummaryOverlay({ restoreFocus: false });
9723
9777
  }
9724
9778
  activeTabId = nextTabId;
9725
9779
  bindGitWorkflowToActiveTab();
9726
9780
  renderFeatureCategoryTag(nextTabId);
9781
+ renderSessionSummaryControls();
9727
9782
  if (remember) rememberActiveTab();
9728
9783
  return activeTabContext(nextTabId);
9729
9784
  }
@@ -12424,6 +12479,7 @@ function syncTabMetadata(nextTabs = []) {
12424
12479
  setTabActivity(tab.id, tab.activity);
12425
12480
  if (Object.prototype.hasOwnProperty.call(tab, "appRunner")) setAppRunnerData(tab.id, { activeRun: tab.appRunner });
12426
12481
  if (Object.prototype.hasOwnProperty.call(tab, "conversationMode")) updateConversationModeForTab(tab.id, tab.conversationMode, { render: false });
12482
+ if (tab.sessionSummary) updateSessionSummaryForTab(tab.id, tab.sessionSummary);
12427
12483
  }
12428
12484
  for (const tabId of tabActivities.keys()) {
12429
12485
  if (!liveIds.has(tabId)) {
@@ -12450,6 +12506,8 @@ function syncTabMetadata(nextTabs = []) {
12450
12506
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
12451
12507
  clearGitWorkflowForTab(tabId);
12452
12508
  commandCatalogsByTab.delete(tabId);
12509
+ sessionSummaryByTab.delete(tabId);
12510
+ if (sessionSummaryOverlayTabId === tabId) closeSessionSummaryOverlay({ restoreFocus: false });
12453
12511
  clearGitFooterPayloadState(tabId);
12454
12512
  gitFooterPayloadRequestSerialByTab.delete(tabId);
12455
12513
  }
@@ -12467,8 +12525,10 @@ function applyTabMetadata(tab) {
12467
12525
  else tabs[index] = { ...tabs[index], ...tab };
12468
12526
  if (tab.activity) setTabActivity(tab.id, tab.activity);
12469
12527
  if (Object.prototype.hasOwnProperty.call(tab, "conversationMode")) updateConversationModeForTab(tab.id, tab.conversationMode, { render: false });
12528
+ if (tab.sessionSummary) updateSessionSummaryForTab(tab.id, tab.sessionSummary);
12470
12529
  renderConversationModeControls();
12471
12530
  renderWorkflowModeControls();
12531
+ renderSessionSummaryControls();
12472
12532
  renderTabs();
12473
12533
  return true;
12474
12534
  }
@@ -33864,6 +33924,26 @@ function optionalFeaturePackageStatus(featureId) {
33864
33924
  return optionalFeaturePackageStatuses.get(featureId) || null;
33865
33925
  }
33866
33926
 
33927
+ function optionalFeatureManualInstallCommand(feature) {
33928
+ return feature?.packageName ? `pi install npm:${feature.packageName}` : "";
33929
+ }
33930
+
33931
+ function optionalFeatureNeedsInstall(feature) {
33932
+ const status = optionalFeaturePackageStatus(feature?.id);
33933
+ if (!status || isOptionalFeatureDisabled(feature?.id)) return false;
33934
+ const legacyNeedsInstall = status.ready !== true && status.resourceConflict !== true;
33935
+ if (status.state) return ["missing", "legacy-migratable"].includes(status.state) && status.resourceConflict !== true;
33936
+ return legacyNeedsInstall;
33937
+ }
33938
+
33939
+ function optionalFeatureBatchCandidates(features = OPTIONAL_FEATURES) {
33940
+ return features.filter((feature) => optionalFeatureNeedsInstall(feature));
33941
+ }
33942
+
33943
+ function optionalFeatureBatchIsActive() {
33944
+ return optionalFeatureBatchState?.phase === "running";
33945
+ }
33946
+
33867
33947
  function optionalFeaturePackageVersionLabel(status) {
33868
33948
  if (!status?.installedVersion) return "";
33869
33949
  return status.declaredSpec ? `${status.installedVersion} (expects ${status.declaredSpec})` : status.installedVersion;
@@ -33928,13 +34008,24 @@ function optionalFeatureInstallFailureFromError(error) {
33928
34008
  const message = details.message || error?.message || String(error);
33929
34009
  const hint = details.hint || (error?.backendOffline
33930
34010
  ? "The Web UI server connection failed. Check that pi-webui is still running, then retry."
33931
- : "Run the shown npm command manually from the Web UI host to inspect the full package-manager output.");
34011
+ : "Run the shown Pi command manually from the Web UI host to inspect the full installer output.");
33932
34012
  return { ...details, message, hint, statusCode: error?.statusCode };
33933
34013
  }
33934
34014
 
34015
+ function optionalFeatureInstallFailureFromBatchResult(result, feature) {
34016
+ const details = result?.optionalFeatureInstall || {};
34017
+ return {
34018
+ ...details,
34019
+ message: details.message || result?.error || `Pi could not install ${feature.packageName}`,
34020
+ hint: details.hint || "Run the shown Pi command manually from the Web UI host to inspect the full installer output.",
34021
+ command: details.command || optionalFeatureManualInstallCommand(feature),
34022
+ };
34023
+ }
34024
+
33935
34025
  async function copyOptionalFeatureInstallCommand(featureId) {
34026
+ const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
33936
34027
  const state = optionalFeatureInstallState(featureId);
33937
- const command = String(state?.command || "").trim();
34028
+ const command = String(state?.command || optionalFeatureManualInstallCommand(feature)).trim();
33938
34029
  if (!command) {
33939
34030
  addEvent("optional feature install command is not available yet", "warn");
33940
34031
  return;
@@ -33947,6 +34038,485 @@ async function copyOptionalFeatureInstallCommand(featureId) {
33947
34038
  }
33948
34039
  }
33949
34040
 
34041
+ function optionalFeatureAuditFeature(featureId) {
34042
+ return optionalFeatureMigrationSnapshot.features.find((feature) => feature?.featureId === featureId) || null;
34043
+ }
34044
+
34045
+ function optionalFeatureDisplayLabel(featureId, packageName = "") {
34046
+ return OPTIONAL_FEATURE_BY_ID.get(featureId)?.label || packageName || featureId || "optional feature";
34047
+ }
34048
+
34049
+ function optionalFeatureCandidateSignature(snapshot, featureIds) {
34050
+ const requested = new Set(featureIds || []);
34051
+ return (snapshot?.features || [])
34052
+ .filter((feature) => requested.has(feature.featureId))
34053
+ .map((feature) => `${feature.featureId}:${feature.state}:${feature.sourceKind}:${feature.previouslyEnabled === true}`)
34054
+ .sort()
34055
+ .join("|");
34056
+ }
34057
+
34058
+ function optionalFeatureMigrationCandidates(featureIds = null, { includeBrowserDisabled = false } = {}) {
34059
+ const requested = featureIds ? new Set(featureIds) : null;
34060
+ return (optionalFeatureMigrationSnapshot.features || []).filter((feature) => {
34061
+ if (feature?.state !== "legacy-migratable") return false;
34062
+ if (requested && !requested.has(feature.featureId)) return false;
34063
+ return includeBrowserDisabled || !isOptionalFeatureDisabled(feature.featureId);
34064
+ });
34065
+ }
34066
+
34067
+ function optionalFeatureMigrationElapsedMs() {
34068
+ const progress = optionalFeatureMigrationSnapshot.progress;
34069
+ if (progress?.startedAt) {
34070
+ const startedAt = Date.parse(progress.startedAt);
34071
+ if (Number.isFinite(startedAt)) return Math.max(Number(progress.elapsedMs) || 0, Date.now() - startedAt);
34072
+ }
34073
+ if (optionalFeatureMigrationSnapshot.phase === "checking") return Date.now() - optionalFeatureMigrationCheckingStartedAt;
34074
+ return Number(progress?.elapsedMs) || 0;
34075
+ }
34076
+
34077
+ function optionalFeatureMigrationProgressText(progress = optionalFeatureMigrationSnapshot.progress) {
34078
+ if (!progress) return "";
34079
+ const elapsed = formatDuration(optionalFeatureMigrationElapsedMs());
34080
+ if (progress.phase === "migrating" && progress.currentFeatureId) {
34081
+ const label = optionalFeatureDisplayLabel(progress.currentFeatureId, progress.currentPackageName);
34082
+ return `Installing ${progress.index || (progress.completed || 0) + 1} of ${progress.total || 0}: ${label}${elapsed ? ` · elapsed ${elapsed}` : ""}`;
34083
+ }
34084
+ if (progress.phase === "partial") return `${progress.succeeded || 0} succeeded · ${progress.failed || 0} failed${elapsed ? ` · finished after ${elapsed}` : ""}`;
34085
+ if (progress.phase === "complete") return `${progress.succeeded || progress.total || 0} installed successfully${elapsed ? ` · finished after ${elapsed}` : ""}`;
34086
+ return "";
34087
+ }
34088
+
34089
+ function optionalFeatureMigrationPhaseMessage(phase) {
34090
+ switch (phase) {
34091
+ case "checking": return "checking optional features";
34092
+ case "ready": return "optional feature audit ready";
34093
+ case "action-required": return "optional feature audit needs attention";
34094
+ case "migrating": return "optional feature migration started";
34095
+ case "partial": return "optional feature migration finished with failures";
34096
+ case "complete": return "optional feature migration completed";
34097
+ case "degraded": return "optional feature audit degraded; Web UI is running core-only";
34098
+ default: return "";
34099
+ }
34100
+ }
34101
+
34102
+ function rememberOptionalFeatureMigrationEvent(key) {
34103
+ optionalFeatureMigrationResultEvents.add(key);
34104
+ while (optionalFeatureMigrationResultEvents.size > 256) optionalFeatureMigrationResultEvents.delete(optionalFeatureMigrationResultEvents.values().next().value);
34105
+ }
34106
+
34107
+ function announceOptionalFeatureMigrationSnapshot(snapshot) {
34108
+ if (snapshot.phase !== optionalFeatureMigrationLastPhase) {
34109
+ optionalFeatureMigrationLastPhase = snapshot.phase;
34110
+ const message = optionalFeatureMigrationPhaseMessage(snapshot.phase);
34111
+ if (message) addEvent(message, ["degraded", "action-required", "partial"].includes(snapshot.phase) ? "warn" : "info");
34112
+ }
34113
+ const progress = snapshot.progress;
34114
+ if (progress?.phase === "migrating" && progress.currentFeatureId) {
34115
+ const startKey = `${progress.startedAt || snapshot.revision}:start:${progress.currentFeatureId}`;
34116
+ if (!optionalFeatureMigrationResultEvents.has(startKey)) {
34117
+ rememberOptionalFeatureMigrationEvent(startKey);
34118
+ addEvent(optionalFeatureMigrationProgressText(progress), "info");
34119
+ }
34120
+ }
34121
+ for (const result of progress?.results || []) {
34122
+ const key = `${progress.startedAt || snapshot.revision}:${result.featureId}:${result.ok}:${result.kind || ""}`;
34123
+ if (optionalFeatureMigrationResultEvents.has(key)) continue;
34124
+ rememberOptionalFeatureMigrationEvent(key);
34125
+ const label = optionalFeatureDisplayLabel(result.featureId, result.packageName);
34126
+ addEvent(`${label}: ${result.ok ? "installed and verified" : result.message || "installation failed"}`, result.ok ? "info" : "error");
34127
+ }
34128
+ }
34129
+
34130
+ function applyOptionalFeatureProgressStates(snapshot) {
34131
+ const progress = snapshot.progress;
34132
+ if (!progress) return;
34133
+ const startedAt = Number.isFinite(Date.parse(progress.startedAt || "")) ? Date.parse(progress.startedAt) : Date.now();
34134
+ for (const result of progress.results || []) {
34135
+ const feature = OPTIONAL_FEATURE_BY_ID.get(result.featureId);
34136
+ const previous = optionalFeatureInstallState(result.featureId) || {};
34137
+ optionalFeatureInstallStates.set(result.featureId, {
34138
+ ...previous,
34139
+ phase: result.ok ? "done" : "failed",
34140
+ actionLabel: progress.migration ? "Migrate" : "Install",
34141
+ startedAt: previous.startedAt || startedAt,
34142
+ endedAt: progress.completedAt ? Date.parse(progress.completedAt) || Date.now() : Date.now(),
34143
+ detail: result.message || (result.ok ? "Installed and verified" : "Installation failed"),
34144
+ hint: result.ok ? "The server verified this package registration." : "Retry this package or run the copied Pi command on the Web UI host.",
34145
+ command: previous.command || optionalFeatureManualInstallCommand(feature),
34146
+ errorKind: result.kind || previous.errorKind || "",
34147
+ });
34148
+ }
34149
+ if (progress.phase === "migrating" && progress.currentFeatureId) {
34150
+ const current = OPTIONAL_FEATURE_BY_ID.get(progress.currentFeatureId);
34151
+ const previous = optionalFeatureInstallState(progress.currentFeatureId) || {};
34152
+ optionalFeatureInstallStates.set(progress.currentFeatureId, {
34153
+ ...previous,
34154
+ phase: "installing",
34155
+ actionLabel: progress.migration ? "Migrate" : "Install",
34156
+ startedAt: previous.startedAt || startedAt,
34157
+ endedAt: 0,
34158
+ detail: optionalFeatureMigrationProgressText(progress),
34159
+ hint: "Pi installs packages sequentially. This operation continues if the browser disconnects.",
34160
+ command: previous.command || optionalFeatureManualInstallCommand(current),
34161
+ });
34162
+ }
34163
+ if (progress.restartDeferred === true) {
34164
+ optionalFeatureRestartNotice = { autoRestarted: false, restartDeferred: true, tabId: activeTabId };
34165
+ } else if (progress.autoRestarted === true) {
34166
+ optionalFeatureRestartNotice = { autoRestarted: true, restartDeferred: false, tabId: activeTabId };
34167
+ }
34168
+ optionalFeatureBatchState = {
34169
+ phase: progress.phase === "migrating" ? "running" : progress.phase === "partial" ? "failed" : "done",
34170
+ scopeLabel: progress.migration ? "previous optional features" : "optional features",
34171
+ total: progress.total || 0,
34172
+ succeeded: progress.succeeded ?? (progress.results || []).filter((result) => result.ok).length,
34173
+ failed: progress.failed ?? (progress.results || []).filter((result) => !result.ok).length,
34174
+ startedAt,
34175
+ endedAt: progress.completedAt ? Date.parse(progress.completedAt) || Date.now() : 0,
34176
+ };
34177
+ }
34178
+
34179
+ function refreshOptionalFeatureMigrationElapsedText() {
34180
+ const detail = elements.optionalFeatureMigrationSurface?.querySelector(".optional-feature-migration-detail");
34181
+ if (!detail) return;
34182
+ if (optionalFeatureMigrationSnapshot.phase === "checking") {
34183
+ const elapsed = optionalFeatureMigrationElapsedMs();
34184
+ detail.textContent = elapsed >= 1000 ? `Read-only startup audit · elapsed ${formatDuration(elapsed)}` : "Read-only startup audit";
34185
+ } else if (optionalFeatureMigrationSnapshot.phase === "migrating") {
34186
+ detail.textContent = optionalFeatureMigrationProgressText(optionalFeatureMigrationSnapshot.progress) || "Preparing sequential Pi installs…";
34187
+ }
34188
+ }
34189
+
34190
+ function ensureOptionalFeatureMigrationRenderTimer() {
34191
+ const timed = ["checking", "migrating"].includes(optionalFeatureMigrationSnapshot.phase);
34192
+ if (timed && !optionalFeatureMigrationRenderTimer) {
34193
+ optionalFeatureMigrationRenderTimer = setInterval(() => {
34194
+ refreshOptionalFeatureMigrationElapsedText();
34195
+ if (optionalFeatureMigrationSnapshot.phase === "migrating") renderOptionalFeaturePanel();
34196
+ }, 1000);
34197
+ } else if (!timed && optionalFeatureMigrationRenderTimer) {
34198
+ clearInterval(optionalFeatureMigrationRenderTimer);
34199
+ optionalFeatureMigrationRenderTimer = null;
34200
+ }
34201
+ }
34202
+
34203
+ function clearOptionalFeatureReadyDismissTimer() {
34204
+ if (optionalFeatureMigrationReadyDismissTimer) clearTimeout(optionalFeatureMigrationReadyDismissTimer);
34205
+ optionalFeatureMigrationReadyDismissTimer = null;
34206
+ optionalFeatureMigrationPendingReadyDismissKey = "";
34207
+ }
34208
+
34209
+ function optionalFeatureReadyDismissKey(snapshot = optionalFeatureMigrationSnapshot) {
34210
+ return snapshot.phase === "ready" ? String(snapshot.revision || "pending") : "";
34211
+ }
34212
+
34213
+ function scheduleOptionalFeatureReadyDismiss(key) {
34214
+ if (!key) {
34215
+ clearOptionalFeatureReadyDismissTimer();
34216
+ if (optionalFeatureMigrationSnapshot.phase !== "ready") optionalFeatureMigrationDismissedReadyKey = "";
34217
+ return;
34218
+ }
34219
+ if (optionalFeatureMigrationDismissedReadyKey === key) return;
34220
+ if (optionalFeatureMigrationReadyDismissTimer && optionalFeatureMigrationPendingReadyDismissKey === key) return;
34221
+ clearOptionalFeatureReadyDismissTimer();
34222
+ optionalFeatureMigrationPendingReadyDismissKey = key;
34223
+ optionalFeatureMigrationReadyDismissTimer = setTimeout(() => {
34224
+ optionalFeatureMigrationReadyDismissTimer = null;
34225
+ optionalFeatureMigrationPendingReadyDismissKey = "";
34226
+ if (optionalFeatureReadyDismissKey() !== key || optionalFeatureRestartNotice) return;
34227
+ optionalFeatureMigrationDismissedReadyKey = key;
34228
+ const surface = elements.optionalFeatureMigrationSurface;
34229
+ if (!surface) return;
34230
+ surface.replaceChildren();
34231
+ surface.hidden = true;
34232
+ }, OPTIONAL_FEATURE_READY_AUTO_DISMISS_MS);
34233
+ }
34234
+
34235
+ function optionalFeatureMigrationAction(label, handler, className = "") {
34236
+ const button = make("button", className, label);
34237
+ button.type = "button";
34238
+ button.addEventListener("click", handler);
34239
+ return button;
34240
+ }
34241
+
34242
+ function optionalFeatureConflictDescription(feature) {
34243
+ return `${optionalFeatureDisplayLabel(feature.featureId, feature.packageName)}: Pi package + top-level resource; the top-level copy was safely excluded.`;
34244
+ }
34245
+
34246
+ async function copyOptionalFeatureConflictFix(feature) {
34247
+ const text = [
34248
+ `Recommended fix for ${feature.packageName}:`,
34249
+ "Keep the registered Pi package as the canonical source.",
34250
+ "Disable or remove the duplicate top-level extension/skill/prompt/theme alias, then use Recheck in Pi Web UI.",
34251
+ ].join("\n");
34252
+ try {
34253
+ await copyText(text);
34254
+ addEvent(`copied recommended conflict fix for ${optionalFeatureDisplayLabel(feature.featureId, feature.packageName)}`, "info");
34255
+ } catch (error) {
34256
+ addEvent(`could not copy optional feature conflict fix: ${error.message || String(error)}`, "warn");
34257
+ }
34258
+ }
34259
+
34260
+ function optionalFeatureFailureOutputTail() {
34261
+ const tails = [];
34262
+ for (const [featureId, state] of optionalFeatureInstallStates) {
34263
+ if (state?.phase !== "failed" || !state.outputTail) continue;
34264
+ tails.push(`${optionalFeatureDisplayLabel(featureId)}\n${String(state.outputTail).slice(-2000)}`);
34265
+ }
34266
+ return tails.join("\n\n").slice(-4000);
34267
+ }
34268
+
34269
+ async function restartOptionalFeatureTab() {
34270
+ const tabId = optionalFeatureRestartNotice?.tabId || activeTabId;
34271
+ try {
34272
+ await sendPrompt("prompt", "/reload", { targetTabId: tabId, throwOnError: true });
34273
+ optionalFeatureRestartNotice = null;
34274
+ renderOptionalFeatureMigrationSurface();
34275
+ } catch (error) {
34276
+ addEvent(`optional feature tab restart failed: ${error.message || String(error)}`, "error");
34277
+ }
34278
+ }
34279
+
34280
+ function renderOptionalFeatureMigrationSurface() {
34281
+ const surface = elements.optionalFeatureMigrationSurface;
34282
+ if (!surface) return;
34283
+ const snapshot = optionalFeatureMigrationSnapshot;
34284
+ const summary = snapshot.summary || {};
34285
+ const conflicts = (snapshot.features || []).filter((feature) => feature.state === "conflict");
34286
+ const progress = snapshot.progress;
34287
+ const readyDismissKey = optionalFeatureReadyDismissKey(snapshot);
34288
+ const readyCanAutoDismiss = Boolean(readyDismissKey && !optionalFeatureRestartNotice);
34289
+ if (readyCanAutoDismiss && optionalFeatureMigrationDismissedReadyKey === readyDismissKey) {
34290
+ surface.replaceChildren();
34291
+ surface.hidden = true;
34292
+ ensureOptionalFeatureMigrationRenderTimer();
34293
+ return;
34294
+ }
34295
+ const card = make("div", `optional-feature-migration-card phase-${snapshot.phase}`);
34296
+ const copy = make("div", "optional-feature-migration-copy");
34297
+ const title = make("strong", "optional-feature-migration-title");
34298
+ const detail = make("span", "optional-feature-migration-detail");
34299
+ const actions = make("div", "optional-feature-migration-actions");
34300
+
34301
+ if (snapshot.phase === "checking") {
34302
+ title.textContent = "Checking optional features…";
34303
+ const elapsed = optionalFeatureMigrationElapsedMs();
34304
+ detail.textContent = elapsed >= 1000 ? `Read-only startup audit · elapsed ${formatDuration(elapsed)}` : "Read-only startup audit";
34305
+ } else if (snapshot.phase === "degraded") {
34306
+ title.textContent = "Web UI started safely without optional companions";
34307
+ detail.textContent = snapshot.diagnostic?.message || "The optional-feature audit could not establish a safe configuration.";
34308
+ actions.append(optionalFeatureMigrationAction("Recheck", () => recheckOptionalFeatureMigration(), "primary"));
34309
+ } else if (snapshot.phase === "migrating") {
34310
+ title.textContent = "Migrating optional features";
34311
+ detail.textContent = optionalFeatureMigrationProgressText(progress) || "Preparing sequential Pi installs…";
34312
+ } else if (snapshot.phase === "partial") {
34313
+ title.textContent = "Optional feature migration needs attention";
34314
+ detail.textContent = optionalFeatureMigrationProgressText(progress);
34315
+ const failedIds = (progress?.results || []).filter((result) => !result.ok).map((result) => result.featureId);
34316
+ if (failedIds.length) actions.append(optionalFeatureMigrationAction("Retry failed", () => openOptionalFeatureMigrationDialog({ featureIds: failedIds, retryFailed: true }), "primary"));
34317
+ actions.append(optionalFeatureMigrationAction("Copy commands", () => copyFailedOptionalFeatureCommands()));
34318
+ } else if (snapshot.phase === "complete") {
34319
+ title.textContent = "Optional feature migration complete";
34320
+ detail.textContent = optionalFeatureMigrationProgressText(progress) || `${summary.ready || 0} optional features ready`;
34321
+ } else if (snapshot.phase === "action-required") {
34322
+ title.textContent = conflicts.length ? "Optional feature conflicts were safely excluded" : "Previous optional features need migration";
34323
+ detail.textContent = conflicts.length
34324
+ ? conflicts.map(optionalFeatureConflictDescription).join(" ")
34325
+ : `${summary.migratable || 0} previously available companion${summary.migratable === 1 ? "" : "s"} can be restored${snapshot.installKind === "upgrade" ? " after this Web UI upgrade" : ""}.`;
34326
+ if (summary.migratable > 0) {
34327
+ actions.append(optionalFeatureMigrationAction("Migrate…", () => openOptionalFeatureMigrationDialog(), "primary"));
34328
+ actions.append(optionalFeatureMigrationAction("Later", () => dismissOptionalFeatureMigration()));
34329
+ }
34330
+ for (const conflict of conflicts) actions.append(optionalFeatureMigrationAction("Copy recommended fix", () => copyOptionalFeatureConflictFix(conflict)));
34331
+ if (conflicts.length) actions.append(optionalFeatureMigrationAction("Recheck", () => recheckOptionalFeatureMigration()));
34332
+ } else {
34333
+ title.textContent = `Core ready · ${summary.ready || 0} optional feature${summary.ready === 1 ? "" : "s"} ready`;
34334
+ detail.textContent = summary.migratable > 0
34335
+ ? "Migration was deferred. Restore remains available in Optional features."
34336
+ : summary.missing > 0 ? `${summary.missing} optional companion${summary.missing === 1 ? " is" : "s are"} not installed.` : "Optional feature audit complete.";
34337
+ }
34338
+
34339
+ copy.append(title, detail);
34340
+ card.append(copy);
34341
+ if (actions.childElementCount) card.append(actions);
34342
+
34343
+ if (conflicts.length) {
34344
+ const alert = make("div", "optional-feature-migration-alert sr-only", "Optional feature conflict detected; duplicate top-level resources were safely excluded.");
34345
+ alert.setAttribute("role", "alert");
34346
+ card.append(alert);
34347
+ }
34348
+ if (snapshot.phase === "partial") {
34349
+ const alert = make("div", "optional-feature-migration-alert sr-only", `${progress?.failed || 0} optional feature installations failed.`);
34350
+ alert.setAttribute("role", "alert");
34351
+ card.append(alert);
34352
+ }
34353
+ const outputTail = optionalFeatureFailureOutputTail();
34354
+ if (outputTail && snapshot.phase === "partial") card.append(make("pre", "optional-feature-migration-output", outputTail));
34355
+
34356
+ if (optionalFeatureRestartNotice) {
34357
+ const notice = make("div", "optional-feature-restart-notice");
34358
+ const noticeText = optionalFeatureRestartNotice.restartDeferred
34359
+ ? "New optional features are ready. Restart is deferred because the affected tab was busy."
34360
+ : "Restarted tab to load new features.";
34361
+ notice.append(make("span", undefined, noticeText));
34362
+ if (optionalFeatureRestartNotice.restartDeferred) {
34363
+ notice.append(optionalFeatureMigrationAction("Restart tab", () => restartOptionalFeatureTab(), "primary"));
34364
+ } else {
34365
+ notice.append(optionalFeatureMigrationAction("Dismiss", () => {
34366
+ optionalFeatureRestartNotice = null;
34367
+ renderOptionalFeatureMigrationSurface();
34368
+ }));
34369
+ }
34370
+ card.append(notice);
34371
+ }
34372
+
34373
+ const focusKey = ["complete", "partial"].includes(snapshot.phase) ? `${snapshot.revision}:${snapshot.phase}:${progress?.completedAt || ""}` : "";
34374
+ if (focusKey) {
34375
+ card.tabIndex = -1;
34376
+ card.classList.add("optional-feature-migration-completion-summary");
34377
+ }
34378
+ surface.replaceChildren(card);
34379
+ surface.hidden = false;
34380
+ ensureOptionalFeatureMigrationRenderTimer();
34381
+ scheduleOptionalFeatureReadyDismiss(readyCanAutoDismiss ? readyDismissKey : "");
34382
+ if (focusKey && focusKey !== optionalFeatureMigrationCompletionFocusKey) {
34383
+ optionalFeatureMigrationCompletionFocusKey = focusKey;
34384
+ queueMicrotask(() => card.isConnected && card.focus({ preventScroll: true }));
34385
+ }
34386
+ }
34387
+
34388
+ function applyOptionalFeatureMigrationSnapshot(snapshot, { announce = true } = {}) {
34389
+ if (!snapshot || typeof snapshot !== "object" || !Array.isArray(snapshot.features)) return false;
34390
+ if (snapshot.phase === "checking" && optionalFeatureMigrationSnapshot.phase !== "checking") optionalFeatureMigrationCheckingStartedAt = Date.now();
34391
+ optionalFeatureMigrationSnapshot = snapshot;
34392
+ optionalFeaturePackageStatuses.clear();
34393
+ for (const status of snapshot.features) {
34394
+ if (status?.featureId) optionalFeaturePackageStatuses.set(status.featureId, status);
34395
+ }
34396
+ optionalFeaturePackageStatusesLoaded = true;
34397
+ optionalFeaturePackageStatusError = "";
34398
+ applyOptionalFeatureProgressStates(snapshot);
34399
+ if (announce) announceOptionalFeatureMigrationSnapshot(snapshot);
34400
+ renderOptionalFeatureMigrationSurface();
34401
+ renderOptionalFeatureControls();
34402
+ return true;
34403
+ }
34404
+
34405
+ async function recheckOptionalFeatureMigration() {
34406
+ addEvent("rechecking optional features", "info");
34407
+ try {
34408
+ const response = await api("/api/optional-feature-migration/recheck", { method: "POST", body: {}, scoped: false });
34409
+ applyOptionalFeatureMigrationSnapshot(response.data);
34410
+ } catch (error) {
34411
+ addEvent(`optional feature recheck failed: ${error.message || String(error)}`, "error");
34412
+ }
34413
+ }
34414
+
34415
+ async function dismissOptionalFeatureMigration({ closeDialog = false, retryOnStale = true } = {}) {
34416
+ const revision = optionalFeatureMigrationSnapshot.revision;
34417
+ try {
34418
+ const response = await api("/api/optional-feature-migration/dismiss", { method: "POST", body: { revision }, scoped: false });
34419
+ applyOptionalFeatureMigrationSnapshot(response.data);
34420
+ if (closeDialog && elements.optionalFeatureMigrationDialog?.open) elements.optionalFeatureMigrationDialog.close();
34421
+ addEvent("optional feature migration deferred; the Migrate action remains available in Optional features", "info");
34422
+ } catch (error) {
34423
+ if (retryOnStale && error.statusCode === 409 && /stale|revision/i.test(error.message || "")) {
34424
+ await refreshOptionalFeaturePackageStatuses();
34425
+ return dismissOptionalFeatureMigration({ closeDialog, retryOnStale: false });
34426
+ }
34427
+ addEvent(`could not defer optional feature migration: ${error.message || String(error)}`, "error");
34428
+ }
34429
+ }
34430
+
34431
+ function renderOptionalFeatureMigrationDialog() {
34432
+ const state = optionalFeatureMigrationDialogState;
34433
+ if (!state || !elements.optionalFeatureMigrationChoices) return;
34434
+ const features = optionalFeatureMigrationCandidates(state.featureIds, { includeBrowserDisabled: true });
34435
+ const availableIds = new Set(features.map((feature) => feature.featureId));
34436
+ state.selected = new Set([...state.selected].filter((featureId) => availableIds.has(featureId) && !isOptionalFeatureDisabled(featureId)));
34437
+ elements.optionalFeatureMigrationChoices.replaceChildren();
34438
+
34439
+ for (const feature of features) {
34440
+ const item = make("div", "optional-feature-migration-choice");
34441
+ const choice = make("label", "optional-feature-migration-choice-label");
34442
+ const input = make("input");
34443
+ input.type = "checkbox";
34444
+ input.value = feature.featureId;
34445
+ input.checked = state.selected.has(feature.featureId);
34446
+ input.disabled = isOptionalFeatureDisabled(feature.featureId);
34447
+ input.addEventListener("change", () => {
34448
+ if (input.checked) state.selected.add(feature.featureId);
34449
+ else state.selected.delete(feature.featureId);
34450
+ renderOptionalFeatureMigrationDialog();
34451
+ });
34452
+ const label = make("span");
34453
+ label.append(make("strong", undefined, optionalFeatureDisplayLabel(feature.featureId, feature.packageName)));
34454
+ label.append(make("span", "optional-feature-migration-choice-package", feature.packageName));
34455
+ choice.append(input, label);
34456
+ const details = make("details", "optional-feature-migration-choice-details");
34457
+ details.append(
34458
+ make("summary", undefined, "Details"),
34459
+ make("span", undefined, `${feature.previouslyEnabled ? "Previously enabled" : "Previously disabled"} · source: ${feature.sourceKind || "legacy evidence"} · Pi will install ${feature.expectedSpec || feature.packageName}.`),
34460
+ );
34461
+ item.append(choice, details);
34462
+ elements.optionalFeatureMigrationChoices.append(item);
34463
+ }
34464
+
34465
+ const selectedFeatures = features.filter((feature) => state.selected.has(feature.featureId));
34466
+ elements.optionalFeatureMigrationDialogTitle.textContent = state.retryFailed ? "Retry failed optional features" : "Migrate optional features";
34467
+ elements.optionalFeatureMigrationDialogMessage.textContent = state.retryFailed
34468
+ ? "Retry only the failed packages. Successful packages stay installed. This is the only confirmation before retry."
34469
+ : "Previously enabled features are selected unless they are disabled in this browser. Pi installs the confirmed selection sequentially.";
34470
+ elements.optionalFeatureMigrationDialogSummary.textContent = selectedFeatures.length
34471
+ ? `${selectedFeatures.length} selected: ${selectedFeatures.map((feature) => optionalFeatureDisplayLabel(feature.featureId, feature.packageName)).join(", ")}. Pi may download code and update its package registration.`
34472
+ : "No features selected. Browser-disabled and previously disabled features remain unselected.";
34473
+ elements.optionalFeatureMigrationConfirmButton.textContent = state.retryFailed ? "Retry selected" : "Migrate selected";
34474
+ elements.optionalFeatureMigrationConfirmButton.disabled = selectedFeatures.length === 0 || optionalFeatureBatchIsActive();
34475
+ elements.optionalFeatureMigrationLaterButton.hidden = state.retryFailed;
34476
+ elements.optionalFeatureMigrationDialogError.hidden = !state.error;
34477
+ elements.optionalFeatureMigrationDialogError.textContent = state.error || "";
34478
+ elements.optionalFeatureMigrationChooseDetails.querySelector("summary").textContent = `Choose features (${selectedFeatures.length} selected)`;
34479
+ }
34480
+
34481
+ function openOptionalFeatureMigrationDialog({ featureIds = null, retryFailed = false } = {}) {
34482
+ const features = optionalFeatureMigrationCandidates(featureIds, { includeBrowserDisabled: true });
34483
+ if (!features.length) {
34484
+ addEvent("no migratable optional features are currently available", "info");
34485
+ return;
34486
+ }
34487
+ const selected = new Set(features
34488
+ .filter((feature) => retryFailed || feature.selectedByDefault === true)
34489
+ .filter((feature) => !isOptionalFeatureDisabled(feature.featureId))
34490
+ .map((feature) => feature.featureId));
34491
+ optionalFeatureMigrationDialogState = {
34492
+ featureIds: features.map((feature) => feature.featureId),
34493
+ selected,
34494
+ retryFailed,
34495
+ error: "",
34496
+ signature: optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, features.map((feature) => feature.featureId)),
34497
+ };
34498
+ renderOptionalFeatureMigrationDialog();
34499
+ if (!elements.optionalFeatureMigrationDialog.open) elements.optionalFeatureMigrationDialog.showModal();
34500
+ queueMicrotask(() => elements.optionalFeatureMigrationConfirmButton?.focus({ preventScroll: true }));
34501
+ }
34502
+
34503
+ async function copyFailedOptionalFeatureCommands() {
34504
+ const commands = [...optionalFeatureInstallStates]
34505
+ .filter(([, state]) => state?.phase === "failed")
34506
+ .map(([featureId, state]) => state.command || optionalFeatureManualInstallCommand(OPTIONAL_FEATURE_BY_ID.get(featureId)))
34507
+ .filter(Boolean);
34508
+ if (!commands.length) {
34509
+ addEvent("no failed optional feature commands are available", "warn");
34510
+ return;
34511
+ }
34512
+ try {
34513
+ await copyText([...new Set(commands)].join("\n"));
34514
+ addEvent(`copied ${new Set(commands).size} failed optional feature command${new Set(commands).size === 1 ? "" : "s"}`, "info");
34515
+ } catch (error) {
34516
+ addEvent(`could not copy failed optional feature commands: ${error.message || String(error)}`, "warn");
34517
+ }
34518
+ }
34519
+
33950
34520
  async function refreshQuestionnaireFeatureAvailability(tabContext = activeTabContext()) {
33951
34521
  if (!tabContext.tabId) return false;
33952
34522
  try {
@@ -33968,15 +34538,11 @@ async function refreshQuestionnaireFeatureAvailability(tabContext = activeTabCon
33968
34538
  async function refreshOptionalFeaturePackageStatuses({ announce = false } = {}) {
33969
34539
  try {
33970
34540
  const response = await api("/api/optional-features", { scoped: false });
33971
- optionalFeaturePackageStatusError = "";
33972
- optionalFeaturePackageStatuses.clear();
33973
- for (const status of response.data?.features || []) {
33974
- if (status?.featureId) optionalFeaturePackageStatuses.set(status.featureId, status);
33975
- }
34541
+ applyOptionalFeatureMigrationSnapshot(response.data, { announce: true });
33976
34542
  await refreshQuestionnaireFeatureAvailability();
33977
- renderOptionalFeatureControls();
33978
34543
  return true;
33979
34544
  } catch (error) {
34545
+ optionalFeaturePackageStatusesLoaded = false;
33980
34546
  optionalFeaturePackageStatusError = error.message || String(error);
33981
34547
  renderOptionalFeatureControls();
33982
34548
  if (announce) addEvent(`optional feature package status check failed: ${optionalFeaturePackageStatusError}`, "warn");
@@ -34105,27 +34671,52 @@ function optionalFeatureStatus(featureId) {
34105
34671
  return {
34106
34672
  label: optionalFeatureInstallPhaseLabel(installState),
34107
34673
  className: "updating",
34108
- detail: optionalFeatureInstallDetail(installState, installMessage || "npm install is running; waiting for package-manager output"),
34109
- hint: "The package manager may be quiet for a while; elapsed time updates here until npm exits.",
34110
- command: installState?.command || "",
34674
+ detail: optionalFeatureInstallDetail(installState, installMessage || "Pi install is running; waiting for installer output"),
34675
+ hint: "Pi may be quiet while resolving the package; elapsed time updates here until it exits.",
34676
+ command: installState?.command || optionalFeatureManualInstallCommand(feature),
34111
34677
  };
34112
34678
  }
34113
34679
  if (installState?.phase === "failed") {
34114
34680
  return {
34115
34681
  label: optionalFeatureInstallPhaseLabel(installState),
34116
34682
  className: "failed",
34117
- detail: optionalFeatureInstallDetail(installState, installState.detail || installMessage || "npm install failed"),
34118
- hint: installState.hint || "Copy the npm command and run it manually from the Web UI host for full diagnostics.",
34119
- command: installState.command || "",
34683
+ detail: optionalFeatureInstallDetail(installState, installState.detail || installMessage || "Pi install failed"),
34684
+ hint: installState.hint || "Copy the Pi command and run it manually from the Web UI host for full diagnostics.",
34685
+ command: installState.command || optionalFeatureManualInstallCommand(feature),
34120
34686
  };
34121
34687
  }
34122
34688
  const doneDetail = installState?.phase === "done" ? optionalFeatureInstallDetail(installState, installMessage) : "";
34689
+ if (disabled) return {
34690
+ label: "Disabled",
34691
+ className: "disabled",
34692
+ detail: `Disabled in this browser and excluded from migration selection${versionSuffix}`,
34693
+ hint: "Enable it in Optional features before installing or restoring it.",
34694
+ };
34695
+ if (!packageStatus && !detected) return { label: "Checking", className: "updating", detail: "Checking Pi installation and registration status…" };
34696
+ if (packageStatus?.resourceConflict) return {
34697
+ label: "Duplicate conflict",
34698
+ className: "failed",
34699
+ detail: `Configured both as a Pi package and as a top-level resource; remove one registration before reloading${versionSuffix}`,
34700
+ hint: "Do not install again. Keep either the package entry or the extensions/skills/prompts/themes alias, not both.",
34701
+ };
34123
34702
  if (packageStatus?.updateAvailable) return { label: "Update available", className: "updating", detail: packageStatus.updateReason || `Installed package is older than the Web UI expects${versionSuffix}` };
34124
34703
  if (detected && managedWithTools) return { label: "Loaded", className: "enabled", detail: doneDetail || `Detected in the active Pi tab; manage access in Tools${versionSuffix}`, command: installState?.command || "" };
34125
34704
  if (detected && !disabled) return { label: "Enabled", className: "enabled", detail: doneDetail || `Detected and enabled in Web UI${versionSuffix}`, command: installState?.command || "" };
34126
34705
  if (detected && disabled) return { label: "Disabled", className: "disabled", detail: `Detected, but disabled in Web UI${versionSuffix}` };
34127
- if (packageStatus?.installed) return { label: "Installed", className: "installed", detail: doneDetail || `Package is installed but not loaded in the active Pi tab${versionSuffix}`, command: installState?.command || "" };
34128
- return { label: "Install needed", className: "missing", detail: installMessage || "Package is not installed or not visible from the Web UI package root" };
34706
+ if (packageStatus?.locallyConfigured) return { label: "Available locally", className: "installed", detail: doneDetail || `Enabled as a top-level Pi resource; reload this tab if the capability is not detected yet${versionSuffix}` };
34707
+ if (packageStatus?.installed && packageStatus?.configured) return { label: "Installed", className: "installed", detail: doneDetail || `Registered with Pi but not loaded in the active tab${versionSuffix}`, command: installState?.command || "" };
34708
+ if (packageStatus?.installed && !packageStatus?.configured) return {
34709
+ label: "Registration needed",
34710
+ className: "missing",
34711
+ detail: doneDetail || `Package files exist, but the package is not registered in Pi settings${versionSuffix}`,
34712
+ command: optionalFeatureManualInstallCommand(feature),
34713
+ };
34714
+ return {
34715
+ label: "Install needed",
34716
+ className: "missing",
34717
+ detail: installMessage || "Package is not installed and registered with Pi",
34718
+ command: optionalFeatureManualInstallCommand(feature),
34719
+ };
34129
34720
  }
34130
34721
 
34131
34722
  function optionalFeatureTooltip(feature, status) {
@@ -34158,10 +34749,52 @@ function optionalFeatureWidgetHasSpecializedRenderer(key) {
34158
34749
  return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === AUR_REVIEW_RPC_WIDGET_KEY || key === "workflow:subprocess" || key === WORKFLOW_INSPECTOR_WIDGET_KEY;
34159
34750
  }
34160
34751
 
34752
+ function renderOptionalFeatureBatchToolbar() {
34753
+ const candidates = optionalFeatureBatchCandidates();
34754
+ const migratable = optionalFeatureMigrationCandidates();
34755
+ const busy = optionalFeatureBatchIsActive();
34756
+ const toolbar = make("div", "optional-feature-batch-toolbar");
34757
+ const action = make("button", "optional-feature-batch-action", busy ? "Installing…" : "Install all");
34758
+ action.type = "button";
34759
+ action.disabled = busy || optionalFeatureInstallInProgress.size > 0 || !optionalFeaturePackageStatusesLoaded || candidates.length === 0 || !!optionalFeaturePackageStatusError;
34760
+ action.setAttribute("aria-label", candidates.length
34761
+ ? `Install all ${candidates.length} missing or unregistered optional features`
34762
+ : "All optional features are installed and registered");
34763
+ if (busy) action.setAttribute("aria-busy", "true");
34764
+ action.addEventListener("click", () => installOptionalFeatureBatch(OPTIONAL_FEATURES, { scopeLabel: "all optional features" }));
34765
+
34766
+ const actionGroup = make("div", "optional-feature-batch-actions");
34767
+ if (migratable.length) {
34768
+ const migrate = make("button", "optional-feature-batch-action primary", "Migrate…");
34769
+ migrate.type = "button";
34770
+ migrate.disabled = busy || optionalFeatureInstallInProgress.size > 0;
34771
+ migrate.setAttribute("aria-label", `Migrate ${migratable.length} previously available optional feature${migratable.length === 1 ? "" : "s"}`);
34772
+ migrate.addEventListener("click", () => openOptionalFeatureMigrationDialog());
34773
+ actionGroup.append(migrate);
34774
+ }
34775
+ actionGroup.append(action);
34776
+
34777
+ let summary = !optionalFeaturePackageStatusesLoaded
34778
+ ? optionalFeaturePackageStatusError ? "Install availability unknown" : "Checking Pi package status…"
34779
+ : candidates.length ? `${candidates.length} missing or unregistered` : "All installed and registered";
34780
+ if (optionalFeatureMigrationSnapshot.phase === "checking") summary = "Checking optional features…";
34781
+ if (optionalFeatureBatchState?.phase === "running") {
34782
+ summary = optionalFeatureMigrationProgressText() || `Installing ${optionalFeatureBatchState.total} sequentially with Pi…`;
34783
+ } else if (["done", "failed"].includes(optionalFeatureBatchState?.phase)) {
34784
+ summary = `Batch finished: ${optionalFeatureBatchState.succeeded} succeeded, ${optionalFeatureBatchState.failed} failed.`;
34785
+ }
34786
+ const status = make("div", `optional-feature-batch-status${optionalFeatureBatchState?.failed ? " warning" : ""}`, summary);
34787
+ status.setAttribute("role", "status");
34788
+ status.setAttribute("aria-live", "polite");
34789
+ toolbar.append(status, actionGroup);
34790
+ return toolbar;
34791
+ }
34792
+
34161
34793
  function renderOptionalFeaturePanel() {
34162
34794
  if (!elements.optionalFeaturesBox) return;
34163
34795
  elements.optionalFeaturesBox.replaceChildren();
34164
34796
  elements.optionalFeaturesBox.classList.remove("muted");
34797
+ elements.optionalFeaturesBox.append(renderOptionalFeatureBatchToolbar());
34165
34798
 
34166
34799
  if (optionalFeaturePackageStatusError) {
34167
34800
  const notice = make("div", "optional-feature-panel-notice error");
@@ -34202,10 +34835,18 @@ function renderOptionalFeatureSection(section, features) {
34202
34835
  sectionNode.dataset.optionalFeatureSection = section.id;
34203
34836
 
34204
34837
  const header = make("div", "optional-feature-section-header");
34205
- header.append(
34206
- make("div", "optional-feature-section-title", section.label),
34207
- make("span", "optional-feature-section-count", String(features.length)),
34208
- );
34838
+ const headerActions = make("div", "optional-feature-section-actions");
34839
+ const candidates = optionalFeatureBatchCandidates(features);
34840
+ const installMissing = make("button", "optional-feature-section-install", optionalFeatureBatchIsActive() ? "Installing…" : "Install missing");
34841
+ installMissing.type = "button";
34842
+ installMissing.disabled = optionalFeatureBatchIsActive() || optionalFeatureInstallInProgress.size > 0 || !optionalFeaturePackageStatusesLoaded || candidates.length === 0 || !!optionalFeaturePackageStatusError;
34843
+ installMissing.setAttribute("aria-label", candidates.length
34844
+ ? `Install ${candidates.length} missing or unregistered features in ${section.label}`
34845
+ : `All features in ${section.label} are installed and registered`);
34846
+ if (optionalFeatureBatchIsActive()) installMissing.setAttribute("aria-busy", "true");
34847
+ installMissing.addEventListener("click", () => installOptionalFeatureBatch(features, { scopeLabel: section.label }));
34848
+ headerActions.append(make("span", "optional-feature-section-count", String(features.length)), installMissing);
34849
+ header.append(make("div", "optional-feature-section-title", section.label), headerActions);
34209
34850
  sectionNode.append(header);
34210
34851
  if (section.description) sectionNode.append(make("div", "optional-feature-section-description", section.description));
34211
34852
 
@@ -34227,6 +34868,7 @@ function renderOptionalFeatureRow(feature) {
34227
34868
  const tooltip = optionalFeatureTooltip(feature, status);
34228
34869
  row.dataset.tooltip = tooltip;
34229
34870
  row.setAttribute("aria-label", tooltip.replace(/\s+/g, " "));
34871
+ if (installing) row.setAttribute("aria-busy", "true");
34230
34872
  row.tabIndex = 0;
34231
34873
 
34232
34874
  const main = make("div", "optional-feature-main");
@@ -34235,7 +34877,8 @@ function renderOptionalFeatureRow(feature) {
34235
34877
  main.append(title);
34236
34878
  if (status.detail) {
34237
34879
  const detail = make("div", `optional-feature-detail ${status.className === "failed" ? "error" : ""}`.trim(), status.detail);
34238
- detail.setAttribute("aria-live", installing ? "polite" : "off");
34880
+ if (status.className === "failed" && !installing) detail.setAttribute("role", "alert");
34881
+ else detail.setAttribute("aria-live", installing ? "polite" : "off");
34239
34882
  main.append(detail);
34240
34883
  }
34241
34884
  if (installing) {
@@ -34255,7 +34898,7 @@ function renderOptionalFeatureRow(feature) {
34255
34898
  const actions = make("div", "optional-feature-actions");
34256
34899
  const action = make("button", "optional-feature-action");
34257
34900
  action.type = "button";
34258
- action.disabled = installing;
34901
+ action.disabled = installing || optionalFeatureBatchIsActive() || (!optionalFeaturePackageStatusesLoaded && !detected);
34259
34902
  if (installing) {
34260
34903
  action.textContent = installState?.actionLabel === "Update" ? "Updating…" : "Installing…";
34261
34904
  action.setAttribute("aria-busy", "true");
@@ -34264,6 +34907,12 @@ function renderOptionalFeatureRow(feature) {
34264
34907
  action.textContent = "Retry…";
34265
34908
  action.classList.add(retryAsUpdate ? "update" : "install");
34266
34909
  action.addEventListener("click", () => installOptionalFeature(feature.id, { update: retryAsUpdate }));
34910
+ } else if (isOptionalFeatureDisabled(feature.id)) {
34911
+ action.textContent = "Enable";
34912
+ action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, false));
34913
+ } else if (packageStatus?.resourceConflict) {
34914
+ action.textContent = "Conflict";
34915
+ action.disabled = true;
34267
34916
  } else if (packageStatus?.updateAvailable) {
34268
34917
  action.textContent = "Update…";
34269
34918
  action.classList.add("update");
@@ -34299,7 +34948,7 @@ function renderOptionalFeatureRow(feature) {
34299
34948
  successMessage: `${feature.label} was ${disabled ? "re-enabled" : "disabled again"}.`,
34300
34949
  });
34301
34950
  });
34302
- } else if (packageStatus?.installed) {
34951
+ } else if (packageStatus?.ready) {
34303
34952
  action.textContent = "Reload";
34304
34953
  action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
34305
34954
  } else {
@@ -34308,9 +34957,21 @@ function renderOptionalFeatureRow(feature) {
34308
34957
  action.addEventListener("click", () => installOptionalFeature(feature.id));
34309
34958
  }
34310
34959
  actions.append(action);
34960
+ if (failed) {
34961
+ const retryFailed = make("button", "optional-feature-action install", "Retry failed");
34962
+ retryFailed.type = "button";
34963
+ retryFailed.disabled = optionalFeatureBatchIsActive();
34964
+ retryFailed.addEventListener("click", () => {
34965
+ const audit = optionalFeatureAuditFeature(feature.id);
34966
+ if (audit?.state === "legacy-migratable") openOptionalFeatureMigrationDialog({ featureIds: [feature.id], retryFailed: true });
34967
+ else installOptionalFeature(feature.id, { update: packageStatus?.updateAvailable === true });
34968
+ });
34969
+ actions.replaceChildren(retryFailed);
34970
+ }
34311
34971
  if (status.command) {
34312
34972
  const copyCommand = make("button", "optional-feature-action copy-command", "Copy cmd");
34313
34973
  copyCommand.type = "button";
34974
+ copyCommand.disabled = optionalFeatureBatchIsActive();
34314
34975
  copyCommand.addEventListener("click", () => copyOptionalFeatureInstallCommand(feature.id));
34315
34976
  actions.append(copyCommand);
34316
34977
  }
@@ -34445,16 +35106,16 @@ function commandUnavailableMessage(commandName) {
34445
35106
 
34446
35107
  async function installOptionalFeature(featureId, { update = false } = {}) {
34447
35108
  const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
34448
- if (!feature || optionalFeatureInstallInProgress.has(featureId)) return;
35109
+ if (!feature || optionalFeatureInstallInProgress.has(featureId) || optionalFeatureBatchIsActive()) return;
34449
35110
 
34450
35111
  const actionLabel = update ? "Update" : "Install";
34451
35112
  const warning = [
34452
35113
  `${actionLabel} optional feature: ${feature.label}?`,
34453
35114
  "",
34454
- `This will run npm install for ${feature.packageName} in the Web UI package install root.`,
34455
- "It can download code from npm and modify the local Pi/Web UI npm installation.",
34456
- "Progress, elapsed time, the npm command, and actionable failures will be shown in the optional-features row and activity log.",
34457
- "If this feature is already installed but disabled in Pi settings, cancel and enable it there instead.",
35115
+ `This will run ${optionalFeatureManualInstallCommand(feature)} with the selected Pi CLI.`,
35116
+ "Pi can download code from npm and update its user package registration and package storage.",
35117
+ "Progress, elapsed time, the Pi command, and actionable failures will be shown in the optional-features row and activity log.",
35118
+ "Re-running the same Pi install command is the supported update path.",
34458
35119
  "",
34459
35120
  "Continue?",
34460
35121
  ].join("\n");
@@ -34462,34 +35123,34 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
34462
35123
 
34463
35124
  const startedAt = Date.now();
34464
35125
  optionalFeatureInstallInProgress.add(featureId);
34465
- optionalFeatureInstallMessages.set(featureId, `${actionLabel} preparing; resolving Web UI package install root…`);
35126
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} preparing with Pi…`);
34466
35127
  setOptionalFeatureInstallState(featureId, {
34467
35128
  phase: "preparing",
34468
35129
  actionLabel,
34469
35130
  startedAt,
34470
35131
  endedAt: 0,
34471
- detail: "Resolving safe Web UI package install root…",
34472
- hint: "The package manager has not started yet.",
34473
- command: "",
35132
+ detail: "Resolving the selected Pi CLI…",
35133
+ hint: "The Pi installer has not started yet.",
35134
+ command: optionalFeatureManualInstallCommand(feature),
34474
35135
  outputTail: "",
34475
35136
  });
34476
35137
  startOptionalFeatureInstallProgressTimer(featureId);
34477
- addEvent(`${update ? "updating" : "installing"} optional feature ${feature.label} (${feature.packageName})…`, "warn");
35138
+ addEvent(`${update ? "updating" : "installing"} optional feature ${feature.label} (${feature.packageName}) with Pi…`, "warn");
34478
35139
  setTimeout(() => {
34479
35140
  const state = optionalFeatureInstallState(featureId);
34480
35141
  if (optionalFeatureInstallInProgress.has(featureId) && state?.startedAt === startedAt && state.phase === "preparing") {
34481
- optionalFeatureInstallMessages.set(featureId, `${actionLabel} running via npm; waiting for package-manager output…`);
35142
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} running via Pi; waiting for installer output…`);
34482
35143
  setOptionalFeatureInstallState(featureId, {
34483
35144
  phase: "installing",
34484
- detail: "npm install is running; waiting for package-manager output…",
34485
- hint: "npm can be quiet while resolving packages. Keep this page open; elapsed time updates here.",
35145
+ detail: "Pi install is running; waiting for installer output…",
35146
+ hint: "Pi may be quiet while resolving the npm package. Keep this page open; elapsed time updates here.",
34486
35147
  });
34487
35148
  }
34488
35149
  }, 1200);
34489
35150
 
34490
35151
  try {
34491
35152
  const response = await api("/api/optional-feature-install", { method: "POST", body: { featureId }, scoped: false });
34492
- const command = response.data?.command || "";
35153
+ const command = response.data?.command || optionalFeatureManualInstallCommand(feature);
34493
35154
  disabledOptionalFeatures.delete(featureId);
34494
35155
  storeDisabledOptionalFeatures();
34495
35156
  optionalFeatureInstallMessages.set(featureId, response.data?.message || `${actionLabel} finished`);
@@ -34497,24 +35158,24 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
34497
35158
  phase: "refreshing",
34498
35159
  actionLabel,
34499
35160
  startedAt,
34500
- detail: "npm finished; checking package status and refreshed Web UI capabilities…",
34501
- hint: "If the package is installed but not detected, reload the active Pi tab.",
35161
+ detail: "Pi finished; checking installation and registration status…",
35162
+ hint: "Reload the active Pi tab to load newly registered resources.",
34502
35163
  command,
34503
35164
  outputTail: "",
34504
35165
  });
34505
- addEvent(response.data?.message || `${update ? "updated" : "installed"} ${feature.packageName}`, "info");
35166
+ addEvent(response.data?.message || `${update ? "updated" : "installed"} ${feature.packageName} with Pi`, "info");
34506
35167
  const output = [response.data?.stderr, response.data?.stdout].filter(Boolean).join("\n").trim();
34507
- if (output) addEvent(`npm output for ${feature.packageName}:\n${output.slice(-4000)}`, "info");
35168
+ if (output) addEvent(`Pi install output for ${feature.packageName}:\n${output.slice(-4000)}`, "info");
34508
35169
  await refreshOptionalFeaturePackageStatuses({ announce: true });
34509
35170
  setOptionalFeatureInstallState(featureId, {
34510
35171
  phase: "done",
34511
35172
  actionLabel,
34512
35173
  endedAt: Date.now(),
34513
- detail: response.data?.message || `${actionLabel} finished. Reload the active Pi tab to load newly installed resources.`,
35174
+ detail: response.data?.message || `${actionLabel} finished. Reload the active Pi tab to load newly registered resources.`,
34514
35175
  hint: "Use Reload if this row still says Installed instead of Enabled.",
34515
35176
  command,
34516
35177
  });
34517
- if (await appConfirmText(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to enable newly loaded resources?`, { affected: "The active Pi tab", confirmLabel: "Reload tab", danger: false })) {
35178
+ if (await appConfirmText(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to load its resources?`, { affected: "The active Pi tab", confirmLabel: "Reload tab", danger: false })) {
34518
35179
  sendPrompt("prompt", "/reload");
34519
35180
  } else {
34520
35181
  const tabContext = activeTabContext();
@@ -34530,7 +35191,7 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
34530
35191
  endedAt: Date.now(),
34531
35192
  detail: failure.message,
34532
35193
  hint: failure.hint,
34533
- command: failure.command || optionalFeatureInstallState(featureId)?.command || "",
35194
+ command: failure.command || optionalFeatureInstallState(featureId)?.command || optionalFeatureManualInstallCommand(feature),
34534
35195
  outputTail: failure.outputTail || "",
34535
35196
  errorKind: failure.kind || "unknown",
34536
35197
  });
@@ -34542,6 +35203,221 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
34542
35203
  }
34543
35204
  }
34544
35205
 
35206
+ async function installOptionalFeatureBatch(features, { scopeLabel = "optional features" } = {}) {
35207
+ if (optionalFeatureBatchIsActive() || optionalFeatureInstallInProgress.size > 0) return;
35208
+ const candidates = optionalFeatureBatchCandidates(features);
35209
+ if (!candidates.length) {
35210
+ addEvent(`no missing or unregistered ${scopeLabel} to install`, "info");
35211
+ return;
35212
+ }
35213
+
35214
+ const warning = [
35215
+ `Install ${candidates.length} missing or unregistered ${scopeLabel}?`,
35216
+ "",
35217
+ "The selected Pi CLI will run one install command at a time:",
35218
+ ...candidates.map((feature) => optionalFeatureManualInstallCommand(feature)),
35219
+ "",
35220
+ "Pi can download code from npm and update its user package registration and package storage.",
35221
+ "The batch continues after individual failures and reports every result.",
35222
+ "The affected tab restarts automatically only when idle; busy work is never interrupted.",
35223
+ "",
35224
+ "Continue?",
35225
+ ].join("\n");
35226
+ if (!(await appConfirmText(warning, {
35227
+ affected: `${candidates.length} optional feature package${candidates.length === 1 ? "" : "s"}`,
35228
+ confirmLabel: candidates.length === 1 ? "Install feature" : "Install features",
35229
+ }))) return;
35230
+
35231
+ await runOptionalFeatureBatch(candidates, {
35232
+ scopeLabel,
35233
+ migration: false,
35234
+ signatureFeatureIds: candidates.map((feature) => feature.id),
35235
+ candidateSignature: optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, candidates.map((feature) => feature.id)),
35236
+ reopen: () => installOptionalFeatureBatch(features, { scopeLabel }),
35237
+ });
35238
+ }
35239
+
35240
+ async function postOptionalFeatureBatch({ featureIds, migration, signatureFeatureIds, candidateSignature, retryOnStale = true }) {
35241
+ const submit = () => api("/api/optional-feature-install-batch", {
35242
+ method: "POST",
35243
+ body: { tab: activeTabId, featureIds, revision: optionalFeatureMigrationSnapshot.revision, migration },
35244
+ scoped: false,
35245
+ });
35246
+ try {
35247
+ return await submit();
35248
+ } catch (error) {
35249
+ const staleRevision = error.statusCode === 409 && /stale|revision/i.test(error.message || "");
35250
+ if (!staleRevision || !retryOnStale) throw error;
35251
+ await refreshOptionalFeaturePackageStatuses();
35252
+ const refreshedSignature = optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, signatureFeatureIds);
35253
+ if (refreshedSignature !== candidateSignature) {
35254
+ error.optionalFeatureCandidatesChanged = true;
35255
+ throw error;
35256
+ }
35257
+ try {
35258
+ return await submit();
35259
+ } catch (retryError) {
35260
+ const stillStale = retryError.statusCode === 409 && /stale|revision/i.test(retryError.message || "");
35261
+ if (stillStale) retryError.optionalFeatureRevisionChurn = true;
35262
+ throw retryError;
35263
+ }
35264
+ }
35265
+ }
35266
+
35267
+ function restoreOptionalFeatureInstallStates(previousStates) {
35268
+ for (const [featureId, state] of previousStates) {
35269
+ if (state) optionalFeatureInstallStates.set(featureId, state);
35270
+ else optionalFeatureInstallStates.delete(featureId);
35271
+ }
35272
+ }
35273
+
35274
+ async function runOptionalFeatureBatch(candidates, {
35275
+ scopeLabel = "optional features",
35276
+ migration = false,
35277
+ signatureFeatureIds = candidates.map((feature) => feature.id),
35278
+ candidateSignature = optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, signatureFeatureIds),
35279
+ reopen = null,
35280
+ } = {}) {
35281
+ if (!candidates.length || optionalFeatureBatchIsActive() || optionalFeatureInstallInProgress.size > 0) return;
35282
+ const startedAt = Date.now();
35283
+ const actionLabel = migration ? "Migrate" : "Install";
35284
+ const featureIds = candidates.map((feature) => feature.id);
35285
+ const previousStates = new Map(candidates.map((feature) => [feature.id, optionalFeatureInstallState(feature.id)]));
35286
+ optionalFeatureBatchState = { phase: "running", scopeLabel, total: candidates.length, succeeded: 0, failed: 0, startedAt };
35287
+ candidates.forEach((feature, index) => {
35288
+ optionalFeatureInstallInProgress.add(feature.id);
35289
+ optionalFeatureInstallMessages.set(feature.id, `Queued (${index + 1} of ${candidates.length})…`);
35290
+ setOptionalFeatureInstallState(feature.id, {
35291
+ phase: "installing",
35292
+ actionLabel,
35293
+ startedAt,
35294
+ endedAt: 0,
35295
+ detail: `Installing ${index + 1} of ${candidates.length}: ${feature.label}`,
35296
+ hint: "Pi installs sequentially and continues after individual failures.",
35297
+ command: optionalFeatureManualInstallCommand(feature),
35298
+ outputTail: "",
35299
+ });
35300
+ startOptionalFeatureInstallProgressTimer(feature.id);
35301
+ });
35302
+ addEvent(`installing ${candidates.length} ${scopeLabel} sequentially with Pi`, "warn");
35303
+
35304
+ try {
35305
+ const response = await postOptionalFeatureBatch({ featureIds, migration, signatureFeatureIds, candidateSignature });
35306
+ const results = Array.isArray(response.data?.results) ? response.data.results : [];
35307
+ const resultByFeatureId = new Map(results.map((result) => [result?.featureId, result]));
35308
+ let succeeded = 0;
35309
+ let failed = 0;
35310
+
35311
+ for (const feature of candidates) {
35312
+ const result = resultByFeatureId.get(feature.id);
35313
+ if (result?.ok === true) {
35314
+ succeeded += 1;
35315
+ const data = result.data || {};
35316
+ const command = data.command || optionalFeatureManualInstallCommand(feature);
35317
+ optionalFeatureInstallMessages.set(feature.id, data.message || "Installed and registered with Pi");
35318
+ setOptionalFeatureInstallState(feature.id, {
35319
+ phase: "done",
35320
+ actionLabel,
35321
+ startedAt,
35322
+ endedAt: Date.now(),
35323
+ detail: data.message || "Installed and verified with Pi.",
35324
+ hint: response.data?.restart?.autoRestarted ? "The affected tab restarted automatically." : "The server verified this package registration.",
35325
+ command,
35326
+ outputTail: "",
35327
+ });
35328
+ const output = [data.stderr, data.stdout].filter(Boolean).join("\n").trim().slice(-4000);
35329
+ if (output) addEvent(`Pi install output for ${feature.packageName}:\n${output}`, "info");
35330
+ addEvent(data.message || `installed ${feature.packageName} with Pi`, "info");
35331
+ } else {
35332
+ failed += 1;
35333
+ const failure = optionalFeatureInstallFailureFromBatchResult(result, feature);
35334
+ optionalFeatureInstallMessages.set(feature.id, `${actionLabel} failed: ${failure.message}`);
35335
+ setOptionalFeatureInstallState(feature.id, {
35336
+ phase: "failed",
35337
+ actionLabel,
35338
+ startedAt,
35339
+ endedAt: Date.now(),
35340
+ detail: failure.message,
35341
+ hint: failure.hint,
35342
+ command: failure.command,
35343
+ outputTail: String(failure.outputTail || "").slice(-4000),
35344
+ errorKind: failure.kind || "unknown",
35345
+ });
35346
+ addEvent(`${actionLabel.toLowerCase()} optional feature ${feature.label} failed: ${failure.message}${failure.hint ? `\nHint: ${failure.hint}` : ""}`, "error");
35347
+ }
35348
+ }
35349
+
35350
+ optionalFeatureBatchState = { phase: failed ? "failed" : "done", scopeLabel, total: candidates.length, succeeded, failed, startedAt, endedAt: Date.now() };
35351
+ const restart = response.data?.restart || {};
35352
+ if (restart.autoRestarted || restart.restartDeferred) {
35353
+ optionalFeatureRestartNotice = { ...restart, tabId: activeTabId };
35354
+ addEvent(restart.autoRestarted ? "restarted tab to load new optional features" : "optional feature restart deferred because the tab is busy", restart.restartDeferred ? "warn" : "info");
35355
+ }
35356
+ await refreshOptionalFeaturePackageStatuses({ announce: true });
35357
+ addEvent(`optional feature batch finished: ${succeeded} succeeded, ${failed} failed`, failed ? "warn" : "info");
35358
+ renderOptionalFeatureMigrationSurface();
35359
+ // Backend-owned idle restart replaces the legacy post-batch prompt (formerly confirmLabel: "Reload tab").
35360
+ } catch (error) {
35361
+ if (error.optionalFeatureCandidatesChanged || error.optionalFeatureRevisionChurn) {
35362
+ restoreOptionalFeatureInstallStates(previousStates);
35363
+ optionalFeatureBatchState = null;
35364
+ if (error.optionalFeatureRevisionChurn) await refreshOptionalFeaturePackageStatuses();
35365
+ addEvent(error.optionalFeatureRevisionChurn
35366
+ ? "optional feature audit changed repeatedly; refreshed the plan before asking again"
35367
+ : "optional feature choices changed while confirmation was open; refreshed the current migration plan", "warn");
35368
+ if (typeof reopen === "function") setTimeout(reopen, 0);
35369
+ } else if (error.statusCode === 409 && /already in progress|mutation|busy/i.test(error.message || "")) {
35370
+ restoreOptionalFeatureInstallStates(previousStates);
35371
+ optionalFeatureBatchState = null;
35372
+ await refreshOptionalFeaturePackageStatuses();
35373
+ addEvent("another optional feature operation is already running; recovered its server-owned progress", "warn");
35374
+ } else {
35375
+ const failure = optionalFeatureInstallFailureFromError(error);
35376
+ for (const feature of candidates) {
35377
+ optionalFeatureInstallMessages.set(feature.id, `Batch request failed: ${failure.message}`);
35378
+ setOptionalFeatureInstallState(feature.id, {
35379
+ phase: "failed",
35380
+ actionLabel,
35381
+ startedAt,
35382
+ endedAt: Date.now(),
35383
+ detail: failure.message,
35384
+ hint: failure.hint,
35385
+ command: failure.command || optionalFeatureManualInstallCommand(feature),
35386
+ outputTail: String(failure.outputTail || "").slice(-4000),
35387
+ errorKind: failure.kind || "batch-request",
35388
+ });
35389
+ }
35390
+ optionalFeatureBatchState = { phase: "failed", scopeLabel, total: candidates.length, succeeded: 0, failed: candidates.length, startedAt, endedAt: Date.now() };
35391
+ addEvent(`optional feature batch request failed: ${failure.message}${failure.hint ? `\nHint: ${failure.hint}` : ""}`, "error");
35392
+ }
35393
+ } finally {
35394
+ for (const feature of candidates) {
35395
+ optionalFeatureInstallInProgress.delete(feature.id);
35396
+ clearOptionalFeatureInstallProgressTimer(feature.id);
35397
+ }
35398
+ renderOptionalFeatureControls();
35399
+ renderOptionalFeatureMigrationSurface();
35400
+ }
35401
+ }
35402
+
35403
+ async function migrateSelectedOptionalFeatures() {
35404
+ const state = optionalFeatureMigrationDialogState;
35405
+ if (!state || optionalFeatureBatchIsActive()) return;
35406
+ const selectedIds = [...state.selected].filter((featureId) => !isOptionalFeatureDisabled(featureId));
35407
+ const candidates = selectedIds.map((featureId) => OPTIONAL_FEATURE_BY_ID.get(featureId)).filter(Boolean);
35408
+ if (!candidates.length) return;
35409
+ elements.optionalFeatureMigrationConfirmButton.disabled = true;
35410
+ elements.optionalFeatureMigrationDialogError.hidden = true;
35411
+ elements.optionalFeatureMigrationDialog.close();
35412
+ await runOptionalFeatureBatch(candidates, {
35413
+ scopeLabel: state.retryFailed ? "failed optional features" : "previous optional features",
35414
+ migration: true,
35415
+ signatureFeatureIds: state.featureIds,
35416
+ candidateSignature: state.signature,
35417
+ reopen: () => openOptionalFeatureMigrationDialog({ featureIds: state.featureIds, retryFailed: state.retryFailed }),
35418
+ });
35419
+ }
35420
+
34545
35421
  function runPublishWorkflow(command) {
34546
35422
  setComposerActionsOpen(false);
34547
35423
  setPublishMenuOpen(false);
@@ -34584,6 +35460,176 @@ async function runNativeCommandMenu(command) {
34584
35460
  await sendPrompt("prompt", command);
34585
35461
  }
34586
35462
 
35463
+ function normalizeSessionSummaryClientState(value, previous = null, { resetProjection = false } = {}) {
35464
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.version !== SESSION_SUMMARY_PROTOCOL_VERSION) return null;
35465
+ const status = ["idle", "generating", "success", "failure"].includes(value.status) ? value.status : "idle";
35466
+ const title = typeof value.title === "string" && value.title.length <= 44 && !/[\r\n]/.test(value.title) ? value.title.trim() : "";
35467
+ const summaryMarkdown = typeof value.summaryMarkdown === "string" && value.summaryMarkdown.length <= SESSION_SUMMARY_MARKDOWN_MAX_CHARS
35468
+ ? value.summaryMarkdown.trim()
35469
+ : "";
35470
+ const message = typeof value.message === "string" ? value.message.replace(/[\r\n]+/g, " ").slice(0, 512).trim() : "";
35471
+ const sessionId = typeof value.sessionId === "string" ? value.sessionId.slice(0, 128) : previous?.sessionId || "";
35472
+ const sessionChanged = !!(sessionId && previous?.sessionId && sessionId !== previous.sessionId);
35473
+ const inherited = resetProjection || sessionChanged ? null : previous;
35474
+ return {
35475
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35476
+ status,
35477
+ configured: value.configured === true,
35478
+ enabled: value.enabled === true,
35479
+ durable: value.durable === true,
35480
+ sessionId,
35481
+ title: title || inherited?.title || "",
35482
+ summaryMarkdown: summaryMarkdown || inherited?.summaryMarkdown || "",
35483
+ message,
35484
+ updatedAt: typeof value.updatedAt === "string" ? value.updatedAt : new Date().toISOString(),
35485
+ };
35486
+ }
35487
+
35488
+ function sessionSummaryStateForTab(tabId = activeTabId) {
35489
+ if (!tabId) return null;
35490
+ const cached = sessionSummaryByTab.get(tabId);
35491
+ if (cached) return cached;
35492
+ const metadata = tabs.find((tab) => tab.id === tabId)?.sessionSummary;
35493
+ const normalized = normalizeSessionSummaryClientState(metadata);
35494
+ if (normalized) sessionSummaryByTab.set(tabId, normalized);
35495
+ return normalized;
35496
+ }
35497
+
35498
+ function renderSessionSummaryControls() {
35499
+ const available = !!activeTabId && hasAvailableCommand("summary", { tabId: activeTabId });
35500
+ const setupAvailable = !!activeTabId && hasAvailableCommand("summary-setup", { tabId: activeTabId });
35501
+ const state = sessionSummaryStateForTab(activeTabId);
35502
+ const status = state?.status === "generating" ? "Generating session summary…" : state?.status === "failure" ? `Session summary failed: ${state.message || "unknown error"}` : state?.summaryMarkdown ? "Open the latest session summary" : "Open or create a session summary";
35503
+ for (const button of [elements.summaryHeaderButton, elements.summaryActionButton]) {
35504
+ if (!button) continue;
35505
+ button.hidden = !available;
35506
+ button.disabled = !available || state?.status === "generating";
35507
+ button.setAttribute("aria-busy", state?.status === "generating" ? "true" : "false");
35508
+ applyStyledTooltip(button, status, { ariaLabel: status, align: "end" });
35509
+ }
35510
+ if (elements.optionsSummarySetupButton) elements.optionsSummarySetupButton.hidden = !setupAvailable;
35511
+ }
35512
+
35513
+ function closeSessionSummaryOverlay({ restoreFocus = true } = {}) {
35514
+ const overlay = elements.sessionSummaryOverlay;
35515
+ if (!overlay || overlay.hidden) return;
35516
+ overlay.hidden = true;
35517
+ const focusReturn = sessionSummaryOverlayFocusReturn;
35518
+ sessionSummaryOverlayTabId = null;
35519
+ sessionSummaryOverlayFocusReturn = null;
35520
+ if (restoreFocus && focusReturn?.isConnected) queueMicrotask(() => focusReturn.focus({ preventScroll: true }));
35521
+ }
35522
+
35523
+ function renderSessionSummaryOverlay() {
35524
+ const overlay = elements.sessionSummaryOverlay;
35525
+ if (!overlay || overlay.hidden || !sessionSummaryOverlayTabId) return;
35526
+ const tab = tabs.find((item) => item.id === sessionSummaryOverlayTabId);
35527
+ const state = sessionSummaryStateForTab(sessionSummaryOverlayTabId);
35528
+ elements.sessionSummaryOverlayTitle.textContent = state?.title || "Session summary";
35529
+ elements.sessionSummaryOverlayMeta.textContent = `${tab?.title || "Pi terminal"}${state?.durable === false ? " · in-memory session" : ""}`;
35530
+ const generating = state?.status === "generating";
35531
+ const failed = state?.status === "failure";
35532
+ elements.sessionSummaryOverlayStatus.textContent = generating
35533
+ ? "Generating with the configured background model…"
35534
+ : failed
35535
+ ? state.message || "Summary generation failed. The previous successful summary is preserved."
35536
+ : state?.summaryMarkdown
35537
+ ? "Latest successful active-branch summary."
35538
+ : "No successful summary is available yet.";
35539
+ elements.sessionSummaryOverlayStatus.classList.toggle("error", failed);
35540
+ elements.sessionSummaryOverlayBody.replaceChildren();
35541
+ if (state?.summaryMarkdown) renderMarkdown(elements.sessionSummaryOverlayBody, state.summaryMarkdown);
35542
+ else elements.sessionSummaryOverlayBody.append(make("p", "muted", generating ? "Waiting for the first validated Markdown result…" : "Generate a summary to populate this view."));
35543
+ elements.sessionSummaryOverlayCopyButton.disabled = !state?.summaryMarkdown;
35544
+ elements.sessionSummaryOverlayRefreshButton.disabled = generating;
35545
+ elements.sessionSummaryOverlayRefreshButton.textContent = generating ? "Generating…" : "Refresh";
35546
+ }
35547
+
35548
+ function openSessionSummaryOverlay(tabId, { loading = false } = {}) {
35549
+ if (!tabId || !elements.sessionSummaryOverlay) return;
35550
+ sessionSummaryOverlayFocusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
35551
+ sessionSummaryOverlayTabId = tabId;
35552
+ if (loading) {
35553
+ const previous = sessionSummaryStateForTab(tabId);
35554
+ sessionSummaryByTab.set(tabId, normalizeSessionSummaryClientState({
35555
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35556
+ status: "generating",
35557
+ configured: true,
35558
+ enabled: previous?.enabled === true,
35559
+ durable: previous?.durable === true,
35560
+ updatedAt: new Date().toISOString(),
35561
+ }, previous));
35562
+ }
35563
+ elements.sessionSummaryOverlay.hidden = false;
35564
+ renderSessionSummaryOverlay();
35565
+ }
35566
+
35567
+ function updateSessionSummaryForTab(tabId, value, { resetProjection = false } = {}) {
35568
+ if (!tabId) return null;
35569
+ const normalized = normalizeSessionSummaryClientState(value, sessionSummaryByTab.get(tabId), { resetProjection });
35570
+ if (!normalized) return null;
35571
+ sessionSummaryByTab.set(tabId, normalized);
35572
+ if (tabId === activeTabId) renderSessionSummaryControls();
35573
+ if (sessionSummaryOverlayTabId === tabId) renderSessionSummaryOverlay();
35574
+ return normalized;
35575
+ }
35576
+
35577
+ async function requestSessionSummaryGeneration(tabId, { refresh = false } = {}) {
35578
+ const previous = sessionSummaryStateForTab(tabId);
35579
+ updateSessionSummaryForTab(tabId, {
35580
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35581
+ status: "generating",
35582
+ configured: true,
35583
+ enabled: previous?.enabled === true,
35584
+ durable: previous?.durable === true,
35585
+ updatedAt: new Date().toISOString(),
35586
+ });
35587
+ try {
35588
+ const signal = globalThis.AbortSignal?.timeout?.(SESSION_SUMMARY_REQUEST_TIMEOUT_MS);
35589
+ const response = await api("/api/session-summary/generate", { method: "POST", body: { refresh }, tabId, signal });
35590
+ if (response.data?.summary) updateSessionSummaryForTab(tabId, response.data.summary);
35591
+ if (response.data?.tab) applyTabMetadata(response.data.tab);
35592
+ return response;
35593
+ } catch (error) {
35594
+ updateSessionSummaryForTab(tabId, {
35595
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35596
+ status: "failure",
35597
+ configured: true,
35598
+ enabled: previous?.enabled === true,
35599
+ durable: previous?.durable === true,
35600
+ message: error.message || String(error),
35601
+ updatedAt: new Date().toISOString(),
35602
+ });
35603
+ throw error;
35604
+ }
35605
+ }
35606
+
35607
+ async function openSessionSummaryForTab(tabId = activeTabId, { refresh = false } = {}) {
35608
+ if (!tabId || !hasAvailableCommand("summary", { tabId })) return;
35609
+ let state = sessionSummaryStateForTab(tabId);
35610
+ if (!state?.configured) {
35611
+ const response = await api("/api/session-summary/preferences", { tabId });
35612
+ state = updateSessionSummaryForTab(tabId, response.data?.summary || {
35613
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35614
+ status: "idle",
35615
+ configured: response.data?.preferences?.configured === true,
35616
+ enabled: response.data?.preferences?.enabled === true,
35617
+ durable: false,
35618
+ updatedAt: new Date().toISOString(),
35619
+ });
35620
+ if (!response.data?.preferences?.configured) {
35621
+ await openNativeSessionSummarySetupDialog({ initialData: response.data });
35622
+ return;
35623
+ }
35624
+ }
35625
+ openSessionSummaryOverlay(tabId, { loading: refresh || !state?.summaryMarkdown });
35626
+ if (refresh || !state?.summaryMarkdown) await requestSessionSummaryGeneration(tabId, { refresh }).catch(() => {});
35627
+ }
35628
+
35629
+ function handleSessionSummaryEvent(event) {
35630
+ updateSessionSummaryForTab(event?.tabId, event?.summary, { resetProjection: event?.kind === "state" });
35631
+ }
35632
+
34587
35633
  function slashCommandName(message) {
34588
35634
  const match = String(message || "").trim().match(/^\/([^\s]+)$/);
34589
35635
  return match ? match[1].toLowerCase() : "";
@@ -34848,6 +35894,19 @@ function nativeSettingToggle(label, checked, hint, badge) {
34848
35894
  return { field, input };
34849
35895
  }
34850
35896
 
35897
+ function nativeSettingTextarea(label, value, hint, { maxLength = SESSION_SUMMARY_PROMPT_MAX_CHARS, rows = 6, badge } = {}) {
35898
+ const field = make("label", "native-settings-field native-settings-textarea-field");
35899
+ field.append(nativeSettingsLabelRow(label, badge));
35900
+ const textarea = make("textarea", "dialog-editor native-settings-textarea");
35901
+ textarea.value = String(value || "");
35902
+ textarea.maxLength = maxLength;
35903
+ textarea.rows = rows;
35904
+ textarea.spellcheck = true;
35905
+ field.append(textarea);
35906
+ if (hint) field.append(make("span", "native-settings-hint", hint));
35907
+ return { field, textarea };
35908
+ }
35909
+
34851
35910
  function nativeSettingsSection(title, description, controls, { open = true, badge } = {}) {
34852
35911
  const section = make("details", "native-settings-section");
34853
35912
  section.open = !!open;
@@ -35362,6 +36421,149 @@ function gitWorkflowSetupModelKey(model) {
35362
36421
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
35363
36422
  }
35364
36423
 
36424
+ async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved } = {}) {
36425
+ nativeCommandTabId = activeTabId;
36426
+ openNativeCommandDialog({
36427
+ title: "/summary-setup",
36428
+ message: "Configure persistent background titles and Markdown summaries. Saving confirms the disclosure below, then immediately generates and opens the first summary.",
36429
+ });
36430
+ renderNativeLoading("Loading session summary preferences and available models…");
36431
+
36432
+ let data = initialData;
36433
+ if (!data) {
36434
+ try {
36435
+ const response = await nativeCommandApi("/api/session-summary/preferences");
36436
+ data = response.data || {};
36437
+ } catch (error) {
36438
+ setNativeCommandError(error.message || String(error));
36439
+ elements.nativeCommandBody.replaceChildren();
36440
+ return;
36441
+ }
36442
+ }
36443
+
36444
+ const preferences = data.preferences || {};
36445
+ const models = Array.isArray(data.models) ? data.models : [];
36446
+ if (!models.length) {
36447
+ setNativeCommandError("No authenticated Pi models are available. Run /login or configure a provider first.");
36448
+ elements.nativeCommandBody.replaceChildren();
36449
+ return;
36450
+ }
36451
+ const configuredKey = `${preferences.model?.provider || ""}/${preferences.model?.modelId || ""}`;
36452
+ const defaultKey = "openai-codex/gpt-5.6-luna";
36453
+ const modelKeys = new Set(models.map(gitWorkflowSetupModelKey));
36454
+ const initialModelKey = modelKeys.has(configuredKey) ? configuredKey : modelKeys.has(defaultKey) ? defaultKey : gitWorkflowSetupModelKey(models[0]);
36455
+ const modelOptions = models.map((model) => ({
36456
+ value: gitWorkflowSetupModelKey(model),
36457
+ label: `${gitWorkflowSetupModelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
36458
+ }));
36459
+ const controls = {
36460
+ model: nativeSettingSelect("Summary model", initialModelKey, modelOptions, "Dedicated authenticated provider/model. No fallback is used.", { label: "required", tone: "safety" }),
36461
+ thinking: nativeSettingSelect("Reasoning effort", preferences.model?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the selected model are offered.", { label: "required", tone: "safety" }),
36462
+ automatic: nativeSettingToggle("Generate automatically", preferences.enabled === true, "After eligible settled turns; automatic updates remain silent.", { label: "cost", tone: "safety" }),
36463
+ titleEnabled: nativeSettingToggle("Update generated titles", preferences.title?.enabled !== false, "Only default/automatic tab titles are eligible. Explicit names always win.", { label: "safe", tone: "safety" }),
36464
+ cadence: nativeSettingSelect("Title update cadence", preferences.title?.minSettledTurns || 3, [1, 2, 3, 5, 10, 20].map((value) => ({ value: String(value), label: `${value} settled user turn${value === 1 ? "" : "s"}` })), "Minimum turns between changed generated titles after the first title.", { label: "saved", tone: "browser" }),
36465
+ injectLatest: nativeSettingToggle("Inject latest summary into main-agent context", preferences.context?.injectLatest === true, "Off by default. When enabled, exactly one latest active-branch summary is injected as reference-only data.", { label: "privacy", tone: "safety" }),
36466
+ titlePrompt: nativeSettingTextarea("Editable title prompt", preferences.prompts?.title, "Maximum 8 KiB. This text is untrusted data, not system authority.", { rows: 4, badge: { label: "prompt", tone: "browser" } }),
36467
+ summaryPrompt: nativeSettingTextarea("Editable Markdown summary prompt", preferences.prompts?.summary, "Maximum 8 KiB. Generated Markdown is validated and capped at 16 KiB.", { rows: 7, badge: { label: "prompt", tone: "browser" } }),
36468
+ };
36469
+ const thinkingLevelsForModel = (modelKey) => {
36470
+ const levels = data.modelThinkingLevels?.[modelKey];
36471
+ return Array.isArray(levels) && levels.length ? levels : ["off"];
36472
+ };
36473
+ const syncThinkingLevels = () => {
36474
+ const current = controls.thinking.select.value || preferences.model?.thinkingLevel || "low";
36475
+ replaceNativeSettingSelectOptions(controls.thinking.select, thinkingLevelsForModel(controls.model.select.value), current);
36476
+ };
36477
+ controls.model.select.addEventListener("change", syncThinkingLevels);
36478
+ syncThinkingLevels();
36479
+
36480
+ const disclosure = data.disclosure || {};
36481
+ const body = make("div", "native-settings-panel session-summary-setup-panel");
36482
+ body.append(
36483
+ nativeSettingsNote("Privacy scope", disclosure.scope || "Active-branch user text, final assistant text, and tool names only. Thinking, images, tool arguments/results, credentials, and prior summaries are excluded."),
36484
+ nativeSettingsNote("Cost and provider behavior", disclosure.cost || "One configured-model request per eligible refresh; no provider fallback or automatic retry."),
36485
+ nativeSettingsNote("Persistence and context", disclosure.persistence || "Preferences and generated output are local. Main-agent context injection is off unless enabled."),
36486
+ nativeSettingsSection("Generation profile", "Choose the dedicated model, effort, and automatic-generation policy.", [controls.model, controls.thinking, controls.automatic], { open: true }),
36487
+ nativeSettingsSection("Titles", "Generated names never replace explicit session or browser names.", [controls.titleEnabled, controls.cadence], { open: true }),
36488
+ nativeSettingsSection("Prompts", "Editable instructions are bounded and treated as untrusted data.", [controls.titlePrompt, controls.summaryPrompt], { open: true }),
36489
+ nativeSettingsSection("Privacy and context", "The transcript scope is fixed to text and tool names; injection is separately opt-in.", [controls.injectLatest], { open: true }),
36490
+ );
36491
+ elements.nativeCommandBody.replaceChildren(body);
36492
+ elements.nativeCommandActions.replaceChildren();
36493
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
36494
+
36495
+ const signature = () => JSON.stringify({
36496
+ model: controls.model.select.value,
36497
+ thinking: controls.thinking.select.value,
36498
+ automatic: controls.automatic.input.checked,
36499
+ titleEnabled: controls.titleEnabled.input.checked,
36500
+ cadence: controls.cadence.select.value,
36501
+ injectLatest: controls.injectLatest.input.checked,
36502
+ titlePrompt: controls.titlePrompt.textarea.value,
36503
+ summaryPrompt: controls.summaryPrompt.textarea.value,
36504
+ });
36505
+ const initialSignature = signature();
36506
+ const updateDirty = () => { nativeSettingsDirty = signature() !== initialSignature; };
36507
+ for (const control of [controls.model.select, controls.thinking.select, controls.automatic.input, controls.titleEnabled.input, controls.cadence.select, controls.injectLatest.input, controls.titlePrompt.textarea, controls.summaryPrompt.textarea]) {
36508
+ control.addEventListener("input", updateDirty);
36509
+ control.addEventListener("change", updateDirty);
36510
+ }
36511
+
36512
+ const save = addNativeCommandAction("Save and generate", async () => {
36513
+ setNativeActionBusy(save, true, "Saving…");
36514
+ setNativeCommandError("");
36515
+ try {
36516
+ const selectedModel = models.find((model) => gitWorkflowSetupModelKey(model) === controls.model.select.value);
36517
+ if (!selectedModel) throw new Error("Select an available session summary model.");
36518
+ const titlePrompt = controls.titlePrompt.textarea.value.trim();
36519
+ const summaryPrompt = controls.summaryPrompt.textarea.value.trim();
36520
+ if (!titlePrompt || !summaryPrompt) throw new Error("Both editable prompts are required.");
36521
+ if (titlePrompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS || summaryPrompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS) throw new Error("Each editable prompt must not exceed 8 KiB.");
36522
+ const reviewed = await appConfirm({
36523
+ title: "Save session summary setup?",
36524
+ summary: `${disclosure.scope || "Selected active-branch text and tool names will be sent to the configured model."}\n\n${disclosure.cost || "Generation may incur provider usage."}`,
36525
+ affected: "Global session-summary preferences and the active tab's first generated summary",
36526
+ undoable: false,
36527
+ confirmLabel: "Save and generate",
36528
+ danger: false,
36529
+ });
36530
+ if (!reviewed) return;
36531
+ const response = await nativeCommandApi("/api/session-summary/preferences", {
36532
+ method: "PUT",
36533
+ body: {
36534
+ confirmed: true,
36535
+ preferences: {
36536
+ enabled: controls.automatic.input.checked,
36537
+ model: { provider: selectedModel.provider, modelId: selectedModel.id, thinkingLevel: controls.thinking.select.value },
36538
+ prompts: { title: titlePrompt, summary: summaryPrompt },
36539
+ input: { scope: "text-and-tool-names" },
36540
+ context: { injectLatest: controls.injectLatest.input.checked },
36541
+ title: { enabled: controls.titleEnabled.input.checked, minSettledTurns: Number(controls.cadence.select.value) },
36542
+ },
36543
+ },
36544
+ });
36545
+ const targetTabId = nativeCommandTabId || activeTabId;
36546
+ updateSessionSummaryForTab(targetTabId, response.data?.summary || {
36547
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
36548
+ status: "idle",
36549
+ configured: true,
36550
+ enabled: controls.automatic.input.checked,
36551
+ durable: false,
36552
+ updatedAt: new Date().toISOString(),
36553
+ });
36554
+ nativeSettingsDirty = false;
36555
+ closeNativeCommandDialog({ force: true });
36556
+ openSessionSummaryOverlay(targetTabId, { loading: true });
36557
+ await requestSessionSummaryGeneration(targetTabId, { refresh: true }).catch(() => {});
36558
+ if (typeof onSaved === "function") await onSaved(response.data?.preferences);
36559
+ } catch (error) {
36560
+ setNativeCommandError(error.message || String(error));
36561
+ } finally {
36562
+ setNativeActionBusy(save, false);
36563
+ }
36564
+ }, "primary");
36565
+ }
36566
+
35365
36567
  async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
35366
36568
  openNativeCommandDialog({
35367
36569
  title: "/git-workflow-setup",
@@ -36375,10 +37577,11 @@ async function openNativeAuthSelector(mode) {
36375
37577
  }
36376
37578
 
36377
37579
  async function handleNativeSlashSelectorCommand(message, { usesPromptInput = false } = {}) {
36378
- const name = slashCommandName(message);
37580
+ const summaryMatch = String(message || "").trim().match(/^\/summary(?:\s+(refresh))?$/i);
37581
+ const name = summaryMatch ? "summary" : slashCommandName(message);
36379
37582
  if (!NATIVE_SELECTOR_COMMANDS.has(name)) return false;
36380
37583
  const featureId = optionalFeatureIdForCommand(name);
36381
- if (name === "workflow-setup" && !hasLoadedRpcCommand(name)) {
37584
+ if ((name === "workflow-setup" || name === "summary" || name === "summary-setup") && !hasLoadedRpcCommand(name)) {
36382
37585
  const tabContext = activeTabContext();
36383
37586
  addEvent(commandUnavailableMessage(name), "warn");
36384
37587
  refreshCommands(tabContext).catch((error) => {
@@ -36407,6 +37610,12 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
36407
37610
  case "settings":
36408
37611
  await openNativeSettingsDialog();
36409
37612
  return true;
37613
+ case "summary":
37614
+ await openSessionSummaryForTab(activeTabId, { refresh: summaryMatch?.[1]?.toLowerCase() === "refresh" });
37615
+ return true;
37616
+ case "summary-setup":
37617
+ await openNativeSessionSummarySetupDialog();
37618
+ return true;
36410
37619
  case "workflow-setup":
36411
37620
  await openNativeWorkflowSetupDialog();
36412
37621
  return true;
@@ -38330,6 +39539,7 @@ async function refreshCommands(tabContext = activeTabContext()) {
38330
39539
  rawAvailableCommands = catalog.raw;
38331
39540
  availableCommands = catalog.available;
38332
39541
  updateOptionalFeatureAvailability();
39542
+ renderSessionSummaryControls();
38333
39543
  renderCommands();
38334
39544
  if (elements.commandPaletteDialog?.open) renderCommandPalette({ preserveScroll: true });
38335
39545
  }
@@ -39756,6 +40966,26 @@ function handleInactiveTabEvent(event) {
39756
40966
  }
39757
40967
 
39758
40968
  function handleEvent(event) {
40969
+ if (event?.type === "webui_session_summary") {
40970
+ handleSessionSummaryEvent(event);
40971
+ return;
40972
+ }
40973
+ if (event?.type === "webui_optional_feature_migration") {
40974
+ applyOptionalFeatureMigrationSnapshot(event.snapshot);
40975
+ return;
40976
+ }
40977
+ if (["webui_optional_feature_restart_completed", "webui_optional_feature_restart_deferred"].includes(event?.type)) {
40978
+ optionalFeatureRestartNotice = {
40979
+ tabId: event.tabId || activeTabId,
40980
+ tabTitle: event.tabTitle || "terminal",
40981
+ autoRestarted: event.autoRestarted === true,
40982
+ restartDeferred: event.restartDeferred === true,
40983
+ reason: event.reason || "",
40984
+ };
40985
+ addEvent(event.autoRestarted ? "restarted tab to load new optional features" : "optional feature restart deferred because the tab is busy", event.restartDeferred ? "warn" : "info");
40986
+ renderOptionalFeatureMigrationSurface();
40987
+ return;
40988
+ }
39759
40989
  if (eventHasTabActivityPayload(event)) ingestEventTabActivity(event);
39760
40990
  if (event?.type === "auto_retry_start" || event?.type === "auto_retry_end") trackAutoRetryStateFromEvent(event);
39761
40991
  if (eventMayAffectSkillUsage(event)) trackSkillsFromEvent(event);
@@ -40149,6 +41379,10 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
40149
41379
  });
40150
41380
  const source = new EventSource(`/api/events?${parameters.toString()}`);
40151
41381
  eventSource = source;
41382
+ source.onopen = () => {
41383
+ if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
41384
+ refreshOptionalFeaturePackageStatuses().catch(() => {});
41385
+ };
40152
41386
  source.onmessage = (message) => {
40153
41387
  if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
40154
41388
  try {
@@ -40339,6 +41573,14 @@ elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerm
40339
41573
  elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
40340
41574
  elements.splitTabButton?.addEventListener("click", () => splitActiveTerminalTab());
40341
41575
  elements.workspaceSaveButton?.addEventListener("click", () => saveWebuiWorkspace());
41576
+ const openActiveSessionSummary = () => {
41577
+ void openSessionSummaryForTab().catch((error) => addEvent(error.message || String(error), "error"));
41578
+ };
41579
+ elements.summaryHeaderButton?.addEventListener("click", openActiveSessionSummary);
41580
+ elements.summaryActionButton?.addEventListener("click", () => {
41581
+ setComposerActionsOpen(false);
41582
+ openActiveSessionSummary();
41583
+ });
40342
41584
  elements.terminalSplitCloseButton?.addEventListener("click", () => closeTerminalSplitView());
40343
41585
  elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
40344
41586
  elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
@@ -40500,6 +41742,7 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
40500
41742
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
40501
41743
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
40502
41744
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
41745
+ elements.optionsSummarySetupButton?.addEventListener("click", () => runNativeCommandMenu("/summary-setup"));
40503
41746
  elements.optionsWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/workflow-setup"));
40504
41747
  elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
40505
41748
  elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
@@ -40508,6 +41751,28 @@ elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu(
40508
41751
  elements.optionsTreeButton.addEventListener("click", () => runNativeCommandMenu("/tree"));
40509
41752
  elements.optionsStatsButton?.addEventListener("click", () => openStatsOverlay({ refresh: true }));
40510
41753
  elements.optionsFooterVisibilityButton?.addEventListener("click", openGitFooterVisibilityDialog);
41754
+ elements.sessionSummaryOverlayCloseButton?.addEventListener("click", () => closeSessionSummaryOverlay());
41755
+ elements.sessionSummaryOverlayCopyButton?.addEventListener("click", async () => {
41756
+ const state = sessionSummaryStateForTab(sessionSummaryOverlayTabId);
41757
+ if (!state?.summaryMarkdown) return;
41758
+ try {
41759
+ await copyText(state.summaryMarkdown);
41760
+ elements.sessionSummaryOverlayStatus.textContent = "Markdown copied to the clipboard.";
41761
+ } catch (error) {
41762
+ elements.sessionSummaryOverlayStatus.textContent = `Copy failed: ${error.message || String(error)}`;
41763
+ elements.sessionSummaryOverlayStatus.classList.add("error");
41764
+ }
41765
+ });
41766
+ elements.sessionSummaryOverlayRefreshButton?.addEventListener("click", () => {
41767
+ const tabId = sessionSummaryOverlayTabId;
41768
+ if (tabId) void requestSessionSummaryGeneration(tabId, { refresh: true }).catch(() => {});
41769
+ });
41770
+ document.addEventListener("keydown", (event) => {
41771
+ if (event.key !== "Escape" || elements.sessionSummaryOverlay?.hidden || document.querySelector("dialog[open]")) return;
41772
+ event.preventDefault();
41773
+ event.stopImmediatePropagation();
41774
+ closeSessionSummaryOverlay();
41775
+ }, true);
40511
41776
  elements.gitFooterVisibilitySelectAllButton?.addEventListener("click", () => setGitFooterVisibilitySelection(true));
40512
41777
  elements.gitFooterVisibilitySelectNoneButton?.addEventListener("click", () => setGitFooterVisibilitySelection(false));
40513
41778
  elements.gitFooterVisibilityCloseButton?.addEventListener("click", closeGitFooterVisibilityDialog);
@@ -41836,6 +43101,14 @@ elements.promptInput.addEventListener("blur", () => {
41836
43101
  }, 120);
41837
43102
  });
41838
43103
 
43104
+ elements.optionalFeatureMigrationCancelButton?.addEventListener("click", () => elements.optionalFeatureMigrationDialog?.close());
43105
+ elements.optionalFeatureMigrationLaterButton?.addEventListener("click", () => dismissOptionalFeatureMigration({ closeDialog: true }));
43106
+ elements.optionalFeatureMigrationConfirmButton?.addEventListener("click", migrateSelectedOptionalFeatures);
43107
+ elements.optionalFeatureMigrationDialog?.addEventListener("cancel", (event) => {
43108
+ event.preventDefault();
43109
+ elements.optionalFeatureMigrationDialog.close();
43110
+ });
43111
+
41839
43112
  installModalPrimitives();
41840
43113
  initializeIssueWizard();
41841
43114
  resizePromptInput();
@@ -41848,6 +43121,7 @@ restoreBusyPromptBehaviorSetting();
41848
43121
  updateComposerModeButtons();
41849
43122
  installSessionSkillTagResizeHandling();
41850
43123
  updateOptionalFeatureAvailability();
43124
+ renderOptionalFeatureMigrationSurface();
41851
43125
  refreshOptionalFeaturePackageStatuses({ announce: true });
41852
43126
  renderAppRunnerControls();
41853
43127
  renderLoadedPromptListPreview();