@firstpick/pi-package-webui 0.6.7 → 0.6.9

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.
package/public/app.js CHANGED
@@ -1,7 +1,8 @@
1
1
  const $ = (selector) => document.querySelector(selector);
2
2
 
3
3
  const elements = {
4
- webuiVersionBadge: $("#webuiVersionBadge"),
4
+ piVersionButton: $("#piVersionButton"),
5
+ webuiVersionButton: $("#webuiVersionButton"),
5
6
  webuiDevBadge: $("#webuiDevBadge"),
6
7
  tabBar: $("#tabBar"),
7
8
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
@@ -21,6 +22,7 @@ const elements = {
21
22
  commandPaletteButton: $("#commandPaletteButton"),
22
23
  workspaceDashboardToggleButton: $("#workspaceDashboardToggleButton"),
23
24
  workspaceDashboard: $("#workspaceDashboard"),
25
+ remoteAccessIndicator: $("#remoteAccessIndicator"),
24
26
  statusBar: $("#statusBar"),
25
27
  contextMeterBar: $("#contextMeterBar"),
26
28
  serverOfflinePanel: $("#serverOfflinePanel"),
@@ -59,6 +61,7 @@ const elements = {
59
61
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
60
62
  sessionSkillTags: $("#sessionSkillTags"),
61
63
  conversationModeChip: $("#conversationModeChip"),
64
+ workflowModeChip: $("#workflowModeChip"),
62
65
  skillEditorDialog: $("#skillEditorDialog"),
63
66
  skillEditorTitle: $("#skillEditorTitle"),
64
67
  skillEditorMeta: $("#skillEditorMeta"),
@@ -85,6 +88,7 @@ const elements = {
85
88
  remoteMicStreamingConsentButton: $("#remoteMicStreamingConsentButton"),
86
89
  newSessionButton: $("#newSessionButton"),
87
90
  compactButton: $("#compactButton"),
91
+ workflowModeButton: $("#workflowModeButton"),
88
92
  gitWorkflowButton: $("#gitWorkflowButton"),
89
93
  publishButton: $("#publishButton"),
90
94
  publishMenu: $("#publishMenu"),
@@ -108,6 +112,7 @@ const elements = {
108
112
  optionsNameButton: $("#optionsNameButton"),
109
113
  optionsCloneButton: $("#optionsCloneButton"),
110
114
  optionsSettingsButton: $("#optionsSettingsButton"),
115
+ optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
111
116
  optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
112
117
  optionsExportButton: $("#optionsExportButton"),
113
118
  optionsForkButton: $("#optionsForkButton"),
@@ -242,6 +247,24 @@ const elements = {
242
247
  commandSearchInput: $("#commandSearchInput"),
243
248
  commandsBox: $("#commandsBox"),
244
249
  eventLog: $("#eventLog"),
250
+ undoToast: $("#undoToast"),
251
+ undoToastMessage: $("#undoToastMessage"),
252
+ undoToastTime: $("#undoToastTime"),
253
+ undoToastButton: $("#undoToastButton"),
254
+ undoToastDismissButton: $("#undoToastDismissButton"),
255
+ confirmationDialog: $("#confirmationDialog"),
256
+ confirmationTitle: $("#confirmationTitle"),
257
+ confirmationSummary: $("#confirmationSummary"),
258
+ confirmationAffected: $("#confirmationAffected"),
259
+ confirmationUndo: $("#confirmationUndo"),
260
+ confirmationCancelButton: $("#confirmationCancelButton"),
261
+ confirmationConfirmButton: $("#confirmationConfirmButton"),
262
+ piReleaseNotesDialog: $("#piReleaseNotesDialog"),
263
+ piReleaseNotesTitle: $("#piReleaseNotesTitle"),
264
+ piReleaseNotesStatus: $("#piReleaseNotesStatus"),
265
+ piReleaseNotesBody: $("#piReleaseNotesBody"),
266
+ piReleaseNotesGithubLink: $("#piReleaseNotesGithubLink"),
267
+ piReleaseNotesCloseButton: $("#piReleaseNotesCloseButton"),
245
268
  dialog: $("#extensionDialog"),
246
269
  dialogTitle: $("#dialogTitle"),
247
270
  dialogMessage: $("#dialogMessage"),
@@ -303,6 +326,8 @@ const elements = {
303
326
  statsOverlayCloseButton: $("#statsOverlayCloseButton"),
304
327
  };
305
328
 
329
+ const PI_WEBUI_NPM_URL = "https://www.npmjs.com/package/@firstpick/pi-package-webui";
330
+
306
331
  let currentState = null;
307
332
  let tabs = [];
308
333
  let activeTabId = null;
@@ -360,12 +385,19 @@ let tabsRenderFrame = null;
360
385
  let foregroundReconcileTimer = null;
361
386
  let eventSource = null;
362
387
  let activeDialog = null;
388
+ let activeConfirmationResolve = null;
389
+ let activeUndoAction = null;
390
+ let undoToastTimer = null;
391
+ let undoToastFocusReturn = null;
392
+ const modalSurfaceState = new WeakMap();
393
+ let activeDrawerModal = null;
363
394
  let activeGitPrDialogResolve = null;
364
395
  let gitChangesState = { loading: false, pulling: false, fetching: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, data: null, operation: null, lastFetch: null, tabId: null };
365
396
  let gitToolsState = { tabId: null, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
366
397
  let gitChangesRequestSerial = 0;
367
398
  const gitChangesUntrackedContentRequests = new Set();
368
399
  let nativeCommandTabId = null;
400
+ let nativeSettingsDirty = false;
369
401
  let pathPickerState = null;
370
402
  let firstTerminalCwdPromptShown = false;
371
403
  let pathFastPicks = [];
@@ -419,6 +451,7 @@ let latestRemoteWebuiQrUrl = "";
419
451
  let remoteQrAutoPopupShown = false;
420
452
  let networkStatusLoaded = false;
421
453
  let webuiVersion = "";
454
+ let piVersion = "";
422
455
  let webuiDevServer = false;
423
456
  let latestCodexUsage = null;
424
457
  let codexUsageError = null;
@@ -519,6 +552,7 @@ let latestQueuedMessagesByTab = new Map();
519
552
  let loadedPromptList = null;
520
553
  let promptListRunning = false;
521
554
  let workspaceDashboardCollapsed = false;
555
+ let interfaceDensity = "comfortable";
522
556
  let commandPaletteIndex = 0;
523
557
  let commandPaletteItems = [];
524
558
  let activeEditRetry = null;
@@ -538,6 +572,7 @@ let escapeAbortHoldSuppressesDoubleEscape = false;
538
572
  let suppressEmptyPromptEscapeUntil = 0;
539
573
  const dialogQueue = [];
540
574
  const SIDE_PANEL_STORAGE_KEY = "pi-webui-side-panel-collapsed";
575
+ const INTERFACE_DENSITY_STORAGE_KEY = "pi-webui-interface-density";
541
576
  const SIDE_PANEL_SECTION_STORAGE_KEY = "pi-webui-side-panel-sections-collapsed";
542
577
  const TAB_STORAGE_KEY = "pi-webui-active-tab";
543
578
  const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
@@ -636,6 +671,15 @@ const BTW_WEBUI_PAYLOAD_TYPES = new Set(["firstpick.pi-extension-btw.overlay", "
636
671
  const WORKFLOW_WIDGET_PAYLOAD_PREFIX = "WORKFLOW_WEBUI_PAYLOAD ";
637
672
  const WORKFLOW_SUBPROCESS_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.subprocess";
638
673
  const WORKFLOW_SUBPROCESS_PAYLOAD_VERSION = 1;
674
+ const WORKFLOW_INSPECTOR_WIDGET_KEY = "workflow:rpc";
675
+ const WORKFLOW_INSPECTOR_PAYLOAD_PREFIX = "WORKFLOW_RPC_PAYLOAD ";
676
+ const WORKFLOW_INSPECTOR_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.inspector";
677
+ const WORKFLOW_INSPECTOR_PAYLOAD_VERSION = 1;
678
+ const WORKFLOW_MODE_STATUS_KEY = "workflow-mode";
679
+ const WORKFLOW_MODE_RPC_WIDGET_KEY = "workflow-mode:rpc";
680
+ const WORKFLOW_MODE_RPC_PAYLOAD_PREFIX = "WORKFLOW_MODE_RPC_PAYLOAD ";
681
+ const WORKFLOW_MODE_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.mode";
682
+ const WORKFLOW_MODE_RPC_PAYLOAD_VERSION = 1;
639
683
  const GIT_CHANGES_RENDER_ROW_LIMIT = 4000;
640
684
  const GIT_PULL_RESULT_FILE_LIMIT = 48;
641
685
  const LAST_USER_PROMPT_STORAGE_KEY = "pi-webui-last-user-prompts";
@@ -737,6 +781,10 @@ const todoProgressSignatureByTab = new Map();
737
781
  const releaseNpmOutputExpandedByTab = new Map();
738
782
  const appRunnerDataByTab = new Map();
739
783
  const conversationModeByTab = new Map();
784
+ const workflowModeByTab = new Map();
785
+ const workflowModeTogglePendingByTab = new Set();
786
+ const workflowInspectorByTab = new Map();
787
+ const workflowInspectorSelectionByTab = new Map();
740
788
  const appRunnerInputDraftByRun = new Map();
741
789
  const appRunnerContextLineDraftByRun = new Map();
742
790
  const liveToolRuns = new Map();
@@ -820,8 +868,8 @@ const OPTIONAL_FEATURES = [
820
868
  id: "safetyGuard",
821
869
  label: "Safety guard",
822
870
  packageName: "@firstpick/pi-extension-safety-guard",
823
- capabilityLabel: "/safety-guard command or safety-guard status event",
824
- description: "Interactive guardrails for dangerous bash commands and protected file edits.",
871
+ capabilityLabel: "/safety-guard or /safety-guard-setup command",
872
+ description: "Configurable guardrails for dangerous bash commands and protected file edits.",
825
873
  },
826
874
  {
827
875
  id: "tuiSkillsCommand",
@@ -928,6 +976,7 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
928
976
  ["workflow", "workflows"],
929
977
  ["workflow-clear", "workflows"],
930
978
  ["safety-guard", "safetyGuard"],
979
+ ["safety-guard-setup", "safetyGuard"],
931
980
  ["skills", "tuiSkillsCommand"],
932
981
  ["tools", "tuiToolsCommand"],
933
982
  ["remote", "remoteWebui"],
@@ -943,7 +992,7 @@ const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
943
992
  HIDDEN_COMMAND_NAMES.add("stats-webui");
944
993
  HIDDEN_COMMAND_NAMES.add("btw-status");
945
994
  HIDDEN_COMMAND_NAMES.add("btw-transfer");
946
- const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
995
+ const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
947
996
  const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
948
997
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
949
998
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
@@ -1581,7 +1630,7 @@ function terminalTabsLayoutStatusText(layout = terminalTabsLayout) {
1581
1630
  function renderTerminalTabsLayoutControl() {
1582
1631
  const layout = normalizeTerminalTabsLayout(terminalTabsLayout);
1583
1632
  if (elements.terminalTabsLayoutSelect) elements.terminalTabsLayoutSelect.value = layout;
1584
- if (elements.terminalTabsLayoutStatus) elements.terminalTabsLayoutStatus.textContent = terminalTabsLayoutStatusText(layout);
1633
+ if (elements.terminalTabsLayoutStatus) elements.terminalTabsLayoutStatus.textContent = `${terminalTabsLayoutStatusText(layout)} · saved in this browser`;
1585
1634
  }
1586
1635
 
1587
1636
  function setTerminalTabsLayout(layout, { persist = true, announce = false } = {}) {
@@ -2544,11 +2593,190 @@ function setMobileTabsExpanded(expanded) {
2544
2593
  elements.terminalTabsToggleButton.setAttribute("aria-expanded", mobileTabsExpanded ? "true" : "false");
2545
2594
  }
2546
2595
 
2596
+ function modalFocusableElements(surface) {
2597
+ if (!surface) return [];
2598
+ return [...surface.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')]
2599
+ .filter((node) => !node.hidden && node.getAttribute("aria-hidden") !== "true" && node.getClientRects().length > 0);
2600
+ }
2601
+
2602
+ function installDialogModalPrimitive(dialog) {
2603
+ if (!dialog || dialog.dataset.modalPrimitive === "true") return;
2604
+ dialog.dataset.modalPrimitive = "true";
2605
+ const showModal = dialog.showModal.bind(dialog);
2606
+ dialog.showModal = () => {
2607
+ modalSurfaceState.set(dialog, { trigger: document.activeElement instanceof HTMLElement ? document.activeElement : null });
2608
+ showModal();
2609
+ };
2610
+ dialog.addEventListener("close", () => {
2611
+ const trigger = modalSurfaceState.get(dialog)?.trigger;
2612
+ modalSurfaceState.delete(dialog);
2613
+ const openModal = document.querySelector("dialog:modal");
2614
+ if (trigger?.isConnected && (!openModal || trigger.closest("dialog:modal"))) queueMicrotask(() => trigger.focus({ preventScroll: true }));
2615
+ });
2616
+ }
2617
+
2618
+ function installModalPrimitives() {
2619
+ document.querySelectorAll("dialog").forEach(installDialogModalPrimitive);
2620
+ }
2621
+
2622
+ function dismissUndoToast() {
2623
+ clearTimeout(undoToastTimer);
2624
+ undoToastTimer = null;
2625
+ activeUndoAction = null;
2626
+ if (!elements.undoToast) return;
2627
+ const returnFocus = elements.undoToast.contains(document.activeElement) ? undoToastFocusReturn : null;
2628
+ undoToastFocusReturn = null;
2629
+ elements.undoToast.hidden = true;
2630
+ elements.undoToast.classList.remove("expiring", "undoing", "error");
2631
+ elements.undoToastButton.disabled = false;
2632
+ if (returnFocus?.isConnected) queueMicrotask(() => returnFocus.focus({ preventScroll: true }));
2633
+ }
2634
+
2635
+ function settleUndoToast(message, { error = false, timeoutMs = 3500 } = {}) {
2636
+ if (!elements.undoToast) return;
2637
+ clearTimeout(undoToastTimer);
2638
+ undoToastTimer = null;
2639
+ activeUndoAction = null;
2640
+ elements.undoToast.hidden = false;
2641
+ elements.undoToast.classList.remove("undoing");
2642
+ elements.undoToast.classList.toggle("error", error);
2643
+ const hadFocus = elements.undoToast.contains(document.activeElement);
2644
+ elements.undoToastMessage.textContent = message;
2645
+ elements.undoToastTime.hidden = true;
2646
+ elements.undoToastButton.hidden = true;
2647
+ if (hadFocus) elements.undoToastDismissButton.focus({ preventScroll: true });
2648
+ undoToastTimer = setTimeout(dismissUndoToast, timeoutMs);
2649
+ }
2650
+
2651
+ function offerUndo({ message, undo, successMessage = "Action undone.", timeoutMs = 10000 } = {}) {
2652
+ if (!message || typeof undo !== "function" || !elements.undoToast) return;
2653
+ dismissUndoToast();
2654
+ undoToastFocusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
2655
+ activeUndoAction = { undo, successMessage };
2656
+ elements.undoToastMessage.textContent = message;
2657
+ elements.undoToastTime.textContent = `Undo available for ${Math.round(timeoutMs / 1000)} seconds`;
2658
+ elements.undoToastTime.hidden = false;
2659
+ elements.undoToastButton.hidden = false;
2660
+ elements.undoToastButton.disabled = false;
2661
+ elements.undoToast.hidden = false;
2662
+ elements.undoToast.style.setProperty("--undo-timeout", `${timeoutMs}ms`);
2663
+ elements.undoToast.classList.remove("expiring", "error", "undoing");
2664
+ void elements.undoToast.offsetWidth;
2665
+ elements.undoToast.classList.add("expiring");
2666
+ undoToastTimer = setTimeout(dismissUndoToast, timeoutMs);
2667
+ }
2668
+
2669
+ async function runOfferedUndo() {
2670
+ const pending = activeUndoAction;
2671
+ if (!pending || !elements.undoToast) return;
2672
+ clearTimeout(undoToastTimer);
2673
+ undoToastTimer = null;
2674
+ activeUndoAction = null;
2675
+ elements.undoToast.classList.remove("expiring");
2676
+ elements.undoToast.classList.add("undoing");
2677
+ elements.undoToastMessage.textContent = "Undoing…";
2678
+ elements.undoToastTime.hidden = true;
2679
+ elements.undoToastButton.disabled = true;
2680
+ try {
2681
+ await pending.undo();
2682
+ settleUndoToast(pending.successMessage);
2683
+ addEvent(pending.successMessage, "success");
2684
+ } catch (error) {
2685
+ const message = `Could not undo: ${error.message || String(error)}`;
2686
+ settleUndoToast(message, { error: true, timeoutMs: 7000 });
2687
+ addEvent(message, "error");
2688
+ }
2689
+ }
2690
+
2691
+ function finishApplicationConfirmation(confirmed) {
2692
+ const resolve = activeConfirmationResolve;
2693
+ activeConfirmationResolve = null;
2694
+ if (elements.confirmationDialog?.open) elements.confirmationDialog.close();
2695
+ resolve?.(!!confirmed);
2696
+ }
2697
+
2698
+ function appConfirm({ title = "Confirm action", summary = "Continue?", affected = "The selected item", undoable = false, confirmLabel = "Continue", danger = true } = {}) {
2699
+ if (!elements.confirmationDialog?.showModal) {
2700
+ return Promise.resolve(window.confirm([title, summary, affected, undoable ? "This can be undone." : "This cannot be undone."].filter(Boolean).join("\n\n")));
2701
+ }
2702
+ if (activeConfirmationResolve) finishApplicationConfirmation(false);
2703
+ elements.confirmationTitle.textContent = title;
2704
+ elements.confirmationSummary.textContent = summary;
2705
+ elements.confirmationAffected.textContent = affected;
2706
+ elements.confirmationUndo.textContent = undoable ? "This action can be undone." : "This action cannot be undone.";
2707
+ elements.confirmationConfirmButton.textContent = confirmLabel;
2708
+ elements.confirmationConfirmButton.classList.toggle("danger", danger);
2709
+ elements.confirmationConfirmButton.classList.toggle("primary", !danger);
2710
+ return new Promise((resolve) => {
2711
+ activeConfirmationResolve = resolve;
2712
+ elements.confirmationDialog.showModal();
2713
+ queueMicrotask(() => elements.confirmationCancelButton?.focus());
2714
+ });
2715
+ }
2716
+
2717
+ function appConfirmText(message, options = {}) {
2718
+ const text = String(message || "Continue?").trim();
2719
+ const [firstLine, ...rest] = text.split("\n");
2720
+ return appConfirm({
2721
+ title: options.title || firstLine || "Confirm action",
2722
+ summary: options.summary || rest.join("\n").trim() || firstLine || "Continue?",
2723
+ affected: options.affected || "The current workspace, session, or server state described above",
2724
+ undoable: options.undoable === true,
2725
+ confirmLabel: options.confirmLabel || "Continue",
2726
+ danger: options.danger !== false,
2727
+ });
2728
+ }
2729
+
2730
+ function handleDrawerModalKeydown(event) {
2731
+ if (!activeDrawerModal || event.defaultPrevented) return;
2732
+ if (event.key === "Escape") {
2733
+ event.preventDefault();
2734
+ setSidePanelCollapsed(true, { persist: false });
2735
+ return;
2736
+ }
2737
+ if (event.key !== "Tab") return;
2738
+ const focusable = modalFocusableElements(activeDrawerModal.surface);
2739
+ if (!focusable.length) {
2740
+ event.preventDefault();
2741
+ activeDrawerModal.surface.focus({ preventScroll: true });
2742
+ return;
2743
+ }
2744
+ const first = focusable[0];
2745
+ const last = focusable[focusable.length - 1];
2746
+ if (event.shiftKey && document.activeElement === first) {
2747
+ event.preventDefault();
2748
+ last.focus({ preventScroll: true });
2749
+ } else if (!event.shiftKey && document.activeElement === last) {
2750
+ event.preventDefault();
2751
+ first.focus({ preventScroll: true });
2752
+ }
2753
+ }
2754
+
2755
+ function activateDrawerModal(surface, trigger) {
2756
+ if (activeDrawerModal?.surface === surface) return;
2757
+ activeDrawerModal = { surface, trigger };
2758
+ surface.setAttribute("aria-modal", "true");
2759
+ surface.setAttribute("tabindex", "-1");
2760
+ document.addEventListener("keydown", handleDrawerModalKeydown, true);
2761
+ }
2762
+
2763
+ function deactivateDrawerModal(surface) {
2764
+ if (activeDrawerModal?.surface !== surface) {
2765
+ surface?.removeAttribute("aria-modal");
2766
+ return;
2767
+ }
2768
+ const trigger = activeDrawerModal.trigger;
2769
+ activeDrawerModal = null;
2770
+ surface.removeAttribute("aria-modal");
2771
+ document.removeEventListener("keydown", handleDrawerModalKeydown, true);
2772
+ if (trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
2773
+ }
2774
+
2547
2775
  function syncMobileSidePanelState(collapsed) {
2548
2776
  const showBackdrop = !collapsed && isSidePanelOverlayView();
2549
2777
  elements.sidePanelBackdrop.hidden = !showBackdrop;
2550
- if (showBackdrop) elements.sidePanel.setAttribute("aria-modal", "true");
2551
- else elements.sidePanel.removeAttribute("aria-modal");
2778
+ if (showBackdrop) activateDrawerModal(elements.sidePanel, elements.sidePanelExpandButton);
2779
+ else deactivateDrawerModal(elements.sidePanel);
2552
2780
  }
2553
2781
 
2554
2782
  function setSidePanelCollapsed(collapsed, { persist = true, focusPanel = false } = {}) {
@@ -2615,6 +2843,32 @@ function restoreWorkspaceDashboardState() {
2615
2843
  setWorkspaceDashboardCollapsed(readStoredWorkspaceDashboardCollapsed(), { persist: false });
2616
2844
  }
2617
2845
 
2846
+ function normalizeInterfaceDensity(value) {
2847
+ return value === "compact" ? "compact" : "comfortable";
2848
+ }
2849
+
2850
+ function setInterfaceDensity(value, { persist = true } = {}) {
2851
+ interfaceDensity = normalizeInterfaceDensity(value);
2852
+ document.documentElement.dataset.density = interfaceDensity;
2853
+ if (persist) {
2854
+ try {
2855
+ localStorage.setItem(INTERFACE_DENSITY_STORAGE_KEY, interfaceDensity);
2856
+ } catch {
2857
+ // Browser storage is optional; density still applies to this page.
2858
+ }
2859
+ }
2860
+ }
2861
+
2862
+ function restoreInterfaceDensity() {
2863
+ let stored = "comfortable";
2864
+ try {
2865
+ stored = localStorage.getItem(INTERFACE_DENSITY_STORAGE_KEY) || stored;
2866
+ } catch {
2867
+ // Use the accessible default.
2868
+ }
2869
+ setInterfaceDensity(stored, { persist: false });
2870
+ }
2871
+
2618
2872
  function bindMobileViewChanges() {
2619
2873
  if (!mobileViewMedia) return;
2620
2874
  const syncForViewport = (event) => {
@@ -3076,17 +3330,28 @@ function openNativeDownloadInBrowser(download) {
3076
3330
  return true;
3077
3331
  }
3078
3332
 
3079
- function openNativeExportDownloadPrompt(download) {
3333
+ function openNativeExportDownloadPrompt(download, serverPath = "") {
3080
3334
  const url = nativeDownloadOpenUrl(download, { externalBrowser: true });
3081
3335
  if (!url) return false;
3082
3336
  const fileName = String(download?.fileName || "session export");
3337
+ const savedPath = String(serverPath || "").trim();
3083
3338
  openNativeCommandDialog({ title: "/export", message: "Session export is ready." });
3084
- elements.nativeCommandBody.append(
3085
- make("p", "native-command-note", `File: ${fileName}`),
3086
- make("p", "native-command-note muted", "Open it in your browser, or cancel and use the transcript download URL later."),
3087
- );
3339
+ const details = [make("p", "native-command-note", `File: ${fileName}`)];
3340
+ if (savedPath) details.push(make("p", "native-command-note native-export-path", `Saved to:\n${savedPath}`));
3341
+ details.push(make("p", "native-command-note muted", "Open it in your browser, or cancel and use the transcript download URL later."));
3342
+ elements.nativeCommandBody.append(...details);
3088
3343
  elements.nativeCommandActions.replaceChildren();
3089
3344
  addNativeCommandAction("Cancel", closeNativeCommandDialog);
3345
+ if (savedPath) {
3346
+ addNativeCommandAction("Copy path", async () => {
3347
+ try {
3348
+ await copyText(savedPath);
3349
+ addEvent("copied export file path", "info");
3350
+ } catch (error) {
3351
+ addEvent(`copy export path failed: ${error.message || String(error)}`, "error");
3352
+ }
3353
+ });
3354
+ }
3090
3355
  addNativeCommandAction("Copy URL", async () => {
3091
3356
  try {
3092
3357
  await copyText(url);
@@ -3103,8 +3368,8 @@ function openNativeExportDownloadPrompt(download) {
3103
3368
  return true;
3104
3369
  }
3105
3370
 
3106
- function handleNativeDownloadResponse(download, command) {
3107
- if (String(command || "").toLowerCase() === "export") return openNativeExportDownloadPrompt(download);
3371
+ function handleNativeDownloadResponse(download, command, serverPath = "") {
3372
+ if (String(command || "").toLowerCase() === "export") return openNativeExportDownloadPrompt(download, serverPath);
3108
3373
  return triggerNativeDownload(download);
3109
3374
  }
3110
3375
 
@@ -3191,27 +3456,51 @@ function isWebuiDevMetadata(data) {
3191
3456
  return data?.webuiDev === true || String(data?.webuiMode || "").toLowerCase() === "dev";
3192
3457
  }
3193
3458
 
3194
- function renderWebuiVersion() {
3195
- const badge = elements.webuiVersionBadge;
3196
- if (!badge) return;
3459
+ function renderPiVersionButton() {
3460
+ const button = elements.piVersionButton;
3461
+ if (!button) return;
3462
+ const label = formatWebuiVersion(piVersion);
3463
+ button.hidden = !label;
3464
+ button.textContent = label ? `Pi ${label}` : "";
3465
+ if (label) {
3466
+ button.title = `View Pi ${label} release notes`;
3467
+ button.setAttribute("aria-label", `View Pi ${label} release notes`);
3468
+ }
3469
+ }
3470
+
3471
+ function renderWebuiVersionButton() {
3472
+ const button = elements.webuiVersionButton;
3473
+ if (!button) return;
3197
3474
  const label = formatWebuiVersion(webuiVersion);
3198
- badge.hidden = !label;
3199
- badge.textContent = label;
3200
- if (label) badge.title = `Pi Web UI ${label}`;
3475
+ button.hidden = !label;
3476
+ button.textContent = label ? `Web UI ${label}` : "";
3477
+ if (label) {
3478
+ button.title = `Open Pi Web UI ${label} on npm`;
3479
+ button.setAttribute("aria-label", `Open Pi Web UI ${label} package page`);
3480
+ }
3201
3481
  }
3202
3482
 
3203
3483
  function renderWebuiDevBadge() {
3204
3484
  const badge = elements.webuiDevBadge;
3205
3485
  if (!badge) return;
3206
3486
  badge.hidden = !webuiDevServer;
3207
- badge.title = "Pi Web UI dev server";
3487
+ const version = formatWebuiVersion(webuiVersion);
3488
+ badge.title = `Pi Web UI${version ? ` ${version}` : ""} dev server`;
3208
3489
  }
3209
3490
 
3210
3491
  function setWebuiVersion(version) {
3211
3492
  const text = String(version || "").trim();
3212
3493
  if (text === webuiVersion) return;
3213
3494
  webuiVersion = text;
3214
- renderWebuiVersion();
3495
+ renderWebuiVersionButton();
3496
+ renderWebuiDevBadge();
3497
+ }
3498
+
3499
+ function setPiVersion(version) {
3500
+ const text = String(version || "").trim().replace(/^v/i, "");
3501
+ if (text === piVersion) return;
3502
+ piVersion = text;
3503
+ renderPiVersionButton();
3215
3504
  }
3216
3505
 
3217
3506
  function setWebuiDevServer(dev) {
@@ -3221,9 +3510,90 @@ function setWebuiDevServer(dev) {
3221
3510
  renderWebuiDevBadge();
3222
3511
  }
3223
3512
 
3513
+ function piReleasePageUrl(version = piVersion) {
3514
+ const cleanVersion = String(version || "").trim().replace(/^v/i, "");
3515
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(cleanVersion)) return "";
3516
+ return `https://github.com/earendil-works/pi/releases/tag/v${encodeURIComponent(cleanVersion)}`;
3517
+ }
3518
+
3519
+ function formatPiReleaseDate(value) {
3520
+ const date = new Date(value);
3521
+ if (!value || Number.isNaN(date.getTime())) return "";
3522
+ return new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(date);
3523
+ }
3524
+
3525
+ function setPiReleaseNotesLink(value) {
3526
+ const link = elements.piReleaseNotesGithubLink;
3527
+ if (!link) return;
3528
+ const href = safeHttpUrl(value);
3529
+ link.hidden = !href;
3530
+ if (href) link.href = href;
3531
+ else link.removeAttribute("href");
3532
+ }
3533
+
3534
+ function openWebuiNpmPageInNewTab() {
3535
+ const href = safeHttpUrl(PI_WEBUI_NPM_URL);
3536
+ if (!href) return false;
3537
+ const anchor = document.createElement("a");
3538
+ anchor.href = href;
3539
+ anchor.target = "_blank";
3540
+ anchor.rel = "noopener noreferrer";
3541
+ anchor.hidden = true;
3542
+ document.body.append(anchor);
3543
+ anchor.click();
3544
+ anchor.remove();
3545
+ return true;
3546
+ }
3547
+
3548
+ async function confirmOpenWebuiNpmPage() {
3549
+ const confirmed = await appConfirm({
3550
+ title: "Open npm package page?",
3551
+ summary: "Open @firstpick/pi-package-webui on npm in a new browser tab?",
3552
+ affected: "A new tab will open to the public Pi Web UI package page.",
3553
+ undoable: true,
3554
+ confirmLabel: "Open npm",
3555
+ danger: false,
3556
+ });
3557
+ if (!confirmed) return;
3558
+ if (!openWebuiNpmPageInNewTab()) addEvent("Pi Web UI npm package URL is unavailable", "error");
3559
+ }
3560
+
3561
+ async function openPiReleaseNotes() {
3562
+ const dialog = elements.piReleaseNotesDialog;
3563
+ if (!dialog) return;
3564
+ const requestedVersion = piVersion;
3565
+ const label = formatWebuiVersion(requestedVersion);
3566
+ elements.piReleaseNotesTitle.textContent = label ? `Pi ${label} release notes` : "Pi release notes";
3567
+ elements.piReleaseNotesStatus.textContent = "Loading release notes from GitHub…";
3568
+ elements.piReleaseNotesBody.setAttribute("aria-busy", "true");
3569
+ elements.piReleaseNotesBody.replaceChildren(make("p", "muted", "Loading…"));
3570
+ setPiReleaseNotesLink(piReleasePageUrl(requestedVersion));
3571
+ if (!dialog.open) dialog.showModal();
3572
+
3573
+ try {
3574
+ const response = await api("/api/pi-release-notes", { scoped: false });
3575
+ if (requestedVersion !== piVersion) return;
3576
+ const release = response.data || {};
3577
+ const releaseVersion = String(release.version || "").trim().replace(/^v/i, "");
3578
+ if (requestedVersion && releaseVersion !== requestedVersion) throw new Error(`Expected Pi ${formatWebuiVersion(requestedVersion)} release notes but received ${formatWebuiVersion(releaseVersion) || "an unknown version"}`);
3579
+ const releaseLabel = formatWebuiVersion(releaseVersion || requestedVersion);
3580
+ elements.piReleaseNotesTitle.textContent = releaseLabel ? `Pi ${releaseLabel} release notes` : (release.title || "Pi release notes");
3581
+ renderMarkdown(elements.piReleaseNotesBody, release.body || "No release notes were provided for this release.");
3582
+ const published = formatPiReleaseDate(release.publishedAt);
3583
+ elements.piReleaseNotesStatus.textContent = `${published ? `Published ${published}` : "Loaded from GitHub"}${release.truncated ? " · Long notes were truncated" : ""}`;
3584
+ setPiReleaseNotesLink(release.url || piReleasePageUrl(release.version));
3585
+ } catch (error) {
3586
+ elements.piReleaseNotesStatus.textContent = "Release notes could not be loaded.";
3587
+ elements.piReleaseNotesBody.replaceChildren(make("p", "pi-release-notes-error", error.message || String(error)));
3588
+ } finally {
3589
+ elements.piReleaseNotesBody.removeAttribute("aria-busy");
3590
+ }
3591
+ }
3592
+
3224
3593
  async function refreshWebuiVersion() {
3225
3594
  const health = await api("/api/health", { scoped: false });
3226
3595
  setWebuiVersion(health.webuiVersion);
3596
+ setPiVersion(health.piVersion);
3227
3597
  setWebuiDevServer(isWebuiDevMetadata(health));
3228
3598
  }
3229
3599
 
@@ -3365,7 +3735,7 @@ async function runPiUpdateAndRestart({ all = false } = {}) {
3365
3735
  renderUpdateNotification(latestUpdateStatus, { force: true });
3366
3736
  return;
3367
3737
  }
3368
- if (!confirm(piUpdateConfirmationText({ all }))) return;
3738
+ if (!(await appConfirmText(piUpdateConfirmationText({ all }), { affected: "The Pi Web UI server and all managed Pi tabs", confirmLabel: all ? "Update all and restart" : "Update Pi and restart" }))) return;
3369
3739
 
3370
3740
  const updateLabel = all ? "Pi and package updates" : "Pi update";
3371
3741
  updateRequestInProgress = true;
@@ -4050,7 +4420,7 @@ function renderBackgroundControl() {
4050
4420
  : `${themeLabel}: theme default`;
4051
4421
  if (elements.backgroundChooseButton) {
4052
4422
  elements.backgroundChooseButton.disabled = customBackgroundLoading;
4053
- elements.backgroundChooseButton.textContent = active ? "Change background" : "Add background";
4423
+ elements.backgroundChooseButton.textContent = active ? "Change image" : "Choose image";
4054
4424
  }
4055
4425
  if (elements.backgroundInput) elements.backgroundInput.disabled = customBackgroundLoading;
4056
4426
  if (elements.backgroundClearButton) {
@@ -4312,6 +4682,155 @@ function isOptionalFeatureEnabled(featureId) {
4312
4682
  return isOptionalFeatureDetected(featureId) && !isOptionalFeatureDisabled(featureId);
4313
4683
  }
4314
4684
 
4685
+ function defaultWorkflowModeState(patch = {}) {
4686
+ return {
4687
+ available: false,
4688
+ enabled: false,
4689
+ phase: "off",
4690
+ behavior: "persistent",
4691
+ statusText: "",
4692
+ updatedAt: "",
4693
+ ...patch,
4694
+ };
4695
+ }
4696
+
4697
+ function normalizeWorkflowModeState(value = {}) {
4698
+ const source = value && typeof value === "object" ? value : {};
4699
+ const enabled = source.enabled === true;
4700
+ const phase = enabled && source.phase === "running" ? "running" : enabled ? "armed" : "off";
4701
+ const behavior = source.behavior === "once" ? "once" : "persistent";
4702
+ return defaultWorkflowModeState({
4703
+ ...source,
4704
+ available: source.available === true,
4705
+ enabled,
4706
+ phase,
4707
+ behavior,
4708
+ statusText: cleanStatusText(source.statusText || ""),
4709
+ });
4710
+ }
4711
+
4712
+ function workflowModeStateFromStatus(statusText = "") {
4713
+ const text = cleanStatusText(statusText || "");
4714
+ const match = text.match(/^workflow\s*:\s*(on|once|running)$/i);
4715
+ return normalizeWorkflowModeState({
4716
+ available: true,
4717
+ enabled: !!match,
4718
+ behavior: match?.[1]?.toLowerCase() === "once" ? "once" : "persistent",
4719
+ phase: match?.[1]?.toLowerCase() === "running" ? "running" : match ? "armed" : "off",
4720
+ statusText: text,
4721
+ updatedAt: new Date().toISOString(),
4722
+ });
4723
+ }
4724
+
4725
+ function workflowModeStateFromRpcPayload(lines) {
4726
+ const raw = String(lines?.[0] || "").trim();
4727
+ if (!raw.startsWith(WORKFLOW_MODE_RPC_PAYLOAD_PREFIX)) return null;
4728
+ try {
4729
+ const payload = JSON.parse(raw.slice(WORKFLOW_MODE_RPC_PAYLOAD_PREFIX.length));
4730
+ if (payload?.type !== WORKFLOW_MODE_RPC_PAYLOAD_TYPE || payload.version !== WORKFLOW_MODE_RPC_PAYLOAD_VERSION) return null;
4731
+ if (typeof payload.enabled !== "boolean" || !["persistent", "once"].includes(payload.behavior) || !["off", "armed", "running"].includes(payload.phase)) return null;
4732
+ return normalizeWorkflowModeState({
4733
+ available: true,
4734
+ enabled: payload.enabled,
4735
+ behavior: payload.behavior,
4736
+ phase: payload.phase,
4737
+ statusText: payload.enabled ? `Workflow: ${payload.phase === "running" ? "running" : payload.behavior === "once" ? "once" : "on"}` : "",
4738
+ updatedAt: typeof payload.updatedAt === "string" ? payload.updatedAt : new Date().toISOString(),
4739
+ });
4740
+ } catch {
4741
+ return null;
4742
+ }
4743
+ }
4744
+
4745
+ function updateWorkflowModeForTab(tabId = activeTabId, mode = {}, { render = true } = {}) {
4746
+ if (!tabId) return normalizeWorkflowModeState(mode);
4747
+ const previous = workflowModeByTab.get(tabId) || {};
4748
+ const next = normalizeWorkflowModeState({ ...previous, ...mode });
4749
+ workflowModeByTab.set(tabId, next);
4750
+ if (tabId === activeTabId && render) renderWorkflowModeControls();
4751
+ return next;
4752
+ }
4753
+
4754
+ function activeWorkflowMode() {
4755
+ return normalizeWorkflowModeState(workflowModeByTab.get(activeTabId) || {});
4756
+ }
4757
+
4758
+ function workflowModeCommandName() {
4759
+ return resolveAvailableCommandName("workflow", { rpcOnly: true }) || "";
4760
+ }
4761
+
4762
+ function renderWorkflowModeControls() {
4763
+ const mode = activeWorkflowMode();
4764
+ const commandName = workflowModeCommandName();
4765
+ const commandAvailable = !!commandName && isOptionalFeatureEnabled("workflows");
4766
+ const active = mode.enabled === true;
4767
+ const pending = !!activeTabId && workflowModeTogglePendingByTab.has(activeTabId);
4768
+ document.body.classList.toggle("workflow-mode-active", active);
4769
+ elements.composer?.classList.toggle("workflow-mode-active", active);
4770
+
4771
+ if (elements.workflowModeButton) {
4772
+ elements.workflowModeButton.hidden = !commandAvailable && !active;
4773
+ elements.workflowModeButton.disabled = !commandName || pending;
4774
+ elements.workflowModeButton.classList.toggle("active", active);
4775
+ elements.workflowModeButton.setAttribute("aria-pressed", active ? "true" : "false");
4776
+ const label = elements.workflowModeButton.querySelector("span");
4777
+ if (label) label.textContent = pending ? "Workflow…" : active ? "Workflow On" : "Workflow";
4778
+ const tooltip = commandName
4779
+ ? `${active ? "Disable" : "Enable"} JavaScript Workflow Mode for this Pi tab via /${commandName} mode ${active ? "off" : "on"}.`
4780
+ : "Workflow Mode is unavailable because the /workflow command is not loaded.";
4781
+ applyStyledTooltip(elements.workflowModeButton, tooltip, { ariaLabel: true, align: "start" });
4782
+ }
4783
+
4784
+ if (elements.workflowModeChip) {
4785
+ elements.workflowModeChip.hidden = !active;
4786
+ elements.workflowModeChip.disabled = !commandName || pending;
4787
+ elements.workflowModeChip.textContent = mode.phase === "running" ? "Workflow: running" : mode.behavior === "once" ? "Workflow: once" : "Workflow: on";
4788
+ elements.workflowModeChip.setAttribute("aria-pressed", "true");
4789
+ elements.workflowModeChip.title = "Workflow Mode is active. Click to return this tab to normal Pi prompting.";
4790
+ elements.workflowModeChip.setAttribute("aria-label", `${elements.workflowModeChip.textContent}. Click to disable Workflow Mode.`);
4791
+ }
4792
+ }
4793
+
4794
+ function handleWorkflowModeStatus(statusText, tabId = activeTabId) {
4795
+ updateWorkflowModeForTab(tabId, workflowModeStateFromStatus(statusText), { render: tabId === activeTabId });
4796
+ }
4797
+
4798
+ async function setWorkflowModeEnabled(enabled) {
4799
+ const tabContext = activeTabContext();
4800
+ if (!tabContext.tabId) return;
4801
+ const commandName = workflowModeCommandName();
4802
+ if (!commandName) {
4803
+ addEvent("Workflow Mode is unavailable because the /workflow command is not loaded.", "warn");
4804
+ await refreshCommands(tabContext);
4805
+ return;
4806
+ }
4807
+
4808
+ workflowModeTogglePendingByTab.add(tabContext.tabId);
4809
+ renderWorkflowModeControls();
4810
+ setComposerActionsOpen(false);
4811
+ try {
4812
+ await sendPrompt("prompt", `/${commandName} mode ${enabled ? "on" : "off"}`, { targetTabId: tabContext.tabId, throwOnError: true });
4813
+ if (!isCurrentTabContext(tabContext)) return;
4814
+ updateWorkflowModeForTab(tabContext.tabId, {
4815
+ available: true,
4816
+ enabled: enabled === true,
4817
+ phase: enabled ? "armed" : "off",
4818
+ statusText: enabled ? "Workflow: on" : "",
4819
+ updatedAt: new Date().toISOString(),
4820
+ });
4821
+ addEvent(enabled ? "Workflow Mode enabled for this tab." : "Workflow Mode disabled for this tab.", "info");
4822
+ } catch (error) {
4823
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
4824
+ } finally {
4825
+ workflowModeTogglePendingByTab.delete(tabContext.tabId);
4826
+ if (isCurrentTabContext(tabContext)) renderWorkflowModeControls();
4827
+ }
4828
+ }
4829
+
4830
+ function toggleWorkflowMode() {
4831
+ return setWorkflowModeEnabled(!activeWorkflowMode().enabled);
4832
+ }
4833
+
4315
4834
  function defaultConversationModeState(patch = {}) {
4316
4835
  return {
4317
4836
  featureId: "naturalConversation",
@@ -5504,7 +6023,7 @@ function fileDisplayName(path = "") {
5504
6023
  }
5505
6024
 
5506
6025
  function fileEntryIcon(entry = {}) {
5507
- if (entry.type === "directory") return "▸";
6026
+ if (entry.type === "directory") return "DIR";
5508
6027
  if (entry.type === "file") return entry.extension === ".md" || entry.extension === ".markdown" ? "Md" : "TXT";
5509
6028
  if (entry.type === "error") return "!";
5510
6029
  return "·";
@@ -5523,8 +6042,6 @@ function normalizeFileTreeGitStatus(status = {}) {
5523
6042
  }
5524
6043
 
5525
6044
  function fileTreeGitStatusForEntry(entry = {}) {
5526
- const own = normalizeFileTreeGitStatus(entry.gitStatus);
5527
- if (own) return own;
5528
6045
  return fileTreeState.gitStatusByPath.get(normalizeFileTreePath(entry.path || "")) || null;
5529
6046
  }
5530
6047
 
@@ -5655,6 +6172,7 @@ function renderFileTree() {
5655
6172
  list.setAttribute("role", "group");
5656
6173
  for (const entry of fileTreeState.searchEntries) appendFileSearchEntry(list, entry);
5657
6174
  root.append(list);
6175
+ syncFileTreeRovingTabindex();
5658
6176
  return;
5659
6177
  }
5660
6178
  const entries = fileTreeState.entriesByPath.get(FILE_TREE_ROOT_PATH) || [];
@@ -5666,6 +6184,51 @@ function renderFileTree() {
5666
6184
  list.setAttribute("role", "group");
5667
6185
  for (const entry of entries) appendFileTreeEntry(list, entry, 0);
5668
6186
  root.append(list);
6187
+ syncFileTreeRovingTabindex();
6188
+ }
6189
+
6190
+ function visibleFileTreeItems() {
6191
+ return [...elements.fileTreeRoot?.querySelectorAll('[role="treeitem"]') || []];
6192
+ }
6193
+
6194
+ function syncFileTreeRovingTabindex(preferredPath = fileTreeState.selectedPath) {
6195
+ const items = visibleFileTreeItems();
6196
+ const active = items.find((item) => normalizeFileTreePath(item.dataset.path) === normalizeFileTreePath(preferredPath)) || items[0];
6197
+ for (const item of items) item.tabIndex = item === active ? 0 : -1;
6198
+ }
6199
+
6200
+ function selectFileTreePath(path, { focus = false } = {}) {
6201
+ fileTreeState.selectedPath = normalizeFileTreePath(path);
6202
+ renderFileTree();
6203
+ if (focus) {
6204
+ const selected = visibleFileTreeItems().find((item) => normalizeFileTreePath(item.dataset.path) === fileTreeState.selectedPath);
6205
+ selected?.focus({ preventScroll: true });
6206
+ }
6207
+ }
6208
+
6209
+ function fileTreeOverflowButton(entry) {
6210
+ const button = make("button", "file-tree-overflow-button", "⋯");
6211
+ button.type = "button";
6212
+ button.setAttribute("aria-label", `Actions for ${entry.name || fileDisplayName(entry.path)}`);
6213
+ button.setAttribute("aria-haspopup", "menu");
6214
+ button.addEventListener("click", (event) => {
6215
+ event.stopPropagation();
6216
+ showFileContextMenuForElement(button, entry);
6217
+ });
6218
+ return button;
6219
+ }
6220
+
6221
+ function fileTreeExpander(entry, expanded = false, { search = false } = {}) {
6222
+ const button = make("button", "file-tree-expander", expanded ? "▾" : "▸");
6223
+ button.type = "button";
6224
+ button.setAttribute("aria-label", `${expanded ? "Collapse" : "Expand"} ${entry.name || fileDisplayName(entry.path)}`);
6225
+ button.setAttribute("aria-expanded", expanded ? "true" : "false");
6226
+ button.addEventListener("click", (event) => {
6227
+ event.stopPropagation();
6228
+ if (search) revealFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
6229
+ else toggleFileTreeDirectory(entry.path).catch((error) => addEvent(error.message || String(error), "error"));
6230
+ });
6231
+ return button;
5669
6232
  }
5670
6233
 
5671
6234
  function appendFileSearchEntry(parent, entry) {
@@ -5681,6 +6244,7 @@ function appendFileSearchEntry(parent, entry) {
5681
6244
  button.dataset.type = entry.type || "file";
5682
6245
  button.style.setProperty("--file-tree-depth", "0");
5683
6246
  button.setAttribute("role", "treeitem");
6247
+ button.setAttribute("aria-selected", fileTreeState.selectedPath === path ? "true" : "false");
5684
6248
  button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5685
6249
  const label = make("span", "file-tree-search-label");
5686
6250
  label.append(
@@ -5698,16 +6262,12 @@ function appendFileSearchEntry(parent, entry) {
5698
6262
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
5699
6263
  button.addEventListener("click", () => {
5700
6264
  fileTreeState.selectedPath = path;
5701
- renderFileTree();
5702
- });
5703
- button.addEventListener("dblclick", (event) => {
5704
- event.preventDefault();
5705
- if (isDirectory) revealFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
5706
- else if (entry.type === "file") openFileInViewer(path);
6265
+ if (entry.type === "file") openFileInViewer(path);
6266
+ else renderFileTree();
5707
6267
  });
5708
6268
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5709
6269
  bindFileTreeDragAndDrop(button, item, entry);
5710
- item.append(button);
6270
+ item.append(isDirectory ? fileTreeExpander(entry, false, { search: true }) : make("span", "file-tree-expander-spacer"), button, fileTreeOverflowButton(entry));
5711
6271
  parent.append(item);
5712
6272
  }
5713
6273
 
@@ -5749,6 +6309,7 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5749
6309
  button.dataset.type = entry.type || "file";
5750
6310
  button.style.setProperty("--file-tree-depth", String(depth));
5751
6311
  button.setAttribute("role", "treeitem");
6312
+ button.setAttribute("aria-selected", fileTreeState.selectedPath === path ? "true" : "false");
5752
6313
  if (isDirectory) button.setAttribute("aria-expanded", expanded ? "true" : "false");
5753
6314
  button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5754
6315
  button.append(
@@ -5761,17 +6322,12 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5761
6322
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
5762
6323
  button.addEventListener("click", () => {
5763
6324
  fileTreeState.selectedPath = path;
5764
- if (isDirectory) toggleFileTreeDirectory(path);
6325
+ if (entry.type === "file") openFileInViewer(path);
5765
6326
  else renderFileTree();
5766
6327
  });
5767
- button.addEventListener("dblclick", (event) => {
5768
- event.preventDefault();
5769
- if (isDirectory) toggleFileTreeDirectory(path, { force: true });
5770
- else openFileInViewer(path);
5771
- });
5772
6328
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5773
6329
  bindFileTreeDragAndDrop(button, item, entry);
5774
- item.append(button);
6330
+ item.append(isDirectory ? fileTreeExpander(entry, expanded) : make("span", "file-tree-expander-spacer"), button, fileTreeOverflowButton(entry));
5775
6331
  if (isDirectory && expanded) {
5776
6332
  const children = fileTreeState.entriesByPath.get(path) || [];
5777
6333
  const childList = make("ul", "file-tree-list");
@@ -5921,9 +6477,11 @@ async function toggleFileTreeDirectory(path = "", { force = false } = {}) {
5921
6477
  await loadFileTreeDirectory(normalized);
5922
6478
  }
5923
6479
 
5924
- function closeFileContextMenu() {
6480
+ function closeFileContextMenu({ returnFocus = true } = {}) {
6481
+ const trigger = fileContextMenuState?.trigger;
5925
6482
  fileContextMenuState = null;
5926
6483
  if (elements.fileContextMenu) elements.fileContextMenu.hidden = true;
6484
+ if (returnFocus && trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
5927
6485
  }
5928
6486
 
5929
6487
  function showFileContextMenu(event, entry) {
@@ -5931,7 +6489,7 @@ function showFileContextMenu(event, entry) {
5931
6489
  event.preventDefault();
5932
6490
  event.stopPropagation();
5933
6491
  const path = normalizeFileTreePath(entry?.path || "");
5934
- fileContextMenuState = { entry: { ...entry, path } };
6492
+ fileContextMenuState = { entry: { ...entry, path }, trigger: event.currentTarget || document.activeElement };
5935
6493
  const menu = elements.fileContextMenu;
5936
6494
  const webui = menu.querySelector('[data-file-menu-action="open-webui"]');
5937
6495
  if (webui) webui.textContent = entry?.type === "directory" ? "Open in WebUI" : "Open in WebUI";
@@ -5941,6 +6499,47 @@ function showFileContextMenu(event, entry) {
5941
6499
  const top = Math.min(event.clientY, Math.max(0, window.innerHeight - rect.height - 8));
5942
6500
  menu.style.left = `${left}px`;
5943
6501
  menu.style.top = `${top}px`;
6502
+ menu.querySelector('[role="menuitem"]')?.focus({ preventScroll: true });
6503
+ }
6504
+
6505
+ function showFileContextMenuForElement(element, entry) {
6506
+ const rect = element.getBoundingClientRect();
6507
+ showFileContextMenu({
6508
+ preventDefault() {},
6509
+ stopPropagation() {},
6510
+ clientX: rect.right,
6511
+ clientY: rect.bottom,
6512
+ currentTarget: element,
6513
+ }, entry);
6514
+ }
6515
+
6516
+ function handleFileTreeKeydown(event) {
6517
+ const current = event.target?.closest?.('[role="treeitem"]');
6518
+ if (!current || !elements.fileTreeRoot?.contains(current)) return;
6519
+ const items = visibleFileTreeItems();
6520
+ const index = items.indexOf(current);
6521
+ if (index < 0) return;
6522
+ const focusAt = (nextIndex) => {
6523
+ const next = items[Math.max(0, Math.min(items.length - 1, nextIndex))];
6524
+ if (!next) return;
6525
+ event.preventDefault();
6526
+ selectFileTreePath(next.dataset.path, { focus: true });
6527
+ };
6528
+ if (event.key === "ArrowDown") focusAt(index + 1);
6529
+ else if (event.key === "ArrowUp") focusAt(index - 1);
6530
+ else if (event.key === "Home") focusAt(0);
6531
+ else if (event.key === "End") focusAt(items.length - 1);
6532
+ else if (event.key === "ArrowRight" && current.dataset.type === "directory") {
6533
+ event.preventDefault();
6534
+ if (current.getAttribute("aria-expanded") !== "true") toggleFileTreeDirectory(current.dataset.path);
6535
+ else focusAt(index + 1);
6536
+ } else if (event.key === "ArrowLeft" && current.dataset.type === "directory" && current.getAttribute("aria-expanded") === "true") {
6537
+ event.preventDefault();
6538
+ toggleFileTreeDirectory(current.dataset.path);
6539
+ } else if (event.key === "Enter" && current.dataset.type === "directory") {
6540
+ event.preventDefault();
6541
+ toggleFileTreeDirectory(current.dataset.path);
6542
+ }
5944
6543
  }
5945
6544
 
5946
6545
  function currentFileViewerPath() {
@@ -6219,7 +6818,13 @@ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6219
6818
  ? "\n\nThe currently open file has unsaved edits that will be discarded from the viewer."
6220
6819
  : "";
6221
6820
  const recursiveWarning = typeLabel === "directory" ? "\n\nThis permanently deletes the directory and all of its contents." : "";
6222
- if (!window.confirm(`Delete ${typeLabel} ${sourcePath}?${recursiveWarning}${dirtyWarning}\n\nThis cannot be undone.`)) return;
6821
+ if (!(await appConfirm({
6822
+ title: `Delete ${typeLabel}?`,
6823
+ summary: `${sourcePath}${recursiveWarning}${dirtyWarning}`,
6824
+ affected: typeLabel === "directory" ? "The directory and all files beneath it" : sourcePath,
6825
+ undoable: false,
6826
+ confirmLabel: `Delete ${typeLabel}`,
6827
+ }))) return;
6223
6828
  const tabContext = activeTabContext();
6224
6829
  setFileTreeStatus(`Deleting ${sourcePath}…`);
6225
6830
  try {
@@ -6240,27 +6845,26 @@ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6240
6845
  }
6241
6846
  }
6242
6847
 
6243
- async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "", { viaDragDrop = false, confirmMove = false } = {}) {
6848
+ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "", { viaDragDrop = false, confirmMove = false, offerMoveUndo = true, tabContext = activeTabContext() } = {}) {
6244
6849
  const sourcePath = normalizeFileTreePath(entry.path || "");
6245
6850
  const normalizedDestination = normalizeFileTreePath(destinationPath);
6246
6851
  if (!sourcePath) {
6247
6852
  addEvent("Workspace root cannot be moved from the Files panel.", "warn");
6248
- return;
6853
+ return false;
6249
6854
  }
6250
6855
  if (!normalizedDestination && normalizedDestination !== FILE_TREE_ROOT_PATH) {
6251
6856
  addEvent("Destination path is required.", "warn");
6252
- return;
6857
+ return false;
6253
6858
  }
6254
6859
  const typeLabel = fileOperationTypeLabel(entry);
6255
- if (confirmMove && !window.confirm(`Move ${typeLabel}?\n\nFrom: ${sourcePath}\nTo: ${normalizedDestination || "."}\n\nExisting destination paths are refused.`)) return;
6256
- const tabContext = activeTabContext();
6860
+ if (confirmMove && !(await appConfirmText(`Move ${typeLabel}?\n\nFrom: ${sourcePath}\nTo: ${normalizedDestination || "."}\n\nExisting destination paths are refused.`, { affected: sourcePath, undoable: true, confirmLabel: `Move ${typeLabel}` }))) return false;
6257
6861
  const isDirectory = fileTreeEntryIsDirectory(entry);
6258
6862
  const restoreSourceExpanded = isDirectory && fileTreeState.expanded.has(sourcePath) && !fileTreeSearchQueryText();
6259
6863
  const expandDestinationDirectory = viaDragDrop && !fileTreeSearchQueryText();
6260
6864
  setFileTreeStatus(`Moving ${sourcePath}…`);
6261
6865
  try {
6262
6866
  const response = await api("/api/files/move", { method: "POST", body: { path: sourcePath, toPath: normalizedDestination || ".", confirmed: true }, tabId: tabContext.tabId });
6263
- if (!isCurrentTabContext(tabContext)) return;
6867
+ if (!isCurrentTabContext(tabContext)) return true;
6264
6868
  const data = response.data || {};
6265
6869
  const nextPath = normalizeFileTreePath(data.destination || normalizedDestination);
6266
6870
  const sourceParent = data.parentPath ?? fileParentPath(sourcePath);
@@ -6277,11 +6881,27 @@ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "",
6277
6881
  renderFileTree();
6278
6882
  setFileTreeStatus(`Moved ${sourcePath} to ${nextPath}.`, "success");
6279
6883
  addEvent(`${viaDragDrop ? "drag-moved" : "moved"} ${sourcePath} to ${nextPath}`, "info");
6884
+ if (offerMoveUndo && nextPath && nextPath !== sourcePath) {
6885
+ offerUndo({
6886
+ message: `Moved ${sourcePath} to ${nextPath}.`,
6887
+ undo: async () => {
6888
+ const restored = await moveFileTreeEntryToDestination(
6889
+ { ...entry, path: nextPath },
6890
+ sourcePath,
6891
+ { offerMoveUndo: false, tabContext },
6892
+ );
6893
+ if (!restored) throw new Error(`Could not move ${nextPath} back to ${sourcePath}.`);
6894
+ },
6895
+ successMessage: `Moved ${nextPath} back to ${sourcePath}.`,
6896
+ });
6897
+ }
6898
+ return true;
6280
6899
  } catch (error) {
6281
6900
  if (isCurrentTabContext(tabContext)) {
6282
6901
  setFileTreeStatus(error.message || String(error), "error");
6283
6902
  addEvent(`file move failed: ${error.message || String(error)}`, "error");
6284
6903
  }
6904
+ return false;
6285
6905
  }
6286
6906
  }
6287
6907
 
@@ -6768,6 +7388,10 @@ function syncTabMetadata(nextTabs = []) {
6768
7388
  widgetsByTab.delete(tabId);
6769
7389
  appRunnerDataByTab.delete(tabId);
6770
7390
  conversationModeByTab.delete(tabId);
7391
+ workflowModeByTab.delete(tabId);
7392
+ workflowModeTogglePendingByTab.delete(tabId);
7393
+ workflowInspectorByTab.delete(tabId);
7394
+ workflowInspectorSelectionByTab.delete(tabId);
6771
7395
  remoteMicConsentTabs.delete(tabId);
6772
7396
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
6773
7397
  clearGitWorkflowForTab(tabId);
@@ -6787,6 +7411,7 @@ function applyTabMetadata(tab) {
6787
7411
  if (tab.activity) setTabActivity(tab.id, tab.activity);
6788
7412
  if (Object.prototype.hasOwnProperty.call(tab, "conversationMode")) updateConversationModeForTab(tab.id, tab.conversationMode, { render: false });
6789
7413
  renderConversationModeControls();
7414
+ renderWorkflowModeControls();
6790
7415
  renderTabs();
6791
7416
  return true;
6792
7417
  }
@@ -7330,20 +7955,33 @@ function terminalConversationModeTooltip(tab) {
7330
7955
  return mode.enabled ? ` · natural conversation: ${mode.uiState || "listening"}` : "";
7331
7956
  }
7332
7957
 
7958
+ function tabWorkflowModeActive(tab) {
7959
+ return normalizeWorkflowModeState(workflowModeByTab.get(tab?.id) || {}).enabled === true;
7960
+ }
7961
+
7962
+ function terminalWorkflowTooltip(tab) {
7963
+ const count = workflowRunningCountForTab(tab?.id);
7964
+ return `${tabWorkflowModeActive(tab) ? " · workflow mode active" : ""}${count ? ` · ${count} workflow run${count === 1 ? "" : "s"} active` : ""}`;
7965
+ }
7966
+
7333
7967
  function terminalTabMeta(tab, indicator) {
7334
7968
  const parts = [tab.running ? `${indicator.meta} · pid ${tab.pid || "…"}` : "stopped"];
7335
7969
  if (tabAppRunnerRunningRun(tab)) parts.push("app runner");
7336
7970
  if (tabConversationModeActive(tab)) parts.push("voice");
7971
+ if (tabWorkflowModeActive(tab)) parts.push("workflow mode");
7972
+ const workflowCount = workflowRunningCountForTab(tab.id);
7973
+ if (workflowCount) parts.push(`${workflowCount} workflow${workflowCount === 1 ? "" : "s"}`);
7337
7974
  return parts.join(" · ");
7338
7975
  }
7339
7976
 
7340
- function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false }) {
7977
+ function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false, workflowModeActive = false, workflowCount = 0 }) {
7341
7978
  const titleRow = make("span", "terminal-tab-title-row");
7342
7979
  const indicatorDot = make("span", "terminal-tab-activity-indicator");
7343
7980
  indicatorDot.setAttribute("aria-hidden", "true");
7344
7981
  titleRow.append(indicatorDot, make("span", "terminal-tab-title", title));
7345
7982
  if (appRunnerIsRunning(appRunnerRun)) titleRow.append(make("span", "terminal-tab-app-runner-indicator", "app"));
7346
7983
  if (conversationModeActive) titleRow.append(make("span", "terminal-tab-conversation-indicator", "voice"));
7984
+ if (workflowModeActive || workflowCount) titleRow.append(make("span", "terminal-tab-workflow-indicator", workflowCount ? `wf ${workflowCount}` : "wf"));
7347
7985
  if (count !== null) titleRow.append(make("span", "terminal-tab-group-count", String(count)));
7348
7986
  button.append(titleRow, make("span", "terminal-tab-meta", meta));
7349
7987
  }
@@ -7355,7 +7993,9 @@ function renderTerminalTab(tab) {
7355
7993
  const appRunnerLabel = appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
7356
7994
  const conversationModeActive = tabConversationModeActive(tab);
7357
7995
  const conversationLabel = conversationModeActive ? `, natural conversation ${tabConversationMode(tab).uiState || "listening"}` : "";
7358
- const wrapper = make("div", `terminal-tab activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}${conversationModeActive ? " conversation-mode-running" : ""}`);
7996
+ const workflowModeActive = tabWorkflowModeActive(tab);
7997
+ const workflowCount = workflowRunningCountForTab(tab.id);
7998
+ const wrapper = make("div", `terminal-tab activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}${conversationModeActive ? " conversation-mode-running" : ""}${workflowModeActive ? " workflow-mode-running" : ""}${workflowCount ? " workflow-run-running" : ""}`);
7359
7999
  wrapper.dataset.tabId = tab.id;
7360
8000
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: tab.id, target: { type: "tab", tabId: tab.id } });
7361
8001
  const button = make("button", "terminal-tab-button");
@@ -7363,10 +8003,10 @@ function renderTerminalTab(tab) {
7363
8003
  button.draggable = false;
7364
8004
  button.setAttribute("role", "tab");
7365
8005
  button.setAttribute("aria-selected", isActive ? "true" : "false");
7366
- button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}`);
7367
- const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)}${terminalConversationModeTooltip(tab)} · drag onto another tab or group to group`;
8006
+ button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
8007
+ const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)}${terminalConversationModeTooltip(tab)}${terminalWorkflowTooltip(tab)} · drag onto another tab or group to group`;
7368
8008
  applyStyledTooltip(button, tooltip, { ariaLabel: false });
7369
- appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive });
8009
+ appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
7370
8010
  button.addEventListener("click", () => switchTab(tab.id));
7371
8011
  wrapper.append(button);
7372
8012
 
@@ -7393,7 +8033,9 @@ function renderTerminalTabGroupItem(tab, group) {
7393
8033
  const appRunnerLabel = appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
7394
8034
  const conversationModeActive = tabConversationModeActive(tab);
7395
8035
  const conversationLabel = conversationModeActive ? `, natural conversation ${tabConversationMode(tab).uiState || "listening"}` : "";
7396
- const item = make("div", `terminal-tab-group-item activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}${conversationModeActive ? " conversation-mode-running" : ""}`);
8036
+ const workflowModeActive = tabWorkflowModeActive(tab);
8037
+ const workflowCount = workflowRunningCountForTab(tab.id);
8038
+ const item = make("div", `terminal-tab-group-item activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}${conversationModeActive ? " conversation-mode-running" : ""}${workflowModeActive ? " workflow-mode-running" : ""}${workflowCount ? " workflow-run-running" : ""}`);
7397
8039
  item.dataset.tabId = tab.id;
7398
8040
  bindTerminalTabDragAndDrop(item, { sourceTabId: tab.id, target: group?.custom ? { type: "group", group } : { type: "tab", tabId: tab.id } });
7399
8041
  const button = make("button", "terminal-tab-button terminal-tab-group-item-button");
@@ -7401,10 +8043,10 @@ function renderTerminalTabGroupItem(tab, group) {
7401
8043
  button.draggable = false;
7402
8044
  button.setAttribute("role", "tab");
7403
8045
  button.setAttribute("aria-selected", isActive ? "true" : "false");
7404
- button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}`);
7405
- const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)}${terminalConversationModeTooltip(tab)} · drag onto another tab or group to group`;
8046
+ button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
8047
+ const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)}${terminalConversationModeTooltip(tab)}${terminalWorkflowTooltip(tab)} · drag onto another tab or group to group`;
7406
8048
  applyStyledTooltip(button, tooltip, { ariaLabel: false });
7407
- appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive });
8049
+ appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
7408
8050
  button.addEventListener("click", (event) => {
7409
8051
  event.stopPropagation();
7410
8052
  switchTab(tab.id);
@@ -7442,10 +8084,12 @@ function renderTerminalTabGroup(group, groupCount = 1) {
7442
8084
  const appRunnerCount = groupTabs.filter(tabAppRunnerRunningRun).length;
7443
8085
  const appRunnerSummary = appRunnerCount > 1 ? `${appRunnerCount} app runners running` : appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
7444
8086
  const groupAppRunnerMeta = appRunnerCount > 1 ? `${appRunnerCount} app runners` : appRunnerRun ? "app runner" : "";
8087
+ const workflowCount = groupTabs.reduce((total, tab) => total + workflowRunningCountForTab(tab.id), 0);
8088
+ const workflowModeActive = groupTabs.some(tabWorkflowModeActive);
7445
8089
  const groupTitle = terminalDisplayGroupTitle(group, activeGroupTab?.title || "group");
7446
8090
  const activeTitle = activeGroupTab?.title || groupTitle;
7447
8091
  const groupDetail = terminalDisplayGroupDetail(group, groupTitle);
7448
- const wrapper = make("div", `terminal-tab terminal-tab-group${group.custom ? " terminal-tab-custom-group" : ""} activity-${indicator.state}${isActive ? " active" : ""}${isStopped ? " stopped" : ""}${appRunnerRun ? " app-runner-running" : ""}`);
8092
+ const wrapper = make("div", `terminal-tab terminal-tab-group${group.custom ? " terminal-tab-custom-group" : ""} activity-${indicator.state}${isActive ? " active" : ""}${isStopped ? " stopped" : ""}${appRunnerRun ? " app-runner-running" : ""}${workflowModeActive ? " workflow-mode-running" : ""}${workflowCount ? " workflow-run-running" : ""}`);
7449
8093
  wrapper.dataset.groupKey = group.key;
7450
8094
  if (group.customGroupId) wrapper.dataset.customGroupId = group.customGroupId;
7451
8095
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: activeGroupTab?.id || "", target: { type: "group", group } });
@@ -7464,10 +8108,10 @@ function renderTerminalTabGroup(group, groupCount = 1) {
7464
8108
  button.setAttribute("aria-selected", isActive ? "true" : "false");
7465
8109
  button.setAttribute("aria-haspopup", "true");
7466
8110
  button.setAttribute("aria-expanded", group.key === openTerminalTabGroupKey ? "true" : "false");
7467
- button.setAttribute("aria-label", `${groupTitle} ${group.custom ? "custom" : "cwd"} group: ${groupTabs.length} tabs, ${indicator.label}${appRunnerSummary ? `, ${appRunnerSummary}` : ""}. Active ${activeTitle}`);
7468
- const tooltip = `${activeTitle} · ${groupTitle} · ${groupDetail} · ${groupTabs.length} tabs · ${indicator.label}${appRunnerSummary ? ` · ${appRunnerSummary}` : ""} · drop tabs here to add to group`;
8111
+ button.setAttribute("aria-label", `${groupTitle} ${group.custom ? "custom" : "cwd"} group: ${groupTabs.length} tabs, ${indicator.label}${appRunnerSummary ? `, ${appRunnerSummary}` : ""}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}. Active ${activeTitle}`);
8112
+ const tooltip = `${activeTitle} · ${groupTitle} · ${groupDetail} · ${groupTabs.length} tabs · ${indicator.label}${appRunnerSummary ? ` · ${appRunnerSummary}` : ""}${workflowModeActive ? " · workflow mode active" : ""}${workflowCount ? ` · ${workflowCount} workflow runs active` : ""} · drop tabs here to add to group`;
7469
8113
  applyStyledTooltip(button, tooltip, { ariaLabel: false });
7470
- appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}`, appRunnerRun, count: groupTabs.length });
8114
+ appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}${workflowModeActive ? " · workflow mode" : ""}${workflowCount ? ` · ${workflowCount} workflows` : ""}`, appRunnerRun, count: groupTabs.length, workflowModeActive, workflowCount });
7471
8115
  button.addEventListener("click", () => switchTab(activeGroupTab.id));
7472
8116
  wrapper.append(button);
7473
8117
 
@@ -7810,7 +8454,7 @@ function shouldOpenCwdChangeInNewTab(tab) {
7810
8454
  || tabHasActiveAgent(tab);
7811
8455
  }
7812
8456
 
7813
- function confirmCloseTerminalTabs(targetTabs, label) {
8457
+ async function confirmCloseTerminalTabs(targetTabs, label) {
7814
8458
  const count = targetTabs.length;
7815
8459
  const noun = count === 1 ? "tab" : "tabs";
7816
8460
  const activeAgentTabs = targetTabs.filter(tabHasActiveAgent);
@@ -7823,23 +8467,22 @@ function confirmCloseTerminalTabs(targetTabs, label) {
7823
8467
  count > 1 ? `\nTabs to close:\n${tabList}` : "",
7824
8468
  ].filter(Boolean).join("\n");
7825
8469
  const warning = activeAgentTabs.length
7826
- ? [
7827
- `WARNING: ${activeAgentTabs.length} ${activeAgentTabs.length === 1 ? "tab has an agent" : "tabs have agents"} still running or waiting for input:`,
7828
- activeList,
7829
- "",
7830
- base,
7831
- "",
7832
- "Close anyway?",
7833
- ].join("\n")
7834
- : base;
7835
- return confirm(warning);
8470
+ ? `WARNING: ${activeAgentTabs.length} ${activeAgentTabs.length === 1 ? "tab has an agent" : "tabs have agents"} still running or waiting for input:\n${activeList}`
8471
+ : "No agent work is currently running in these tabs.";
8472
+ return appConfirm({
8473
+ title: `Close ${count === 1 ? "tab" : `${count} tabs`}?`,
8474
+ summary: `${base}\n\n${warning}`,
8475
+ affected: tabList || label || `${count} terminal ${noun}`,
8476
+ undoable: false,
8477
+ confirmLabel: activeAgentTabs.length ? "Close and stop work" : count === 1 ? "Close tab" : "Close tabs",
8478
+ });
7836
8479
  }
7837
8480
 
7838
8481
  async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } = {}) {
7839
8482
  const targetIds = [...new Set(tabIds.filter(Boolean))];
7840
8483
  const targetTabs = targetIds.map((id) => tabs.find((item) => item.id === id)).filter(Boolean);
7841
8484
  if (!targetTabs.length) return;
7842
- if (!confirmCloseTerminalTabs(targetTabs, label)) return;
8485
+ if (!(await confirmCloseTerminalTabs(targetTabs, label))) return;
7843
8486
 
7844
8487
  const closedActiveTab = targetTabs.some((tab) => tab.id === activeTabId);
7845
8488
  const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
@@ -7916,10 +8559,67 @@ async function initializeTabs() {
7916
8559
  }
7917
8560
  }
7918
8561
 
7919
- function addEvent(message, level = "info") {
7920
- const line = make("div", `event ${level}`.trim());
7921
- const time = new Date().toLocaleTimeString();
7922
- line.textContent = `[${time}] ${message}`;
8562
+ function chatEventTargetForLine(line) {
8563
+ const toolCallId = line?.dataset.chatToolCallId || "";
8564
+ if (toolCallId) {
8565
+ const toolTarget = elements.chat.querySelector(`.message[data-tool-call-id="${CSS.escape(toolCallId)}"]`);
8566
+ if (toolTarget) return toolTarget;
8567
+ }
8568
+
8569
+ const eventTimestamp = Number(line?.dataset.chatEventTimestamp);
8570
+ let closestTarget = null;
8571
+ let closestDistance = Number.POSITIVE_INFINITY;
8572
+ for (const candidate of elements.chat.querySelectorAll(".message[data-chat-timestamp]")) {
8573
+ const candidateTimestamp = Number(candidate.dataset.chatTimestamp);
8574
+ if (!Number.isFinite(eventTimestamp) || !Number.isFinite(candidateTimestamp)) continue;
8575
+ const distance = Math.abs(candidateTimestamp - eventTimestamp);
8576
+ if (distance <= closestDistance) {
8577
+ closestTarget = candidate;
8578
+ closestDistance = distance;
8579
+ }
8580
+ }
8581
+ return closestTarget || Array.from(elements.chat.querySelectorAll(".message:not(.runIndicator)")).at(-1) || null;
8582
+ }
8583
+
8584
+ function highlightChatEventTarget(target) {
8585
+ clearTimeout(target._chatEventHighlightTimer);
8586
+ target.classList.remove("chat-event-target");
8587
+ void target.offsetWidth;
8588
+ target.classList.add("chat-event-target");
8589
+ target._chatEventHighlightTimer = setTimeout(() => target.classList.remove("chat-event-target"), 1600);
8590
+ }
8591
+
8592
+ function jumpToChatEvent(line) {
8593
+ const revealTarget = () => {
8594
+ const target = chatEventTargetForLine(line);
8595
+ if (!target) return;
8596
+ autoFollowChat = false;
8597
+ lastChatProgrammaticScrollAt = performance.now();
8598
+ const centeredTop = chatScrollTopForNode(target) - Math.max(stickyUserPromptViewportGap(), (elements.chat.clientHeight - target.offsetHeight) / 2);
8599
+ setChatScrollTopInstant(Math.max(0, centeredTop));
8600
+ highlightChatEventTarget(target);
8601
+ updateJumpToLatestButton();
8602
+ updateStickyUserPromptButton();
8603
+ };
8604
+
8605
+ if (isSidePanelOverlayView() && !document.body.classList.contains("side-panel-collapsed")) {
8606
+ setSidePanelCollapsed(true, { persist: false });
8607
+ requestAnimationFrame(revealTarget);
8608
+ } else {
8609
+ revealTarget();
8610
+ }
8611
+ }
8612
+
8613
+ function addEvent(message, level = "info", { toolCallId = "" } = {}) {
8614
+ const occurredAt = Date.now();
8615
+ const line = make("button", `event ${level}`.trim());
8616
+ line.type = "button";
8617
+ line.dataset.chatEventTimestamp = String(occurredAt);
8618
+ if (toolCallId) line.dataset.chatToolCallId = String(toolCallId);
8619
+ line.textContent = `[${new Date(occurredAt).toLocaleTimeString()}] ${message}`;
8620
+ line.title = "Jump to this event in the chat";
8621
+ line.setAttribute("aria-label", `${line.textContent}. Jump to this event in the chat.`);
8622
+ line.addEventListener("click", () => jumpToChatEvent(line));
7923
8623
  elements.eventLog.prepend(line);
7924
8624
  while (elements.eventLog.children.length > 120) elements.eventLog.lastElementChild?.remove();
7925
8625
  }
@@ -8555,7 +9255,7 @@ async function runGitFooterPiCalibration(mode = "current", tabContext = activeTa
8555
9255
  addEvent("PI calibration unavailable: /calibrate is not loaded in this Pi tab.", "warn");
8556
9256
  return;
8557
9257
  }
8558
- if (mode === "probe" && !confirm("Start an isolated PI calibration probe? This sends one tiny model request and may incur provider token usage.")) return;
9258
+ if (mode === "probe" && !(await appConfirmText("Start an isolated PI calibration probe? This sends one tiny model request and may incur provider token usage.", { affected: "Provider token allowance and this tab's calibration result", confirmLabel: "Start probe", danger: false }))) return;
8559
9259
 
8560
9260
  const command = mode === "probe" ? `/${commandName}` : `/${commandName} current`;
8561
9261
  gitFooterPiCalibrationInFlightByTab.add(tabContext.tabId);
@@ -9065,7 +9765,7 @@ function renderGitFooterVisibilityDialog() {
9065
9765
  if (!gitFooterVisibilityDirty) {
9066
9766
  setGitFooterVisibilityStatus(
9067
9767
  gitFooterVisibilityCommandAvailable()
9068
- ? "Runtime changes last until Pi/package restart. Use PI_GIT_FOOTER_WEBUI_HIDE or per-key env vars for persistence."
9768
+ ? "Changes are saved globally and reused by every Pi session. Reset WebUI removes the saved WebUI overrides."
9069
9769
  : commandUnavailableMessage("git-footer-visibility"),
9070
9770
  gitFooterVisibilityCommandAvailable() ? "muted" : "warn",
9071
9771
  );
@@ -9112,7 +9812,7 @@ async function applyGitFooterVisibilityDialog() {
9112
9812
  if (hide.length) await runGitFooterVisibilityCommand("hide", hide);
9113
9813
  if (show.length) await runGitFooterVisibilityCommand("show", show);
9114
9814
  gitFooterVisibilityDirty = false;
9115
- setGitFooterVisibilityStatus(`Applied ${hide.length + show.length} WebUI footer visibility change${hide.length + show.length === 1 ? "" : "s"}.`, "success");
9815
+ setGitFooterVisibilityStatus(`Saved ${hide.length + show.length} global WebUI footer visibility change${hide.length + show.length === 1 ? "" : "s"}.`, "success");
9116
9816
  requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9117
9817
  renderFooter();
9118
9818
  } catch (error) {
@@ -9129,7 +9829,7 @@ async function resetGitFooterVisibilityDialog() {
9129
9829
  try {
9130
9830
  await runGitFooterVisibilityCommand("reset");
9131
9831
  gitFooterVisibilityDirty = false;
9132
- setGitFooterVisibilityStatus("Reset WebUI footer visibility overrides.", "success");
9832
+ setGitFooterVisibilityStatus("Removed the saved global WebUI footer visibility overrides.", "success");
9133
9833
  requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9134
9834
  } catch (error) {
9135
9835
  setGitFooterVisibilityStatus(error.message || String(error), "error");
@@ -9566,7 +10266,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
9566
10266
  const protectedWarning = ["main", "master"].includes(branch)
9567
10267
  ? `\n\nWarning: ${branch} is usually a protected/shared branch. Consider pushing a feature branch and opening a PR instead.`
9568
10268
  : "";
9569
- if (!window.confirm(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?${protectedWarning}`)) return;
10269
+ if (!(await appConfirmText(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?${protectedWarning}`, { affected: `Remote Git branch ${branch || "current branch"}`, confirmLabel: "Push commits" }))) return;
9570
10270
 
9571
10271
  gitFooterSyncPushInFlightByTab.add(tabId);
9572
10272
  if (isCurrentTabContext(tabContext)) renderFooter();
@@ -9574,7 +10274,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
9574
10274
  const response = await api("/api/git-workflow/push", { method: "POST", body: {}, tabId });
9575
10275
  if (!response.ok) {
9576
10276
  if (response.code === "NO_UPSTREAM") {
9577
- const publish = window.confirm(`${response.error}\n\n${response.hint || ""}\n\nRun git push -u to publish ${branch || "the current branch"} and set its upstream?`);
10277
+ const publish = await appConfirmText(`${response.error}\n\n${response.hint || ""}\n\nRun git push -u to publish ${branch || "the current branch"} and set its upstream?`, { affected: `Remote Git branch ${branch || "current branch"}`, confirmLabel: "Publish branch" });
9578
10278
  if (publish) {
9579
10279
  const upstreamResponse = await api("/api/git-workflow/push", { method: "POST", body: { setUpstream: true }, tabId });
9580
10280
  if (!upstreamResponse.ok) throw new Error([upstreamResponse.error, upstreamResponse.hint].filter(Boolean).join("\n"));
@@ -9585,7 +10285,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
9585
10285
  throw new Error([response.error, response.hint].filter(Boolean).join("\n"));
9586
10286
  }
9587
10287
  if (response.code === "NON_FAST_FORWARD") {
9588
- const forcePush = window.confirm([
10288
+ const forcePush = await appConfirmText([
9589
10289
  response.error,
9590
10290
  "",
9591
10291
  response.hint || "",
@@ -10599,7 +11299,7 @@ async function pullGitChangesDialog() {
10599
11299
  if (behind <= 0 || gitChangesState.pulling || gitChangesState.loading || gitChangesState.fetching) return;
10600
11300
  if (gitChangesState.data?.remote?.diverged === true) return;
10601
11301
  const root = gitChangesState.data?.root || "the current repository";
10602
- if (!window.confirm(`Run git pull --ff-only in ${root}?`)) return;
11302
+ if (!(await appConfirmText(`Run git pull --ff-only in ${root}?`, { affected: root, confirmLabel: "Pull changes" }))) return;
10603
11303
 
10604
11304
  const requestSerial = ++gitChangesRequestSerial;
10605
11305
  gitChangesState = { ...gitChangesState, pulling: true, loading: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId };
@@ -10692,13 +11392,13 @@ async function integrateGitChangesDialog(mode) {
10692
11392
  const data = gitChangesState.data;
10693
11393
  const upstream = data?.remote?.upstream || "@{upstream}";
10694
11394
  const command = mode === "merge" ? `git merge --no-edit ${upstream}` : `git rebase ${upstream}`;
10695
- if (!window.confirm([
11395
+ if (!(await appConfirmText([
10696
11396
  `${mode === "merge" ? "Merge" : "Rebase onto"} ${upstream} in ${data?.root || "the current repository"}?`,
10697
11397
  "",
10698
11398
  `Command: ${command}`,
10699
11399
  mode === "rebase" ? "Rebase rewrites local commits. Conflicts open the conflicts panel." : "Conflicts open the conflicts panel.",
10700
11400
  "For risky integration, prefer a separate worktree instead.",
10701
- ].join("\n"))) return;
11401
+ ].join("\n"), { affected: data?.root || "the current repository", confirmLabel: mode === "merge" ? "Merge" : "Rebase" }))) return;
10702
11402
  gitChangesState = { ...gitChangesState, pulling: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null };
10703
11403
  renderGitChangesDialog();
10704
11404
  try {
@@ -10741,7 +11441,7 @@ async function runGitFileAction(action, path) {
10741
11441
  },
10742
11442
  }[action];
10743
11443
  if (!config) return;
10744
- if (config.confirm && !window.confirm(config.confirm)) return;
11444
+ if (config.confirm && !(await appConfirmText(config.confirm, { affected: path, confirmLabel: action }))) return;
10745
11445
  try {
10746
11446
  const response = await api(config.url, { method: "POST", body: config.body, tabId });
10747
11447
  if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || `git ${action} failed`);
@@ -10801,7 +11501,7 @@ async function runGitOperationRequest(url, body, successLabel) {
10801
11501
  function renderGitOperationPanel(operation) {
10802
11502
  const kind = operation?.operation;
10803
11503
  if (!kind) return null;
10804
- const busy = gitToolsState.busy.has("operation") || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
11504
+ const busy = gitToolsState.busy.has("operation") || gitToolsState.busy.has("conflict-agent") || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
10805
11505
  const conflicts = operation.conflicts || [];
10806
11506
  const panel = make("section", "git-operation-panel");
10807
11507
  const header = make("div", "git-operation-header");
@@ -10826,8 +11526,8 @@ function renderGitOperationPanel(operation) {
10826
11526
  reset.type = "button";
10827
11527
  reset.disabled = busy;
10828
11528
  reset.title = "git bisect reset";
10829
- reset.addEventListener("click", () => {
10830
- if (!window.confirm(`Reset the bisect session in ${operation.root}?\n\nCommand: git bisect reset\nThis returns to the pre-bisect checkout.`)) return;
11529
+ reset.addEventListener("click", async () => {
11530
+ if (!(await appConfirmText(`Reset the bisect session in ${operation.root}?\n\nCommand: git bisect reset\nThis returns to the pre-bisect checkout.`, { affected: operation.root, confirmLabel: "Reset bisect" }))) return;
10831
11531
  runGitOperationRequest("/api/git-operation/bisect", { verdict: "reset", confirmed: true }, "Reset the bisect session");
10832
11532
  });
10833
11533
  row.append(reset);
@@ -10870,6 +11570,32 @@ function renderGitOperationPanel(operation) {
10870
11570
  refresh.addEventListener("click", refreshGitChangesDialog);
10871
11571
  row.append(refresh);
10872
11572
 
11573
+ if (conflicts.length) {
11574
+ const resolveWithAgent = make("button", "git-operation-button primary", "Resolve with agent");
11575
+ resolveWithAgent.type = "button";
11576
+ resolveWithAgent.disabled = busy;
11577
+ resolveWithAgent.title = `Open a new Pi tab in ${operation.root} and send it the ${kind} conflict context`;
11578
+ resolveWithAgent.addEventListener("click", async () => {
11579
+ const sourceTabId = gitChangesState.tabId || activeTabId;
11580
+ gitToolsState.busy.add("conflict-agent");
11581
+ renderGitChangesDialog();
11582
+ try {
11583
+ const response = await api("/api/git-operation/resolve-with-agent", { method: "POST", body: {}, tabId: sourceTabId });
11584
+ if (!response.ok) throw new Error(response.error || "Failed to open a conflict-resolution agent");
11585
+ closeGitChangesDialog();
11586
+ const targetTab = await switchToResponseTab(response);
11587
+ addEvent(`Opened ${targetTab?.title || "a new Pi tab"} and sent the ${kind} conflict context.`, "success");
11588
+ } catch (error) {
11589
+ gitChangesState = { ...gitChangesState, error: error.message || String(error) };
11590
+ renderGitChangesDialog();
11591
+ } finally {
11592
+ gitToolsState.busy.delete("conflict-agent");
11593
+ if (elements.gitChangesDialog?.open) renderGitChangesDialog();
11594
+ }
11595
+ });
11596
+ row.append(resolveWithAgent);
11597
+ }
11598
+
10873
11599
  const cont = make("button", "git-operation-button primary", kind === "merge" ? "Continue (commit merge)" : "Continue");
10874
11600
  cont.type = "button";
10875
11601
  cont.disabled = busy || operation.canContinue !== true;
@@ -10882,8 +11608,8 @@ function renderGitOperationPanel(operation) {
10882
11608
  skip.type = "button";
10883
11609
  skip.disabled = busy;
10884
11610
  skip.title = operation.commands?.skip || "";
10885
- skip.addEventListener("click", () => {
10886
- if (!window.confirm(`Skip the current ${kind} step?\n\nCommand: ${operation.commands?.skip || `git ${kind} --skip`}\nThe skipped commit is left out of the result.`)) return;
11611
+ skip.addEventListener("click", async () => {
11612
+ if (!(await appConfirmText(`Skip the current ${kind} step?\n\nCommand: ${operation.commands?.skip || `git ${kind} --skip`}\nThe skipped commit is left out of the result.`, { affected: operation.root, confirmLabel: `Skip ${kind} step` }))) return;
10887
11613
  runGitOperationRequest("/api/git-operation/skip", {}, `Skipped the current ${kind} step`);
10888
11614
  });
10889
11615
  row.append(skip);
@@ -10893,16 +11619,16 @@ function renderGitOperationPanel(operation) {
10893
11619
  abort.type = "button";
10894
11620
  abort.disabled = busy;
10895
11621
  abort.title = operation.commands?.abort || "";
10896
- abort.addEventListener("click", () => {
11622
+ abort.addEventListener("click", async () => {
10897
11623
  const summary = operation.summary || {};
10898
- if (!window.confirm([
11624
+ if (!(await appConfirmText([
10899
11625
  `Abort the ${kind} in ${operation.root}?`,
10900
11626
  "",
10901
11627
  `Command: ${operation.commands?.abort || `git ${kind} --abort`}`,
10902
11628
  `Working tree: ${summary.staged || 0} staged · ${summary.unstaged || 0} unstaged · ${conflicts.length} conflicted`,
10903
11629
  "",
10904
11630
  "This discards the in-progress operation state and returns to the pre-operation HEAD.",
10905
- ].join("\n"))) return;
11631
+ ].join("\n"), { affected: operation.root, confirmLabel: `Abort ${kind}` }))) return;
10906
11632
  runGitOperationRequest("/api/git-operation/abort", { confirmed: true }, `Aborted the ${kind}`);
10907
11633
  });
10908
11634
  row.append(abort);
@@ -10983,7 +11709,7 @@ async function loadGitToolsSection(key, { force = false } = {}) {
10983
11709
 
10984
11710
  async function runGitToolAction(sectionKey, { url, method = "POST", body, confirm, success, successMessage, refreshChanges = false }) {
10985
11711
  const tabId = gitChangesState.tabId || activeTabId;
10986
- if (confirm && !window.confirm(confirm)) return;
11712
+ if (confirm && !(await appConfirmText(confirm, { affected: gitChangesState.data?.root || "the current repository", confirmLabel: success || "Continue" }))) return;
10987
11713
  gitToolsState.busy.add(sectionKey);
10988
11714
  renderGitChangesDialog();
10989
11715
  try {
@@ -11025,13 +11751,13 @@ async function confirmGitStashActionWithPreview(stash, question) {
11025
11751
  } catch {
11026
11752
  // Preview is best-effort; the confirmation still shows the stash subject.
11027
11753
  }
11028
- return window.confirm([
11754
+ return appConfirmText([
11029
11755
  question,
11030
11756
  "",
11031
11757
  stash.subject || stash.ref,
11032
11758
  "",
11033
11759
  statText ? `Preview (git stash show --stat):\n${statText.slice(0, 2000)}` : "Preview unavailable.",
11034
- ].join("\n"));
11760
+ ].join("\n"), { affected: stash.subject || stash.ref, confirmLabel: "Continue" });
11035
11761
  }
11036
11762
 
11037
11763
  function renderGitStashTools(body, data, busy) {
@@ -11951,7 +12677,7 @@ function footerBranchDirtySummaryLines() {
11951
12677
  ];
11952
12678
  }
11953
12679
 
11954
- function confirmFooterGitBranchAction(branch, { create = false, requireConfirm = false, tabContext = activeTabContext() } = {}) {
12680
+ async function confirmFooterGitBranchAction(branch, { create = false, requireConfirm = false, tabContext = activeTabContext() } = {}) {
11955
12681
  const branchName = cleanStatusText(branch);
11956
12682
  const warningLines = footerBranchAgentWarningLines(tabContext);
11957
12683
  const dirtyLines = footerBranchDirtySummaryLines();
@@ -11966,10 +12692,10 @@ function confirmFooterGitBranchAction(branch, { create = false, requireConfirm =
11966
12692
  "",
11967
12693
  "Continue?",
11968
12694
  ].join("\n");
11969
- return window.confirm(message);
12695
+ return appConfirmText(message, { affected: branchName || "the current branch", confirmLabel: create ? "Create branch" : "Switch branch" });
11970
12696
  }
11971
12697
 
11972
- function confirmFooterGitWorktreeAction(branch, { path = "", create = false, requireConfirm = false } = {}) {
12698
+ async function confirmFooterGitWorktreeAction(branch, { path = "", create = false, requireConfirm = false } = {}) {
11973
12699
  const branchName = cleanStatusText(branch);
11974
12700
  if (!requireConfirm) return true;
11975
12701
  const targetPath = cleanFooterPayloadText(path, "", 4000);
@@ -11984,7 +12710,7 @@ function confirmFooterGitWorktreeAction(branch, { path = "", create = false, req
11984
12710
  "",
11985
12711
  "Continue?",
11986
12712
  ].join("\n");
11987
- return window.confirm(message);
12713
+ return appConfirmText(message, { affected: targetPath || branchName, confirmLabel: create ? "Create worktree" : "Open worktree", danger: false });
11988
12714
  }
11989
12715
 
11990
12716
  function footerBranchCreateType(value = footerBranchCreateDraft.type) {
@@ -12075,7 +12801,7 @@ async function createFooterGitBranch(branch = footerBranchCreateName()) {
12075
12801
  return;
12076
12802
  }
12077
12803
  const tabContext = activeTabContext();
12078
- if (!confirmFooterGitBranchAction(branchName, { create: true, requireConfirm: true, tabContext })) return;
12804
+ if (!(await confirmFooterGitBranchAction(branchName, { create: true, requireConfirm: true, tabContext }))) return;
12079
12805
  await applyFooterGitBranch(branchName, { create: true, tabContext, skipConfirm: true });
12080
12806
  }
12081
12807
 
@@ -12108,7 +12834,7 @@ async function createFooterGitBranchWorktree(branch = footerBranchCreateName(),
12108
12834
  addEvent("Enter a branch name before creating a branch worktree.", "warn");
12109
12835
  return;
12110
12836
  }
12111
- if (!skipConfirm && !confirmFooterGitWorktreeAction(branchName, { create: true, requireConfirm: true })) return;
12837
+ if (!skipConfirm && !(await confirmFooterGitWorktreeAction(branchName, { create: true, requireConfirm: true }))) return;
12112
12838
  const tabId = tabContext.tabId || activeTabId;
12113
12839
  try {
12114
12840
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName, tabId };
@@ -12128,7 +12854,7 @@ async function createFooterGitBranchWorktree(branch = footerBranchCreateName(),
12128
12854
  async function openFooterGitWorktree(path, { branchName = "", tabContext = activeTabContext(), skipConfirm = false } = {}) {
12129
12855
  const worktreePath = cleanFooterPayloadText(path, "", 4000);
12130
12856
  if (!worktreePath) return;
12131
- if (!skipConfirm && !confirmFooterGitWorktreeAction(branchName, { path: worktreePath, requireConfirm: false })) return;
12857
+ if (!skipConfirm && !(await confirmFooterGitWorktreeAction(branchName, { path: worktreePath, requireConfirm: false }))) return;
12132
12858
  const tabId = tabContext.tabId || activeTabId;
12133
12859
  try {
12134
12860
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName || worktreePath, tabId };
@@ -12149,7 +12875,7 @@ async function applyFooterGitBranch(branch, { create = false, tabContext = activ
12149
12875
  const branchName = cleanStatusText(branch);
12150
12876
  if (!branchName) return;
12151
12877
  const tabId = tabContext.tabId || activeTabId;
12152
- if (!skipConfirm && !confirmFooterGitBranchAction(branchName, { create, tabContext })) return;
12878
+ if (!skipConfirm && !(await confirmFooterGitBranchAction(branchName, { create, tabContext }))) return;
12153
12879
  try {
12154
12880
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName, tabId };
12155
12881
  renderFooter();
@@ -12350,13 +13076,13 @@ function renderFooterBranchOption(branch, state = footerBranchPickerState) {
12350
13076
 
12351
13077
  async function removeFooterGitWorktree(worktree, tabContext = activeTabContext()) {
12352
13078
  const tabId = tabContext.tabId || activeTabId;
12353
- if (!window.confirm([
13079
+ if (!(await appConfirmText([
12354
13080
  `Remove worktree ${worktree.path}?`,
12355
13081
  "",
12356
13082
  `Branch: ${worktree.branch || "detached"}`,
12357
13083
  "Command: git worktree remove",
12358
13084
  "This deletes the checkout directory. Dirty worktrees and worktrees with open tabs are refused.",
12359
- ].join("\n"))) return;
13085
+ ].join("\n"), { affected: worktree.path, confirmLabel: "Remove worktree" }))) return;
12360
13086
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "" };
12361
13087
  renderFooter();
12362
13088
  try {
@@ -12381,7 +13107,7 @@ async function pruneFooterGitWorktrees(tabContext = activeTabContext()) {
12381
13107
  return;
12382
13108
  }
12383
13109
  const lines = prunable.map((item) => `${item.path}${item.reason ? ` (${item.reason})` : ""}`).join("\n");
12384
- if (!window.confirm(`Prune stale worktree records?\n\nDry run:\n${output || lines || "(no output)"}\n\nThis removes administrative records for worktree directories that no longer exist.`)) return;
13110
+ if (!(await appConfirmText(`Prune stale worktree records?\n\nDry run:\n${output || lines || "(no output)"}\n\nThis removes administrative records for worktree directories that no longer exist.`, { affected: "Stale Git worktree administration records", confirmLabel: "Prune records" }))) return;
12385
13111
  const response = await api("/api/git-worktrees/prune", { method: "POST", body: { confirmed: true }, tabId });
12386
13112
  if (!response.ok) throw new Error(response.error || "Failed to prune worktrees");
12387
13113
  addEvent("Pruned stale worktree records.", "success");
@@ -13115,7 +13841,7 @@ async function changeActiveTabCwd() {
13115
13841
  return;
13116
13842
  }
13117
13843
 
13118
- if (!window.confirm(`Restart ${tab.title} in:\n${cwd}\n\nCurrent in-flight work in this tab will be stopped. The conversation continues in the new directory.`)) return;
13844
+ if (!(await appConfirmText(`Restart ${tab.title} in:\n${cwd}\n\nCurrent in-flight work in this tab will be stopped. The conversation continues in the new directory.`, { affected: tab.title, confirmLabel: "Change working folder" }))) return;
13119
13845
 
13120
13846
  saveActiveDraft();
13121
13847
  try {
@@ -13538,16 +14264,24 @@ function subagentOverlayOutputLines(data = subagentOverlayData) {
13538
14264
  return tools;
13539
14265
  }
13540
14266
 
14267
+ function subagentOverlayOutputText(data = subagentOverlayData) {
14268
+ return subagentOverlayOutputLines(data).join("\n").trimEnd();
14269
+ }
14270
+
13541
14271
  function appendSubagentOutputWaitingIndicator(parent) {
13542
- const row = make("div", "release-npm-line subagent-output-waiting");
13543
- row.setAttribute("role", "status");
13544
- row.setAttribute("aria-label", "Waiting for agent output");
14272
+ const bubble = make("article", "message runIndicator run-indicator-message streaming subagent-output-waiting");
14273
+ bubble.setAttribute("role", "status");
14274
+ bubble.setAttribute("aria-label", "Waiting for agent output");
14275
+ const body = make("div", "message-body");
14276
+ const row = make("div", "run-indicator-row");
13545
14277
  row.append(
13546
14278
  make("span", "subagent-output-waiting-dot", "."),
13547
14279
  make("span", "subagent-output-waiting-dot", "."),
13548
14280
  make("span", "subagent-output-waiting-dot", "."),
13549
14281
  );
13550
- parent.append(row);
14282
+ body.append(row);
14283
+ bubble.append(body);
14284
+ parent.append(bubble);
13551
14285
  }
13552
14286
 
13553
14287
  function subagentOverlayStateFacts(data = subagentOverlayData) {
@@ -13584,8 +14318,9 @@ function renderSubagentOverlayWidget() {
13584
14318
  const agent = data?.agent || selection.agent || {};
13585
14319
  const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
13586
14320
  const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
13587
- const lines = subagentOverlayOutputLines(data);
13588
- const shownLines = lines.length ? lines : running && agent.currentTool ? [] : [running ? "Waiting for the first agent activity…" : "No recent output was captured."];
14321
+ const outputText = subagentOverlayOutputText(data);
14322
+ const shownText = outputText || (running && agent.currentTool ? "" : running ? "Waiting for the first agent activity…" : "No recent output was captured.");
14323
+ const shownLineCount = shownText ? shownText.split("\n").length : 0;
13589
14324
  const widget = make("section", `widget release-npm-widget app-runner-widget subagent-overlay-widget${running ? " app-runner-live-widget" : " app-runner-log-widget"}`);
13590
14325
  widget.setAttribute("aria-label", `Live output for subagent ${agent.name || "subagent"}`);
13591
14326
 
@@ -13596,17 +14331,26 @@ function renderSubagentOverlayWidget() {
13596
14331
  for (const fact of subagentOverlayStateFacts(data)) meta.append(make("span", "release-npm-pill", fact));
13597
14332
  header.append(titleWrap, meta);
13598
14333
 
13599
- const streamHeader = releaseNpmStreamHeader(running ? "Live agent output" : "Agent output", shownLines.length, { live: running });
13600
- const terminal = make("div", "release-npm-terminal subagent-overlay-terminal");
13601
- terminal.setAttribute("role", "log");
13602
- terminal.setAttribute("aria-live", running ? "polite" : "off");
13603
- for (const line of shownLines) appendReleaseNpmTerminalLine(terminal, line);
13604
- if (running && agent.currentTool) appendSubagentOutputWaitingIndicator(terminal);
14334
+ const streamHeader = releaseNpmStreamHeader(running ? "Live agent output" : "Agent output", shownLineCount, { live: running });
14335
+ const output = make("div", "subagent-overlay-transcript");
14336
+ output.setAttribute("role", "log");
14337
+ output.setAttribute("aria-live", running ? "polite" : "off");
14338
+ if (shownText) {
14339
+ const { bubble } = createMessageBubble({
14340
+ role: "assistant",
14341
+ title: "final output",
14342
+ timestamp: data?.updatedAt || Date.now(),
14343
+ content: shownText,
14344
+ }, { streaming: running, transient: true });
14345
+ bubble.classList.add("subagent-overlay-message");
14346
+ output.append(bubble);
14347
+ }
14348
+ if (running && agent.currentTool) appendSubagentOutputWaitingIndicator(output);
13605
14349
 
13606
14350
  const controls = make("div", "release-npm-controls subagent-overlay-output-controls");
13607
14351
  const actions = make("div", "app-runner-output-actions");
13608
14352
  const copyButton = appRunnerActionButton("Copy output", copySubagentOverlayOutput, "subagent-overlay-copy-action");
13609
- copyButton.disabled = subagentOverlayOutputLines(data).length === 0;
14353
+ copyButton.disabled = !outputText;
13610
14354
  const refreshButton = appRunnerActionButton(subagentOverlayLoading ? "Refreshing…" : "Refresh", () => {
13611
14355
  refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
13612
14356
  }, "subagent-overlay-refresh-action");
@@ -13620,9 +14364,9 @@ function renderSubagentOverlayWidget() {
13620
14364
  subagentOverlayError,
13621
14365
  ].filter(Boolean);
13622
14366
  controls.append(actions, make("span", `app-runner-output-meta${subagentOverlayError ? " warning" : ""}`, details.join(" · ")));
13623
- const outputDetails = renderReleaseNpmOutputDetails(`subagent:${selection.tabId}:${selection.agentId}`, streamHeader, terminal, controls);
14367
+ const outputDetails = renderReleaseNpmOutputDetails(`subagent:${selection.tabId}:${selection.agentId}`, streamHeader, output, controls);
13624
14368
  widget.append(header, outputDetails);
13625
- requestAnimationFrame(() => { if (outputDetails.open) terminal.scrollTop = terminal.scrollHeight; });
14369
+ requestAnimationFrame(() => { if (outputDetails.open) output.scrollTop = output.scrollHeight; });
13626
14370
  return widget;
13627
14371
  }
13628
14372
 
@@ -13697,7 +14441,7 @@ function closeSubagentOverlay() {
13697
14441
  }
13698
14442
 
13699
14443
  async function copySubagentOverlayOutput() {
13700
- const text = subagentOverlayOutputLines().join("\n").trimEnd();
14444
+ const text = subagentOverlayOutputText();
13701
14445
  if (!text) {
13702
14446
  addEvent("subagent output is empty", "warn");
13703
14447
  return;
@@ -13819,12 +14563,62 @@ function initializeSubagents() {
13819
14563
  refreshSubagents().finally(() => scheduleRefreshSubagents());
13820
14564
  }
13821
14565
 
13822
- function renderStatus() {
13823
- if (deferUiRenderDuringPointerActivation("status", renderStatus)) return;
13824
- const state = currentState;
14566
+ function sessionCopyButton(label, value) {
14567
+ const button = make("button", "session-copy-button", "Copy");
14568
+ button.type = "button";
14569
+ button.title = `Copy ${label.toLowerCase()}`;
14570
+ button.setAttribute("aria-label", button.title);
14571
+ button.addEventListener("click", async () => {
14572
+ const original = button.textContent;
14573
+ try {
14574
+ await copyText(value);
14575
+ button.textContent = "Copied";
14576
+ button.classList.add("copied");
14577
+ } catch {
14578
+ button.textContent = "Failed";
14579
+ }
14580
+ setTimeout(() => {
14581
+ if (!button.isConnected) return;
14582
+ button.textContent = original;
14583
+ button.classList.remove("copied");
14584
+ }, 1400);
14585
+ });
14586
+ return button;
14587
+ }
14588
+
14589
+ function sessionDetailField(label, value, { secondary = "", copyValue = "", mono = false, truncate = false, wide = false } = {}) {
14590
+ const field = make("div", `session-detail-field${wide ? " wide" : ""}`);
14591
+ const labelNode = make("span", "session-detail-label", label);
14592
+ const valueRow = make("div", "session-detail-value-row");
14593
+ const valueCopy = make("div", `session-detail-value${mono ? " mono" : ""}${truncate ? " truncate" : ""}`);
14594
+ const primary = make("span", "session-detail-primary", value);
14595
+ primary.title = copyValue || value;
14596
+ valueCopy.append(primary);
14597
+ if (secondary) {
14598
+ const secondaryNode = make("span", "session-detail-secondary", secondary);
14599
+ secondaryNode.title = copyValue || secondary;
14600
+ valueCopy.append(secondaryNode);
14601
+ }
14602
+ valueRow.append(valueCopy);
14603
+ if (copyValue) valueRow.append(sessionCopyButton(label, copyValue));
14604
+ field.append(labelNode, valueRow);
14605
+ return field;
14606
+ }
14607
+
14608
+ function splitSessionFilePath(sessionFile) {
14609
+ const value = String(sessionFile || "");
14610
+ const separator = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
14611
+ if (separator < 0) return { name: value || "in-memory", directory: "" };
14612
+ const directory = value.slice(0, separator).replace(/^\/home\/[^/]+(?=\/|$)/, "~");
14613
+ return { name: value.slice(separator + 1) || value, directory };
14614
+ }
14615
+
14616
+ function renderStatus() {
14617
+ if (deferUiRenderDuringPointerActivation("status", renderStatus)) return;
14618
+ const state = currentState;
13825
14619
  updateComposerModeButtons();
13826
- const running = state?.isStreaming ? "running" : "idle";
13827
- const compacting = state?.isCompacting ? " · compacting" : "";
14620
+ const statusKey = state?.isCompacting ? "compacting" : state?.isStreaming ? "running" : "idle";
14621
+ const statusLabel = statusKey[0].toUpperCase() + statusKey.slice(1);
13828
14622
 
13829
14623
  elements.stateDetails.replaceChildren();
13830
14624
  const pendingThinkingLevel = state?.pendingThinkingLevel || null;
@@ -13832,19 +14626,43 @@ function renderStatus() {
13832
14626
  const thinkingDetail = pendingThinkingLevel && pendingThinkingLevel !== state?.thinkingLevel
13833
14627
  ? `${state?.thinkingLevel || "unknown"} → ${pendingThinkingLevel} next prompt`
13834
14628
  : state?.thinkingLevel || "unknown";
13835
- const details = {
13836
- Status: `${running}${compacting}`,
13837
- Model: modelLabel(state?.model),
13838
- Thinking: thinkingDetail,
13839
- Session: state?.sessionName || state?.sessionId || "unknown",
13840
- File: state?.sessionFile || "in-memory",
13841
- Messages: String(state?.messageCount ?? "?"),
13842
- Queue: String(state?.pendingMessageCount ?? 0),
13843
- "Auto compact": footerAutoCompactionEnabled(state) ? "on" : "off",
13844
- };
13845
- for (const [key, value] of Object.entries(details)) {
13846
- elements.stateDetails.append(make("dt", undefined, key), make("dd", undefined, value));
13847
- }
14629
+ const overview = make("div", "session-overview");
14630
+ const statusCard = make("div", `session-status-card ${statusKey}`);
14631
+ const statusDot = make("span", "session-status-dot");
14632
+ statusDot.setAttribute("aria-hidden", "true");
14633
+ const statusCopy = make("span", "session-overview-copy");
14634
+ statusCopy.append(make("span", "session-overview-label", "Status"), make("strong", undefined, statusLabel));
14635
+ statusCard.append(statusDot, statusCopy);
14636
+ const messagesCard = make("div", "session-metric-card");
14637
+ messagesCard.append(make("span", "session-overview-label", "Messages"), make("strong", undefined, String(state?.messageCount ?? "?")));
14638
+ const queueCard = make("div", "session-metric-card");
14639
+ queueCard.append(make("span", "session-overview-label", "Queue"), make("strong", undefined, String(state?.pendingMessageCount ?? 0)));
14640
+ overview.append(statusCard, messagesCard, queueCard);
14641
+
14642
+ const sessionId = state?.sessionId || "unknown";
14643
+ const sessionName = state?.sessionName && state.sessionName !== sessionId ? state.sessionName : "";
14644
+ const sessionFile = state?.sessionFile || "";
14645
+ const fileParts = splitSessionFilePath(sessionFile);
14646
+ const infoGrid = make("div", "session-info-grid");
14647
+ infoGrid.append(
14648
+ sessionDetailField("Model", modelLabel(state?.model), { wide: true, truncate: true }),
14649
+ sessionDetailField("Thinking", thinkingDetail, { truncate: true }),
14650
+ sessionDetailField("Auto compact", footerAutoCompactionEnabled(state) ? "On" : "Off"),
14651
+ sessionDetailField("Session ID", sessionName || sessionId, {
14652
+ secondary: sessionName ? sessionId : "",
14653
+ copyValue: sessionId !== "unknown" ? sessionId : "",
14654
+ mono: !sessionName,
14655
+ wide: true,
14656
+ }),
14657
+ sessionDetailField("Session file", fileParts.name, {
14658
+ secondary: fileParts.directory,
14659
+ copyValue: sessionFile,
14660
+ mono: true,
14661
+ truncate: true,
14662
+ wide: true,
14663
+ }),
14664
+ );
14665
+ elements.stateDetails.append(overview, infoGrid);
13848
14666
 
13849
14667
  if (shownThinkingLevel) elements.thinkingSelect.value = shownThinkingLevel;
13850
14668
  elements.compactButton.disabled = !!state?.isCompacting;
@@ -14401,6 +15219,191 @@ function renderReleaseAurLogWidget() {
14401
15219
  return node;
14402
15220
  }
14403
15221
 
15222
+ function parseWorkflowInspectorPayload(lines) {
15223
+ const raw = String(lines?.[0] || "").trim();
15224
+ if (!raw.startsWith(WORKFLOW_INSPECTOR_PAYLOAD_PREFIX)) return null;
15225
+ try {
15226
+ const payload = JSON.parse(raw.slice(WORKFLOW_INSPECTOR_PAYLOAD_PREFIX.length));
15227
+ if (payload?.type !== WORKFLOW_INSPECTOR_PAYLOAD_TYPE || payload.version !== WORKFLOW_INSPECTOR_PAYLOAD_VERSION || !Array.isArray(payload.runs)) return null;
15228
+ if (!payload.runs.every((run) => run && typeof run.runId === "string" && Array.isArray(run.phases) && run.controls && typeof run.controls === "object")) return null;
15229
+ return payload;
15230
+ } catch {
15231
+ return null;
15232
+ }
15233
+ }
15234
+
15235
+ function updateWorkflowInspectorForTab(tabId, payload) {
15236
+ if (!tabId || !payload) return;
15237
+ workflowInspectorByTab.set(tabId, payload);
15238
+ if (payload.mode) updateWorkflowModeForTab(tabId, { ...payload.mode, available: true, updatedAt: payload.updatedAt }, { render: tabId === activeTabId });
15239
+ const selection = workflowInspectorSelectionByTab.get(tabId) || {};
15240
+ if (selection.runId && !payload.runs.some((run) => run.runId === selection.runId)) workflowInspectorSelectionByTab.delete(tabId);
15241
+ }
15242
+
15243
+ function activeWorkflowInspectorPayload() {
15244
+ const cached = workflowInspectorByTab.get(activeTabId);
15245
+ if (cached) return cached;
15246
+ const parsed = parseWorkflowInspectorPayload(getWidgetLines(WORKFLOW_INSPECTOR_WIDGET_KEY));
15247
+ if (parsed && activeTabId) updateWorkflowInspectorForTab(activeTabId, parsed);
15248
+ return parsed;
15249
+ }
15250
+
15251
+ function workflowRunIsLive(run) {
15252
+ return ["queued", "validating", "awaiting_approval", "running", "paused"].includes(run?.status);
15253
+ }
15254
+
15255
+ function workflowRunningCountForTab(tabId) {
15256
+ const payload = workflowInspectorByTab.get(tabId);
15257
+ return Array.isArray(payload?.runs) ? payload.runs.filter(workflowRunIsLive).length : 0;
15258
+ }
15259
+
15260
+ function workflowInspectorSelection(payload) {
15261
+ const existing = workflowInspectorSelectionByTab.get(activeTabId) || {};
15262
+ const run = payload.runs.find((candidate) => candidate.runId === existing.runId)
15263
+ || payload.runs.find(workflowRunIsLive)
15264
+ || payload.runs[0];
15265
+ const phase = run?.phases?.find((candidate) => candidate.phaseId === existing.phaseId) || run?.phases?.[0];
15266
+ const agent = phase?.agents?.find((candidate) => candidate.callId === existing.callId) || phase?.agents?.[0];
15267
+ const next = { runId: run?.runId || "", phaseId: phase?.phaseId || "", callId: agent?.callId || "" };
15268
+ if (activeTabId) workflowInspectorSelectionByTab.set(activeTabId, next);
15269
+ return { run, phase, agent, selection: next };
15270
+ }
15271
+
15272
+ function workflowInspectorSetSelection(patch) {
15273
+ if (!activeTabId) return;
15274
+ workflowInspectorSelectionByTab.set(activeTabId, { ...(workflowInspectorSelectionByTab.get(activeTabId) || {}), ...patch });
15275
+ renderWidgets();
15276
+ }
15277
+
15278
+ function workflowInspectorJson(value) {
15279
+ if (value === undefined) return "—";
15280
+ if (typeof value === "string") return value;
15281
+ try { return JSON.stringify(value, null, 2); } catch { return String(value); }
15282
+ }
15283
+
15284
+ async function sendWorkflowInspectorCommand(command, { confirmMessage = "" } = {}) {
15285
+ const tabContext = activeTabContext();
15286
+ if (!tabContext.tabId || !command) return;
15287
+ if (confirmMessage && !window.confirm(confirmMessage)) return;
15288
+ try {
15289
+ await sendPrompt("prompt", command, { targetTabId: tabContext.tabId, throwOnError: true });
15290
+ if (isCurrentTabContext(tabContext)) addEvent(`workflow action sent: ${command}`, "info");
15291
+ } catch (error) {
15292
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
15293
+ }
15294
+ }
15295
+
15296
+ function workflowInspectorActionButton(label, command, { danger = false, confirmMessage = "" } = {}) {
15297
+ const button = make("button", `release-npm-action${danger ? " danger" : ""}`, label);
15298
+ button.type = "button";
15299
+ button.addEventListener("click", () => void sendWorkflowInspectorCommand(command, { confirmMessage }));
15300
+ return button;
15301
+ }
15302
+
15303
+ function renderWorkflowInspectorAgent(agent, run) {
15304
+ const details = make("details", "workflow-inspector-agent");
15305
+ const summary = make("summary", "workflow-inspector-agent-summary");
15306
+ summary.append(
15307
+ make("span", `workflow-inspector-status status-${agent.status || "unknown"}`, agent.status || "unknown"),
15308
+ make("strong", undefined, agent.name || agent.label || agent.taskId || agent.callId),
15309
+ );
15310
+ details.append(summary);
15311
+ const body = make("div", "workflow-inspector-agent-body");
15312
+ const prompt = make("details", "workflow-inspector-block");
15313
+ prompt.append(make("summary", undefined, "Prompt"), make("pre", undefined, agent.prompt || "—"));
15314
+ body.append(prompt);
15315
+ if (Array.isArray(agent.recentEvents) && agent.recentEvents.length) {
15316
+ const activity = make("details", "workflow-inspector-block");
15317
+ activity.append(make("summary", undefined, `Recent activity (${agent.recentEvents.length})`));
15318
+ activity.append(make("pre", undefined, agent.recentEvents.slice(-12).map((event) => `${event.timestamp || ""} ${event.line || event.command || event.eventType || event.type || "event"}`.trim()).join("\n")));
15319
+ body.append(activity);
15320
+ }
15321
+ const result = make("details", "workflow-inspector-block");
15322
+ result.append(make("summary", undefined, "Result and usage"), make("pre", undefined, `${workflowInspectorJson(agent.result)}\n\nUsage: ${workflowInspectorJson(agent.usage)}${agent.worktree ? `\n\nIsolated worktree: ${workflowInspectorJson(agent.worktree)}` : ""}${agent.error ? `\n\nError: ${agent.error}` : ""}`));
15323
+ body.append(result);
15324
+ if (run.controls?.canRetry) {
15325
+ const controls = make("div", "workflow-inspector-inline-actions");
15326
+ controls.append(workflowInspectorActionButton("Retry agent", `/workflow retry ${run.runId} ${agent.callId}`, {
15327
+ confirmMessage: `Retry ${agent.name || agent.callId}? Unrelated completed calls will remain cached.`,
15328
+ }));
15329
+ body.append(controls);
15330
+ }
15331
+ details.append(body);
15332
+ return details;
15333
+ }
15334
+
15335
+ function renderWorkflowInspectorWidget() {
15336
+ if (!isOptionalFeatureEnabled("workflows")) return null;
15337
+ const payload = activeWorkflowInspectorPayload();
15338
+ if (!payload?.runs?.length) return null;
15339
+ const { run, phase } = workflowInspectorSelection(payload);
15340
+ if (!run) return null;
15341
+
15342
+ const node = make("section", "widget release-npm-widget workflow-widget workflow-inspector-widget");
15343
+ node.setAttribute("aria-label", "workflow run inspector");
15344
+ const header = make("div", "release-npm-header");
15345
+ const titleWrap = make("div", "release-npm-title-wrap");
15346
+ titleWrap.append(make("span", "release-npm-kicker", "workflows"), make("strong", "release-npm-title", `${payload.runs.length} run${payload.runs.length === 1 ? "" : "s"}`));
15347
+ const meta = make("div", "release-npm-meta");
15348
+ meta.append(make("span", "release-npm-pill", payload.mode?.enabled ? `mode ${payload.mode.phase}` : "mode off"));
15349
+ const liveCount = payload.runs.filter(workflowRunIsLive).length;
15350
+ if (liveCount) meta.append(make("span", "release-npm-pill workflow-status running", `${liveCount} active`));
15351
+ header.append(titleWrap, meta);
15352
+
15353
+ const layout = make("div", "workflow-inspector-layout");
15354
+ const runList = make("nav", "workflow-inspector-run-list");
15355
+ runList.setAttribute("aria-label", "Workflow runs");
15356
+ for (const candidate of payload.runs) {
15357
+ const button = make("button", `workflow-inspector-run${candidate.runId === run.runId ? " active" : ""}`);
15358
+ button.type = "button";
15359
+ button.append(make("span", `workflow-inspector-status status-${candidate.status}`, candidate.status), make("strong", undefined, candidate.workflowName || candidate.workflowKey), make("small", undefined, candidate.runId));
15360
+ button.addEventListener("click", () => workflowInspectorSetSelection({ runId: candidate.runId, phaseId: "", callId: "" }));
15361
+ runList.append(button);
15362
+ }
15363
+
15364
+ const detail = make("div", "workflow-inspector-detail");
15365
+ const runHeader = make("div", "workflow-inspector-run-header");
15366
+ runHeader.append(make("div", undefined, `${run.workflowName || run.workflowKey}\n${run.runId}`));
15367
+ const actions = make("div", "release-npm-actions workflow-inspector-actions");
15368
+ if (run.controls?.canPause) actions.append(workflowInspectorActionButton("Pause", `/workflow pause ${run.runId}`));
15369
+ if (run.status === "paused") actions.append(workflowInspectorActionButton("Resume", `/workflow resume ${run.runId}`));
15370
+ else if (run.controls?.canResume) actions.append(workflowInspectorActionButton("Replay", `/workflow resume ${run.runId}`, { confirmMessage: `Replay ${run.workflowName || run.runId}?` }));
15371
+ if (run.controls?.canAbort) actions.append(workflowInspectorActionButton("Abort", `/workflow abort ${run.runId}`, { danger: true, confirmMessage: `Abort ${run.workflowName || run.runId} and active subprocesses?` }));
15372
+ if (run.controls?.canSave) {
15373
+ actions.append(workflowInspectorActionButton("Save user", `/workflow save ${run.runId} --user`));
15374
+ actions.append(workflowInspectorActionButton("Save project", `/workflow save ${run.runId} --project`));
15375
+ }
15376
+ runHeader.append(actions);
15377
+ detail.append(runHeader);
15378
+ const summary = make("pre", "workflow-inspector-run-summary", `Status: ${run.status}\nStarted: ${run.startedAt}\nUsage: ${workflowInspectorJson(run.usage)}\nResult: ${workflowInspectorJson(run.result)}${run.error ? `\nError: ${run.error}` : ""}`);
15379
+ detail.append(summary);
15380
+
15381
+ if (run.phases?.length) {
15382
+ const phaseTabs = make("div", "workflow-inspector-phase-tabs");
15383
+ for (const candidate of run.phases) {
15384
+ const button = make("button", `workflow-inspector-phase-tab${candidate.phaseId === phase?.phaseId ? " active" : ""}`, `${candidate.name} · ${candidate.status}`);
15385
+ button.type = "button";
15386
+ button.addEventListener("click", () => workflowInspectorSetSelection({ phaseId: candidate.phaseId, callId: "" }));
15387
+ phaseTabs.append(button);
15388
+ }
15389
+ detail.append(phaseTabs);
15390
+ if (phase) {
15391
+ const agents = make("div", "workflow-inspector-agent-list");
15392
+ for (const agent of phase.agents || []) agents.append(renderWorkflowInspectorAgent(agent, run));
15393
+ if (!phase.agents?.length) agents.append(make("p", "muted", "This phase has no agent calls."));
15394
+ detail.append(agents);
15395
+ }
15396
+ }
15397
+ if (run.script) {
15398
+ const raw = make("details", "workflow-inspector-raw-script");
15399
+ raw.append(make("summary", undefined, "Raw workflow script"), make("pre", undefined, run.script));
15400
+ detail.append(raw);
15401
+ }
15402
+ layout.append(runList, detail);
15403
+ node.append(header, layout);
15404
+ return node;
15405
+ }
15406
+
14404
15407
  function parseWorkflowSubprocessPayload(lines) {
14405
15408
  const raw = String(lines?.[0] || "").trim();
14406
15409
  if (!raw) return null;
@@ -14871,7 +15874,16 @@ async function saveAppRunnerCustomRunner(form) {
14871
15874
  }
14872
15875
  }
14873
15876
 
14874
- async function deleteAppRunnerCustomRunner(id) {
15877
+ async function deleteAppRunnerCustomRunner(runner = {}) {
15878
+ const id = String(runner.id || "");
15879
+ if (!id) return;
15880
+ const restoreRunner = {
15881
+ id,
15882
+ label: runner.label || "",
15883
+ command: runner.command || "./",
15884
+ path: runner.path || "",
15885
+ args: appRunnerCustomArgsText(runner.args),
15886
+ };
14875
15887
  const tabContext = activeTabContext();
14876
15888
  try {
14877
15889
  const response = await api("/api/app-runner-config", { method: "DELETE", body: { id }, tabId: tabContext.tabId });
@@ -14883,6 +15895,20 @@ async function deleteAppRunnerCustomRunner(id) {
14883
15895
  renderWidgets();
14884
15896
  renderAppRunnerInfoDialog();
14885
15897
  addEvent("deleted custom app runner", "warn");
15898
+ offerUndo({
15899
+ message: `Deleted custom app runner “${runner.label || runner.path || id}”.`,
15900
+ undo: async () => {
15901
+ const restored = await api("/api/app-runner-config", { method: "POST", body: { runner: restoreRunner }, tabId: tabContext.tabId });
15902
+ if (isCurrentTabContext(tabContext)) {
15903
+ setAppRunnerData(tabContext.tabId, restored.data || {});
15904
+ setAppRunnerCustomFeedback("success", "Restored custom app runner.");
15905
+ renderAppRunnerControls();
15906
+ renderWidgets();
15907
+ renderAppRunnerInfoDialog();
15908
+ }
15909
+ },
15910
+ successMessage: `Restored custom app runner “${runner.label || runner.path || id}”.`,
15911
+ });
14886
15912
  } catch (error) {
14887
15913
  if (!isCurrentTabContext(tabContext)) return;
14888
15914
  const message = error.message || String(error);
@@ -14987,10 +16013,7 @@ function renderAppRunnerCustomSection() {
14987
16013
  });
14988
16014
  const remove = make("button", "danger", "Delete");
14989
16015
  remove.type = "button";
14990
- remove.addEventListener("click", () => {
14991
- if (!confirm(`Delete custom app runner “${runner.label || runner.path || runner.id}”?`)) return;
14992
- deleteAppRunnerCustomRunner(runner.id);
14993
- });
16016
+ remove.addEventListener("click", () => deleteAppRunnerCustomRunner(runner));
14994
16017
  actions.append(edit, remove);
14995
16018
  row.append(details, actions);
14996
16019
  existing.append(row);
@@ -15596,7 +16619,7 @@ async function runStatsCalibration(mode) {
15596
16619
  renderStatsOverlay();
15597
16620
  return;
15598
16621
  }
15599
- if (mode === "probe" && !confirm("Start an isolated calibration probe? This sends one tiny model request and may incur provider token usage.")) return;
16622
+ if (mode === "probe" && !(await appConfirmText("Start an isolated calibration probe? This sends one tiny model request and may incur provider token usage.", { affected: "Provider token allowance and calibration results", confirmLabel: "Start probe", danger: false }))) return;
15600
16623
 
15601
16624
  const command = mode === "current" ? `/${commandName} current` : `/${commandName}`;
15602
16625
  statsOverlayCalibrationBusy = mode;
@@ -16320,6 +17343,8 @@ function renderWidgets() {
16320
17343
  if (releaseAurOutput) elements.widgetArea.append(releaseAurOutput);
16321
17344
  const releaseAurLog = renderReleaseAurLogWidget();
16322
17345
  if (releaseAurLog) elements.widgetArea.append(releaseAurLog);
17346
+ const workflowInspectorWidget = renderWorkflowInspectorWidget();
17347
+ if (workflowInspectorWidget) elements.widgetArea.append(workflowInspectorWidget);
16323
17348
  const workflowSubprocessWidget = renderWorkflowSubprocessWidget();
16324
17349
  if (workflowSubprocessWidget) elements.widgetArea.append(workflowSubprocessWidget);
16325
17350
  const appRunnerWidget = renderAppRunnerWidget();
@@ -17100,8 +18125,9 @@ async function gitWorkflowRequest(path, { method = "POST", body = {}, runId, tab
17100
18125
  }
17101
18126
  if (expectedRunId !== undefined && !isCurrentGitWorkflowRun(expectedRunId, tabId)) return null;
17102
18127
  if (!response.ok) {
18128
+ const hint = response.hint ? `\n\nHint: ${response.hint}` : "";
17103
18129
  const detail = response.data ? `\n\n${formatGitCommandResult(response.data)}` : "";
17104
- throw new Error(`${response.error || "Git workflow request failed"}${detail}`);
18130
+ throw new Error(`${response.error || "Git workflow request failed"}${hint}${detail}`);
17105
18131
  }
17106
18132
  return response.data;
17107
18133
  }
@@ -17160,7 +18186,7 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
17160
18186
  }
17161
18187
 
17162
18188
  const workflow = gitWorkflowForTab(tabId);
17163
- if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !confirm("Restart the active git workflow?")) return;
18189
+ if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !(await appConfirmText("Restart the active git workflow?", { affected: "The active guided Git workflow", confirmLabel: "Restart workflow" }))) return;
17164
18190
  const preferences = setupData.preferences;
17165
18191
  workflow.runId += 1;
17166
18192
  setGitWorkflow({
@@ -17194,10 +18220,10 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
17194
18220
  }, { tabId });
17195
18221
  }
17196
18222
 
17197
- function startGitInitWorkflow(tabId = activeTabId) {
18223
+ async function startGitInitWorkflow(tabId = activeTabId) {
17198
18224
  if (!tabId) return;
17199
18225
  const workflow = gitWorkflowForTab(tabId);
17200
- if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !confirm("Restart the active git repository setup workflow?")) return;
18226
+ if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !(await appConfirmText("Restart the active git repository setup workflow?", { affected: "The active Git repository setup workflow", confirmLabel: "Restart setup" }))) return;
17201
18227
  const setup = readGitFooterStatusSetup().githubUsername ? readGitFooterStatusSetup() : configureGitFooterStatusSetup({ force: true });
17202
18228
  const githubUsername = setup?.githubUsername || "";
17203
18229
  const repoName = defaultGitInitRepoName(tabs.find((tab) => tab.id === tabId) || activeTab());
@@ -17847,14 +18873,14 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
17847
18873
  const failureStep = variant === "input" && workflow.step === "generate" ? "generate" : "message";
17848
18874
  const inputMessage = variant === "input" ? gitWorkflowManualCommitInputMessage(workflow) : "";
17849
18875
  if (workflow.preferences?.verificationPolicy === "ask" && !workflow.verificationConfirmed) {
17850
- const proceed = window.confirm([
18876
+ const proceed = await appConfirmText([
17851
18877
  "Pre-commit verification reminder",
17852
18878
  "",
17853
18879
  "Review the staged diff and any relevant test, lint, or build results before committing.",
17854
18880
  "Git hooks and signing configuration will still run normally.",
17855
18881
  "",
17856
18882
  "Continue with this commit?",
17857
- ].join("\n"));
18883
+ ].join("\n"), { affected: "The staged Git changes", confirmLabel: "Continue to commit" });
17858
18884
  if (!proceed) return;
17859
18885
  workflow.verificationConfirmed = true;
17860
18886
  }
@@ -17883,7 +18909,7 @@ async function pushGitWorkflow(tabId = gitWorkflowActionTabId()) {
17883
18909
  const tabContext = activeTabContext(tabId);
17884
18910
  const workflow = gitWorkflowForTab(tabId, { create: false });
17885
18911
  if (!workflow) return;
17886
- if (!window.confirm("Push the committed changes to the configured upstream?\n\nGuided Git never force-pushes automatically.")) return;
18912
+ if (!(await appConfirmText("Push the committed changes to the configured upstream?\n\nGuided Git never force-pushes automatically.", { affected: "The configured remote Git branch", confirmLabel: "Push commits" }))) return;
17887
18913
  const runId = workflow.runId;
17888
18914
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: "Running git push…" }, { tabId });
17889
18915
  try {
@@ -17975,7 +19001,7 @@ async function pushAndCreatePrGitWorkflow(tabId = gitWorkflowActionTabId()) {
17975
19001
  const workflow = gitWorkflowForTab(tabId, { create: false });
17976
19002
  if (!workflow) return;
17977
19003
  const branch = workflow.prBranch || "current branch";
17978
- if (!window.confirm(`Push ${branch} and continue to generated PR review?\n\nThe pull request is still created only after a second explicit review/confirmation.`)) return;
19004
+ if (!(await appConfirmText(`Push ${branch} and continue to generated PR review?\n\nThe pull request is still created only after a second explicit review/confirmation.`, { affected: `Remote Git branch ${branch}`, confirmLabel: "Push and review PR" }))) return;
17979
19005
  const runId = workflow.runId;
17980
19006
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: `Pushing PR branch ${branch}…` }, { tabId });
17981
19007
  try {
@@ -18378,13 +19404,12 @@ function loadSelectedPromptListIntoEditor() {
18378
19404
  if (loadPromptListIntoEditor(list, { updateLoaded: true })) elements.promptListDialog?.close();
18379
19405
  }
18380
19406
 
18381
- function deleteSelectedPromptList() {
19407
+ async function deleteSelectedPromptList() {
18382
19408
  const list = savedPromptListById(elements.promptListSelect?.value);
18383
19409
  if (!list) {
18384
19410
  setPromptListStatus("No saved prompt list selected to delete.", "warn");
18385
19411
  return;
18386
19412
  }
18387
- if (!window.confirm(`Delete prompt list “${list.name}”? This cannot be undone.`)) return;
18388
19413
  const deleted = deleteStoredPromptList(list.id);
18389
19414
  if (!deleted) {
18390
19415
  setPromptListStatus("Prompt list was already deleted.", "warn");
@@ -18400,6 +19425,15 @@ function deleteSelectedPromptList() {
18400
19425
  populatePromptListSelect();
18401
19426
  setPromptListStatus(`Deleted “${deleted.name}”.`, "success");
18402
19427
  addEvent(`deleted prompt list “${deleted.name}”`);
19428
+ offerUndo({
19429
+ message: `Deleted prompt list “${deleted.name}”.`,
19430
+ undo: () => {
19431
+ upsertStoredPromptList(deleted);
19432
+ populatePromptListSelect(deleted.id);
19433
+ setPromptListStatus(`Restored “${deleted.name}”.`, "success");
19434
+ },
19435
+ successMessage: `Restored prompt list “${deleted.name}”.`,
19436
+ });
18403
19437
  }
18404
19438
 
18405
19439
  function openPromptListDialog({ mode = "create", list = null } = {}) {
@@ -19968,6 +21002,115 @@ function appendChatMessageBubble(bubble) {
19968
21002
  }
19969
21003
  }
19970
21004
 
21005
+ function emptyStartRecentWorkspaces() {
21006
+ const seen = new Set();
21007
+ return pathFastPicks.map((item) => {
21008
+ const cwd = typeof item === "string" ? item.trim() : typeof item?.cwd === "string" ? item.cwd.trim() : "";
21009
+ const rawLabel = typeof item === "string" ? item : typeof item?.displayCwd === "string" ? item.displayCwd : cwd;
21010
+ const label = String(rawLabel || "").trim();
21011
+ if (!cwd || !label || /^\[object Object\]$/i.test(label) || seen.has(cwd)) return null;
21012
+ seen.add(cwd);
21013
+ return { cwd, label: normalizeDisplayPath(label) };
21014
+ }).filter(Boolean).slice(0, 4);
21015
+ }
21016
+
21017
+ function emptyStartAction({ title, description, symbol, className = "", onClick }) {
21018
+ const button = make("button", `empty-start-action ${className}`.trim());
21019
+ button.type = "button";
21020
+ const icon = make("span", "empty-start-action-icon", symbol);
21021
+ icon.setAttribute("aria-hidden", "true");
21022
+ const copy = make("span", "empty-start-action-copy");
21023
+ copy.append(make("strong", undefined, title), make("span", undefined, description));
21024
+ const arrow = make("span", "empty-start-action-arrow", "→");
21025
+ arrow.setAttribute("aria-hidden", "true");
21026
+ button.append(icon, copy, arrow);
21027
+ button.addEventListener("click", () => onClick(button));
21028
+ return button;
21029
+ }
21030
+
21031
+ function renderEmptyStartState() {
21032
+ if (elements.chat.querySelector(".empty-start-state")) return;
21033
+ const tab = activeTab();
21034
+ const workspace = latestWorkspace?.displayCwd || (tab?.cwd ? normalizeDisplayPath(tab.cwd) : "");
21035
+ const workspaceInfo = normalizeGitWorkspaceInfo(tab?.gitWorkspace);
21036
+ const branch = workspaceInfo?.branch || "";
21037
+ const model = currentState?.model ? shortModelLabel(currentState.model) : "";
21038
+ const usage = contextUsageDisplay();
21039
+ const card = make("section", "empty-start-state");
21040
+ card.setAttribute("aria-labelledby", "emptyStartTitle");
21041
+
21042
+ const intro = make("header", "empty-start-intro");
21043
+ const mark = make("span", "empty-start-mark", "π");
21044
+ mark.setAttribute("aria-hidden", "true");
21045
+ const heading = make("div", "empty-start-heading");
21046
+ const title = make("h1", undefined, "Choose where to work");
21047
+ title.id = "emptyStartTitle";
21048
+ heading.append(title, make("p", undefined, "Open a workspace, return to a session, or isolate branch work. To start here, just type below."));
21049
+ intro.append(mark, heading);
21050
+
21051
+ const actions = make("div", "empty-start-actions");
21052
+ actions.append(
21053
+ emptyStartAction({
21054
+ title: "Open workspace",
21055
+ description: "Choose a folder for a new Pi tab",
21056
+ symbol: "+",
21057
+ className: "primary",
21058
+ onClick: (button) => createTerminalTabFromChosenDirectory({ triggerButton: button }),
21059
+ }),
21060
+ emptyStartAction({
21061
+ title: "Resume session",
21062
+ description: "Continue previous work and context",
21063
+ symbol: "↶",
21064
+ onClick: () => runNativeCommandMenu("/resume"),
21065
+ }),
21066
+ emptyStartAction({
21067
+ title: "Branch worktree",
21068
+ description: "Work on a branch in an isolated checkout",
21069
+ symbol: "⑂",
21070
+ className: "worktree",
21071
+ onClick: () => openBranchWorktreePicker(),
21072
+ }),
21073
+ );
21074
+
21075
+ const recentWorkspaces = emptyStartRecentWorkspaces();
21076
+ const recent = recentWorkspaces.length ? make("section", "empty-start-recent") : null;
21077
+ if (recent) {
21078
+ const recentHeading = make("div", "empty-start-section-heading");
21079
+ recentHeading.append(make("strong", undefined, "Recent workspaces"), make("span", undefined, `${recentWorkspaces.length} available`));
21080
+ const recentList = make("div", "empty-start-recent-list");
21081
+ for (const item of recentWorkspaces) {
21082
+ const button = make("button", "empty-start-recent-item");
21083
+ button.type = "button";
21084
+ button.title = `Open ${item.cwd}`;
21085
+ button.append(make("span", "empty-start-recent-icon", "▰"), make("span", "empty-start-recent-path", item.label), make("span", "empty-start-recent-arrow", "→"));
21086
+ button.addEventListener("click", () => createTerminalTab(item.cwd, { triggerButton: button }));
21087
+ recentList.append(button);
21088
+ }
21089
+ recent.append(recentHeading, recentList);
21090
+ }
21091
+
21092
+ const contextItems = [];
21093
+ if (workspace) contextItems.push(["Workspace", workspace]);
21094
+ if (branch) contextItems.push(["Branch", branch]);
21095
+ if (model) contextItems.push(["Model", model]);
21096
+ if (usage && !/^0(?:\.0+)?%/.test(usage)) contextItems.push(["Context", usage]);
21097
+ const context = contextItems.length ? make("footer", "empty-start-context") : null;
21098
+ if (context) {
21099
+ context.append(make("span", "empty-start-context-label", "Current"));
21100
+ for (const [label, value] of contextItems) {
21101
+ const item = make("span", "empty-start-context-item");
21102
+ item.append(make("span", undefined, label), make("strong", undefined, value));
21103
+ context.append(item);
21104
+ }
21105
+ }
21106
+
21107
+ card.append(intro, actions);
21108
+ if (recent) card.append(recent);
21109
+ if (context) card.append(context);
21110
+ appendChatMessageBubble(card);
21111
+ if (elements.workspaceDashboard) elements.workspaceDashboard.hidden = true;
21112
+ }
21113
+
19971
21114
  function userPromptTargets() {
19972
21115
  return [...elements.chat.querySelectorAll('.message[data-user-prompt="true"][data-message-index]')]
19973
21116
  .map((node) => {
@@ -20500,7 +21643,14 @@ function liveToolRunMessage(run) {
20500
21643
  };
20501
21644
  }
20502
21645
 
21646
+ function applyChatEventMetadata(bubble, message) {
21647
+ const timestamp = messageTimestampMs(message);
21648
+ if (timestamp > 0) bubble.dataset.chatTimestamp = String(timestamp);
21649
+ else bubble.removeAttribute("data-chat-timestamp");
21650
+ }
21651
+
20503
21652
  function applyToolExecutionBubbleState(bubble, message) {
21653
+ applyChatEventMetadata(bubble, message);
20504
21654
  const status = toolExecutionStatus(message);
20505
21655
  const nextClass = `tool-${status}`;
20506
21656
  if (bubble.dataset.toolStatus !== status || !bubble.classList.contains(nextClass)) {
@@ -20712,15 +21862,11 @@ function jumpToStickyUserPrompt() {
20712
21862
  requestAnimationFrame(updateStickyUserPromptButton);
20713
21863
  }
20714
21864
 
20715
- function appendMessage(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, reusableToolCards = null, itemKey = "" } = {}) {
20716
- const reused = reuseToolExecutionBubble(reusableToolCards, message, { streaming, messageIndex, transient });
20717
- if (reused) {
20718
- if (itemKey) reused.bubble.dataset.itemKey = itemKey;
20719
- return reused;
20720
- }
21865
+ function createMessageBubble(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, itemKey = "" } = {}) {
20721
21866
  const role = String(message.role || "message");
20722
21867
  const safeRole = role.replace(/[^a-z0-9_-]/gi, "");
20723
21868
  const bubble = make("article", `message ${safeRole}${message.level ? ` ${message.level}` : ""}${streaming ? " streaming" : ""}${animateEntry ? " action-enter" : ""}`);
21869
+ applyChatEventMetadata(bubble, message);
20724
21870
  if (message.role === "toolExecution") applyToolExecutionBubbleState(bubble, message);
20725
21871
  if (!transient && messageIndex >= 0) {
20726
21872
  bubble.dataset.messageIndex = String(messageIndex);
@@ -20775,10 +21921,27 @@ function appendMessage(message, { streaming = false, messageIndex = -1, transien
20775
21921
  attachMessageCopyButton(bubble, message, body);
20776
21922
  attachMessageEditRetryButton(bubble, message, messageIndex, { streaming, transient });
20777
21923
  if (!streaming && !transient) renderActionFeedbackControls(bubble, message, messageIndex);
20778
- appendChatMessageBubble(bubble);
20779
21924
  return { bubble, body };
20780
21925
  }
20781
21926
 
21927
+ function appendMessage(message, options = {}) {
21928
+ const {
21929
+ streaming = false,
21930
+ messageIndex = -1,
21931
+ transient = false,
21932
+ reusableToolCards = null,
21933
+ itemKey = "",
21934
+ } = options;
21935
+ const reused = reuseToolExecutionBubble(reusableToolCards, message, { streaming, messageIndex, transient });
21936
+ if (reused) {
21937
+ if (itemKey) reused.bubble.dataset.itemKey = itemKey;
21938
+ return reused;
21939
+ }
21940
+ const created = createMessageBubble(message, options);
21941
+ appendChatMessageBubble(created.bubble);
21942
+ return created;
21943
+ }
21944
+
20782
21945
  function appendTranscriptMessage(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, reusableToolCards = null, itemKey = "" } = {}) {
20783
21946
  if (streaming || transient || message?.role !== "assistant") {
20784
21947
  return appendMessage(message, { streaming, messageIndex, transient, animateEntry, reusableToolCards, itemKey });
@@ -21264,6 +22427,8 @@ function renderAllMessages({ preserveScroll = false, forceRebuild = false } = {}
21264
22427
  });
21265
22428
  }
21266
22429
  pruneDisconnectedLiveToolCards();
22430
+ if (nextEntries.length === 0 && !runIndicatorIsActive()) renderEmptyStartState();
22431
+ else if (elements.workspaceDashboard) elements.workspaceDashboard.hidden = workspaceDashboardCollapsed;
21267
22432
  renderedTranscriptState = { epoch, entries: nextEntries.map(({ key, sig }) => ({ key, sig })) };
21268
22433
  rememberActionEntries(transcriptItems);
21269
22434
  applyToolOutputExpansionToDom();
@@ -21300,7 +22465,7 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
21300
22465
  });
21301
22466
  }
21302
22467
 
21303
- if (data.download && handleNativeDownloadResponse(data.download, data.command)) {
22468
+ if (data.download && handleNativeDownloadResponse(data.download, data.command, data.serverPath)) {
21304
22469
  addEvent(data.command === "export" ? `export ready: ${data.download.fileName || data.download.url}` : `download started: ${data.download.fileName || data.download.url}`, "info");
21305
22470
  }
21306
22471
 
@@ -21772,7 +22937,7 @@ function updateOptionalFeatureAvailability() {
21772
22937
  optionalFeatureAvailability.releaseNpm = hasAvailableCommand("release-npm");
21773
22938
  optionalFeatureAvailability.releaseAur = hasAvailableCommand("release-aur");
21774
22939
  optionalFeatureAvailability.workflows = hasAvailableCommand("workflow") || hasAvailableCommand("workflow-clear") || optionalFeatureAvailability.workflows || widgets.has("workflow") || widgets.has("workflow:subprocess");
21775
- optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
22940
+ optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || hasAvailableCommand("safety-guard-setup") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
21776
22941
  optionalFeatureAvailability.statsCommand = hasAvailableCommand("stats");
21777
22942
  optionalFeatureAvailability.gitFooterStatus = hasAvailableCommand("git-footer-refresh") || hasAvailableCommand("git-footer-visibility") || optionalFeatureAvailability.gitFooterStatus || statusEntries.has("git-footer") || statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY);
21778
22943
  optionalFeatureAvailability.tuiSkillsCommand = hasLoadedRpcCommand("skills");
@@ -21846,7 +23011,7 @@ function optionalFeatureWidgetFeatureId(key) {
21846
23011
  }
21847
23012
 
21848
23013
  function optionalFeatureWidgetHasSpecializedRenderer(key) {
21849
- return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === "workflow:subprocess";
23014
+ return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === "workflow:subprocess" || key === WORKFLOW_INSPECTOR_WIDGET_KEY;
21850
23015
  }
21851
23016
 
21852
23017
  function renderOptionalFeaturePanel() {
@@ -21961,7 +23126,15 @@ function renderOptionalFeatureRow(feature) {
21961
23126
  action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
21962
23127
  } else if (detected) {
21963
23128
  action.textContent = enabled ? "Disable" : "Enable";
21964
- action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, enabled));
23129
+ action.addEventListener("click", () => {
23130
+ const disabled = enabled;
23131
+ setOptionalFeatureDisabled(feature.id, disabled);
23132
+ offerUndo({
23133
+ message: `${feature.label} was ${disabled ? "disabled" : "enabled"}.`,
23134
+ undo: () => setOptionalFeatureDisabled(feature.id, !disabled),
23135
+ successMessage: `${feature.label} was ${disabled ? "re-enabled" : "disabled again"}.`,
23136
+ });
23137
+ });
21965
23138
  } else if (packageStatus?.installed) {
21966
23139
  action.textContent = "Reload";
21967
23140
  action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
@@ -22027,6 +23200,16 @@ function renderOptionalFeatureControls() {
22027
23200
  );
22028
23201
  if (!hasNativeCommandMenu && nativeCommandMenuOpen) setNativeCommandMenuOpen(false);
22029
23202
 
23203
+ const hasSafetyGuardSetup = isOptionalFeatureEnabled("safetyGuard") && hasAvailableCommand("safety-guard-setup");
23204
+ if (elements.optionsSafetyGuardSetupButton) {
23205
+ elements.optionsSafetyGuardSetupButton.hidden = !hasSafetyGuardSetup;
23206
+ setOptionalControlState(
23207
+ elements.optionsSafetyGuardSetupButton,
23208
+ hasSafetyGuardSetup,
23209
+ commandUnavailableMessage("safety-guard-setup"),
23210
+ );
23211
+ }
23212
+
22030
23213
  const hasStatsCommand = isOptionalFeatureEnabled("statsCommand");
22031
23214
  if (elements.optionsStatsButton) {
22032
23215
  elements.optionsStatsButton.hidden = !hasStatsCommand;
@@ -22052,6 +23235,7 @@ function renderOptionalFeatureControls() {
22052
23235
  elements.optionsConversationModeButton.hidden = !hasNaturalConversation;
22053
23236
  }
22054
23237
  renderConversationModeControls();
23238
+ renderWorkflowModeControls();
22055
23239
 
22056
23240
  const hasRemoteWebuiCommand = isOptionalFeatureEnabled("remoteWebui") && hasAvailableCommand("remote");
22057
23241
  if (elements.optionsRemoteButton) {
@@ -22071,9 +23255,9 @@ function syncRemoteWebuiControlVisibility(hasRemoteWebuiCommand = isOptionalFeat
22071
23255
  if (!elements.networkControlField) return;
22072
23256
  elements.networkControlField.hidden = !hasRemoteWebuiCommand;
22073
23257
  elements.networkControlField.classList.toggle("feature-unavailable", !hasRemoteWebuiCommand);
22074
- const label = elements.networkControlField.querySelector("label");
23258
+ const heading = elements.networkControlField.querySelector("#remoteAccessControlsTitle");
22075
23259
  const payload = remoteWebuiControlsPayload();
22076
- if (label) label.textContent = payload?.title || "Remote WebUI";
23260
+ if (heading) heading.textContent = payload?.title || "Remote access";
22077
23261
  elements.networkControlField.title = hasRemoteWebuiCommand
22078
23262
  ? payload?.description || "Remote WebUI controls are provided by @firstpick/pi-package-remote-webui."
22079
23263
  : optionalFeatureUnavailableMessage("remoteWebui");
@@ -22100,7 +23284,7 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
22100
23284
  "",
22101
23285
  "Continue?",
22102
23286
  ].join("\n");
22103
- if (!confirm(warning)) return;
23287
+ if (!(await appConfirmText(warning, { affected: feature.packageName, confirmLabel: update ? "Update feature" : "Install feature" }))) return;
22104
23288
 
22105
23289
  const startedAt = Date.now();
22106
23290
  optionalFeatureInstallInProgress.add(featureId);
@@ -22156,7 +23340,7 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
22156
23340
  hint: "Use Reload if this row still says Installed instead of Enabled.",
22157
23341
  command,
22158
23342
  });
22159
- if (confirm(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to enable newly loaded resources?`)) {
23343
+ 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 })) {
22160
23344
  sendPrompt("prompt", "/reload");
22161
23345
  } else {
22162
23346
  const tabContext = activeTabContext();
@@ -22249,9 +23433,24 @@ function openNativeCommandDialog({ title, message = "", searchPlaceholder = "" }
22249
23433
  if (searchPlaceholder) queueMicrotask(() => elements.nativeCommandSearch.focus());
22250
23434
  }
22251
23435
 
22252
- function closeNativeCommandDialog() {
23436
+ function closeNativeCommandDialog({ force = false } = {}) {
23437
+ if (nativeSettingsDirty && !force) {
23438
+ appConfirm({
23439
+ title: "Discard unsaved settings?",
23440
+ summary: "Your changes have not been applied.",
23441
+ affected: "All changed fields in this settings window",
23442
+ undoable: false,
23443
+ confirmLabel: "Discard changes",
23444
+ }).then((confirmed) => {
23445
+ if (!confirmed) return;
23446
+ nativeSettingsDirty = false;
23447
+ closeNativeCommandDialog({ force: true });
23448
+ });
23449
+ return;
23450
+ }
22253
23451
  if (elements.nativeCommandDialog.open) elements.nativeCommandDialog.close();
22254
23452
  elements.nativeCommandSearch.oninput = null;
23453
+ nativeSettingsDirty = false;
22255
23454
  nativeCommandTabId = null;
22256
23455
  }
22257
23456
 
@@ -22419,8 +23618,18 @@ function nativeSettingsBadge(label, tone = "") {
22419
23618
 
22420
23619
  function normalizedSettingsBadge(badge) {
22421
23620
  if (!badge) return null;
22422
- if (typeof badge === "string") return { label: badge, tone: "" };
22423
- return badge;
23621
+ const normalized = typeof badge === "string" ? { label: badge, tone: "" } : { ...badge };
23622
+ const scopeLabels = {
23623
+ now: "This tab",
23624
+ browser: "This browser",
23625
+ reload: "Global · reload",
23626
+ TUI: "Native TUI",
23627
+ tui: "Native TUI",
23628
+ startup: "Global · next start",
23629
+ safety: "Global",
23630
+ };
23631
+ normalized.label = scopeLabels[normalized.label] || normalized.label;
23632
+ return normalized;
22424
23633
  }
22425
23634
 
22426
23635
  function nativeSettingsLabelRow(label, badge) {
@@ -22533,7 +23742,7 @@ function nativeSettingsChangedMessage(response, reloadRequested) {
22533
23742
  }
22534
23743
 
22535
23744
  async function openNativeSettingsDialog() {
22536
- openNativeCommandDialog({ title: "/settings", message: "Pi settings for this Web UI tab. Badges show whether changes apply now, in the browser, or after reloading the tab." });
23745
+ openNativeCommandDialog({ title: "/settings", message: "Settings show their scope in plain language. Apply reloads the active tab only when a changed global field requires it." });
22537
23746
  renderNativeLoading("Loading settings…");
22538
23747
  let settingsData;
22539
23748
  try {
@@ -22566,6 +23775,10 @@ async function openNativeSettingsDialog() {
22566
23775
  { value: "followUp", label: "follow-up" },
22567
23776
  { value: "steer", label: "steer" },
22568
23777
  ], "When you submit a normal prompt while a tab is already busy.", { label: "browser", tone: "browser" }),
23778
+ density: nativeSettingSelect("Interface density", interfaceDensity, [
23779
+ { value: "comfortable", label: "Comfortable" },
23780
+ { value: "compact", label: "Compact" },
23781
+ ], "Compact reduces spacing while preserving the 12 px text floor.", { label: "browser", tone: "browser" }),
22569
23782
  thinkingOutput: nativeSettingToggle("Show thinking output", settings.hideThinkingBlock !== true, "Browser transcript visibility; also writes Pi's hide-thinking setting.", { label: "browser", tone: "browser" }),
22570
23783
  doneNotifications: nativeSettingToggle("Agent done notifications", agentDoneNotificationsEnabled, "Browser notification after background tab work completes.", { label: "browser", tone: "browser" }),
22571
23784
  autocompleteMax: nativeSettingSelect("Autocomplete max items", settings.autocompleteMaxVisible ?? autocompleteMaxVisible, SETTINGS_AUTOCOMPLETE_OPTIONS, "Maximum visible slash/path suggestions.", { label: "browser", tone: "browser" }),
@@ -22586,11 +23799,47 @@ async function openNativeSettingsDialog() {
22586
23799
  terminalProgress: nativeSettingToggle("Terminal progress", settings.showTerminalProgress === true, "Native TUI OSC 9;4 terminal progress indicators.", { label: "TUI", tone: "tui" }),
22587
23800
  };
22588
23801
 
23802
+ const remoteAccessSection = make("details", "native-settings-section native-settings-remote-access");
23803
+ remoteAccessSection.open = false;
23804
+ remoteAccessSection.append(make("summary", "native-settings-section-summary", "Remote access"));
23805
+ const remoteAccessBody = make("div", "native-settings-grid");
23806
+ const renderRemoteAccessSettings = () => {
23807
+ const open = !!latestNetwork?.open;
23808
+ const auth = latestNetwork?.auth || {};
23809
+ const status = make("div", `native-settings-note ${open ? "warning" : ""}`.trim());
23810
+ status.append(
23811
+ make("strong", undefined, open ? "Open to the network" : "Closed · local only"),
23812
+ make("span", undefined, `${open ? "Listener is reachable from the network." : "Only this machine can connect."} ${auth.enabled ? "Remote PIN authentication is enabled." : "Remote PIN authentication is disabled."}`),
23813
+ );
23814
+ const actions = make("div", "native-settings-remote-actions");
23815
+ const listenerButton = make("button", open ? "danger" : "", open ? "Close remote access" : "Open for remote access");
23816
+ listenerButton.type = "button";
23817
+ listenerButton.addEventListener("click", async () => {
23818
+ await openToNetwork();
23819
+ renderRemoteAccessSettings();
23820
+ });
23821
+ const authButton = make("button", undefined, auth.enabled ? "Disable remote PIN auth" : "Enable remote PIN auth");
23822
+ authButton.type = "button";
23823
+ authButton.addEventListener("click", async () => {
23824
+ await toggleRemoteAuth();
23825
+ renderRemoteAccessSettings();
23826
+ });
23827
+ const qrButton = make("button", undefined, "Show QR code");
23828
+ qrButton.type = "button";
23829
+ qrButton.hidden = !open;
23830
+ qrButton.addEventListener("click", () => showRemoteWebuiQrPopupFromNetwork().catch((error) => addEvent(error.message || String(error), "error")));
23831
+ actions.append(listenerButton, authButton, qrButton);
23832
+ remoteAccessBody.replaceChildren(status, actions);
23833
+ };
23834
+ renderRemoteAccessSettings();
23835
+ remoteAccessSection.append(remoteAccessBody);
23836
+
22589
23837
  const body = make("div", "native-settings-panel");
22590
23838
  body.append(
22591
- nativeSettingsNote("Scopes", "Runtime settings apply to the active tab. Reload-badged settings are saved globally and need a tab reload for the running Pi process."),
23839
+ nativeSettingsNote("Scopes", "Each field says whether it affects this tab, this browser, global Pi settings, or the native TUI."),
23840
+ remoteAccessSection,
22592
23841
  nativeSettingsSection("Runtime", "Model behavior and request transport.", [controls.thinking, controls.autoCompact, controls.steering, controls.followUp, controls.transport, controls.httpIdleTimeout], { open: true }),
22593
- nativeSettingsSection("Browser workflow", "Local Web UI behavior plus shared composer defaults.", [controls.busyBehavior, controls.thinkingOutput, controls.doneNotifications, controls.autocompleteMax, controls.doubleEscape, controls.treeFilter], { open: true }),
23842
+ nativeSettingsSection("Browser workflow", "Local Web UI behavior plus shared composer defaults.", [controls.busyBehavior, controls.density, controls.thinkingOutput, controls.doneNotifications, controls.autocompleteMax, controls.doubleEscape, controls.treeFilter], { open: true }),
22594
23843
  nativeSettingsSection("Images", "Provider image policy and native terminal image display.", [controls.autoResizeImages, controls.blockImages, controls.showImages, controls.imageWidth], { open: true }),
22595
23844
  nativeSettingsSection("Startup & safety", "Command registration, warnings, update/startup behavior.", [controls.skillCommands, controls.anthropicWarning, controls.collapseChangelog, controls.quietStartup, controls.installTelemetry], { open: false }),
22596
23845
  nativeSettingsSection("Native TUI advanced", "Saved for the terminal UI; mostly informational in the browser.", [controls.hardwareCursor, controls.editorPadding, controls.clearOnShrink, controls.terminalProgress], { open: false })
@@ -22599,10 +23848,46 @@ async function openNativeSettingsDialog() {
22599
23848
  elements.nativeCommandActions.replaceChildren();
22600
23849
  addNativeCommandAction("Model…", () => openNativeModelSelector());
22601
23850
  addNativeCommandAction("Theme…", () => openNativeThemeSelector());
22602
- addNativeCommandAction("Cancel", closeNativeCommandDialog);
23851
+ addNativeCommandAction("Cancel", () => closeNativeCommandDialog());
23852
+
23853
+ const initialPayload = collectNativeSettingsPayload(controls);
23854
+ const initialRuntime = JSON.stringify({
23855
+ thinking: state.thinkingLevel || "off",
23856
+ autoCompact: state.autoCompactionEnabled !== false,
23857
+ steering: state.steeringMode || "one-at-a-time",
23858
+ followUp: state.followUpMode || "one-at-a-time",
23859
+ busyBehavior,
23860
+ density: interfaceDensity,
23861
+ doneNotifications: agentDoneNotificationsEnabled,
23862
+ });
23863
+ const reloadKeys = new Set(["transport", "httpIdleTimeoutMs", "autoResizeImages", "blockImages", "enableSkillCommands"]);
23864
+ const reloadNeeded = () => {
23865
+ const payload = collectNativeSettingsPayload(controls);
23866
+ return [...reloadKeys].some((key) => JSON.stringify(payload[key]) !== JSON.stringify(initialPayload[key]));
23867
+ };
23868
+ const currentRuntime = () => JSON.stringify({
23869
+ thinking: controls.thinking.select.value,
23870
+ autoCompact: controls.autoCompact.input.checked,
23871
+ steering: controls.steering.select.value,
23872
+ followUp: controls.followUp.select.value,
23873
+ busyBehavior: controls.busyBehavior.select.value,
23874
+ density: controls.density.select.value,
23875
+ doneNotifications: controls.doneNotifications.input.checked,
23876
+ });
23877
+ let applyButton;
23878
+ const updateDirtyState = () => {
23879
+ nativeSettingsDirty = currentRuntime() !== initialRuntime || JSON.stringify(collectNativeSettingsPayload(controls)) !== JSON.stringify(initialPayload);
23880
+ if (applyButton) {
23881
+ applyButton.disabled = !nativeSettingsDirty;
23882
+ applyButton.textContent = reloadNeeded() ? "Apply and reload" : "Apply";
23883
+ }
23884
+ };
23885
+ body.addEventListener("input", updateDirtyState);
23886
+ body.addEventListener("change", updateDirtyState);
22603
23887
 
22604
- const applySettings = async (reload, button) => {
22605
- setNativeActionBusy(button, true, reload ? "Applying & reloading…" : "Applying…");
23888
+ const applySettings = async (button) => {
23889
+ const reload = reloadNeeded();
23890
+ setNativeActionBusy(button, true, reload ? "Applying and reloading…" : "Applying…");
22606
23891
  setNativeCommandError("");
22607
23892
  try {
22608
23893
  const requests = [];
@@ -22612,15 +23897,18 @@ async function openNativeSettingsDialog() {
22612
23897
  if (controls.followUp.select.value !== (state.followUpMode || "one-at-a-time")) requests.push(nativeCommandApi("/api/follow-up-mode", { method: "POST", body: { mode: controls.followUp.select.value } }));
22613
23898
  if (controls.autoCompact.input.checked !== (state.autoCompactionEnabled !== false)) requests.push(nativeCommandApi("/api/auto-compaction", { method: "POST", body: { enabled: controls.autoCompact.input.checked } }));
22614
23899
  setBusyPromptBehavior(controls.busyBehavior.select.value);
23900
+ setInterfaceDensity(controls.density.select.value);
22615
23901
  if (controls.thinkingOutput.input.checked !== thinkingOutputVisible) setThinkingOutputVisible(controls.thinkingOutput.input.checked);
22616
23902
  if (controls.doneNotifications.input.checked !== agentDoneNotificationsEnabled) await setAgentDoneNotificationsEnabled(controls.doneNotifications.input.checked);
22617
23903
  await Promise.all(requests);
22618
- const response = await nativeCommandApi("/api/settings", { method: "POST", body: { settings: collectNativeSettingsPayload(controls), reload } });
23904
+ const payload = collectNativeSettingsPayload(controls);
23905
+ const response = await nativeCommandApi("/api/settings", { method: "POST", body: { settings: payload, reload } });
22619
23906
  applyResponseTab(response);
22620
- applyNativeSettingsForBrowser(response.data?.settings || collectNativeSettingsPayload(controls));
23907
+ applyNativeSettingsForBrowser(response.data?.settings || payload);
22621
23908
  if (thinkingLevelChanged) requestGitFooterWebuiPayload(activeTabContext(), { force: true });
22622
23909
  addTransientMessage({ role: "native", title: "/settings", content: nativeSettingsChangedMessage(response, reload), level: response.data?.reloadRecommended?.length && !response.data?.reloaded ? "warn" : "info" });
22623
- closeNativeCommandDialog();
23910
+ nativeSettingsDirty = false;
23911
+ closeNativeCommandDialog({ force: true });
22624
23912
  await refreshAll();
22625
23913
  } catch (error) {
22626
23914
  setNativeCommandError(error.message || String(error));
@@ -22629,8 +23917,8 @@ async function openNativeSettingsDialog() {
22629
23917
  }
22630
23918
  };
22631
23919
 
22632
- const reloadButton = addNativeCommandAction("Apply & reload tab", () => applySettings(true, reloadButton));
22633
- const save = addNativeCommandAction("Apply", () => applySettings(false, save), "primary");
23920
+ applyButton = addNativeCommandAction("Apply", () => applySettings(applyButton), "primary");
23921
+ updateDirtyState();
22634
23922
  }
22635
23923
 
22636
23924
  function replaceNativeSettingSelectOptions(select, options, preferredValue) {
@@ -22645,6 +23933,124 @@ function replaceNativeSettingSelectOptions(select, options, preferredValue) {
22645
23933
  select.value = values.includes(String(preferredValue)) ? String(preferredValue) : values[0] || "";
22646
23934
  }
22647
23935
 
23936
+ const SAFETY_GUARD_CATEGORY_LABELS = Object.freeze({
23937
+ git: "Git history and destructive operations",
23938
+ filesystem: "Filesystem deletion and overwrite",
23939
+ docker: "Docker and Podman destruction",
23940
+ package: "Package removal",
23941
+ system: "System state and permissions",
23942
+ database: "Dangerous SQL",
23943
+ secrets: "Secret file access",
23944
+ });
23945
+
23946
+ async function openNativeSafetyGuardSetupDialog() {
23947
+ openNativeCommandDialog({
23948
+ title: "/safety-guard-setup",
23949
+ message: "Configure persistent command categories, protected-path checks, and the context shown around dangerous matches.",
23950
+ });
23951
+ renderNativeLoading("Loading safety guard setup…");
23952
+
23953
+ let data;
23954
+ try {
23955
+ const response = await nativeCommandApi("/api/safety-guard/config");
23956
+ data = response.data || {};
23957
+ } catch (error) {
23958
+ setNativeCommandError(error.message || String(error));
23959
+ elements.nativeCommandBody.replaceChildren();
23960
+ return;
23961
+ }
23962
+
23963
+ const config = data.config || {};
23964
+ const defaults = data.defaults || {};
23965
+ const categories = Array.isArray(data.categories) && data.categories.length
23966
+ ? data.categories
23967
+ : Object.keys(SAFETY_GUARD_CATEGORY_LABELS);
23968
+ const minimumContext = Number.isInteger(data.contextLines?.min) ? data.contextLines.min : 0;
23969
+ const maximumContext = Number.isInteger(data.contextLines?.max) ? data.contextLines.max : 20;
23970
+ const contextOptions = Array.from(
23971
+ { length: Math.max(1, maximumContext - minimumContext + 1) },
23972
+ (_, index) => String(index + minimumContext),
23973
+ );
23974
+ const categoryControls = Object.fromEntries(categories.map((category) => [
23975
+ category,
23976
+ nativeSettingToggle(
23977
+ SAFETY_GUARD_CATEGORY_LABELS[category] || category,
23978
+ config.categories?.[category] !== false,
23979
+ `Prompt when a command matches the ${category} guard category.`,
23980
+ { label: category, tone: "safety" },
23981
+ ),
23982
+ ]));
23983
+ const controls = {
23984
+ enabled: nativeSettingToggle("Safety guard enabled", config.enabled !== false, "Master switch for command and protected-path guards.", { label: "global", tone: "safety" }),
23985
+ before: nativeSettingSelect("Lines before a match", config.contextLines?.before ?? 3, contextOptions, "Number of command lines shown before each matched line.", { label: "preview", tone: "browser" }),
23986
+ after: nativeSettingSelect("Lines after a match", config.contextLines?.after ?? 3, contextOptions, "Number of command lines shown after each matched line.", { label: "preview", tone: "browser" }),
23987
+ protectedWrite: nativeSettingToggle("Guard protected-path writes", config.protectedPaths?.write !== false, "Prompt before write calls target credentials, private keys, or environment files.", { label: "write", tone: "safety" }),
23988
+ protectedEdit: nativeSettingToggle("Guard protected-path edits", config.protectedPaths?.edit !== false, "Prompt before edit calls target credentials, private keys, or environment files.", { label: "edit", tone: "safety" }),
23989
+ };
23990
+
23991
+ const collectConfig = () => ({
23992
+ version: data.version || 1,
23993
+ enabled: controls.enabled.input.checked,
23994
+ categories: Object.fromEntries(categories.map((category) => [category, categoryControls[category].input.checked])),
23995
+ protectedPaths: {
23996
+ write: controls.protectedWrite.input.checked,
23997
+ edit: controls.protectedEdit.input.checked,
23998
+ },
23999
+ contextLines: {
24000
+ before: Number.parseInt(controls.before.select.value, 10),
24001
+ after: Number.parseInt(controls.after.select.value, 10),
24002
+ },
24003
+ });
24004
+ const applyConfig = (value) => {
24005
+ controls.enabled.input.checked = value?.enabled !== false;
24006
+ controls.before.select.value = String(value?.contextLines?.before ?? 3);
24007
+ controls.after.select.value = String(value?.contextLines?.after ?? 3);
24008
+ controls.protectedWrite.input.checked = value?.protectedPaths?.write !== false;
24009
+ controls.protectedEdit.input.checked = value?.protectedPaths?.edit !== false;
24010
+ for (const category of categories) categoryControls[category].input.checked = value?.categories?.[category] !== false;
24011
+ };
24012
+
24013
+ const body = make("div", "native-settings-panel");
24014
+ body.append(
24015
+ nativeSettingsNote("Persistence", `Saved globally in ${data.path || "~/.pi/agent/safety-guard.json"}. Changes are reloaded before guard checks.`),
24016
+ nativeSettingsSection("General", "Enable or disable all guard behavior.", [controls.enabled], { open: true }),
24017
+ nativeSettingsSection("Command preview", "Choose independent context limits before and after each dangerous matched line.", [controls.before, controls.after], { open: true }),
24018
+ nativeSettingsSection("Command categories", "Disable only categories you intentionally do not want guarded.", categories.map((category) => categoryControls[category]), { open: true }),
24019
+ nativeSettingsSection("Protected paths", "Control write/edit prompts for secret-bearing files and credential paths.", [controls.protectedWrite, controls.protectedEdit], { open: true }),
24020
+ );
24021
+ elements.nativeCommandBody.replaceChildren(body);
24022
+ elements.nativeCommandActions.replaceChildren();
24023
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
24024
+ addNativeCommandAction("Reset defaults", () => {
24025
+ applyConfig(defaults);
24026
+ setNativeCommandError("");
24027
+ });
24028
+
24029
+ const save = addNativeCommandAction("Save setup", async () => {
24030
+ setNativeActionBusy(save, true, "Saving…");
24031
+ setNativeCommandError("");
24032
+ try {
24033
+ const response = await nativeCommandApi("/api/safety-guard/config", {
24034
+ method: "POST",
24035
+ body: { config: collectConfig() },
24036
+ });
24037
+ const saved = response.data?.config || collectConfig();
24038
+ const activeCategories = categories.filter((category) => saved.categories?.[category]).length;
24039
+ addTransientMessage({
24040
+ role: "native",
24041
+ title: "/safety-guard-setup",
24042
+ content: `Safety guard ${saved.enabled ? "enabled" : "disabled"}; ${activeCategories}/${categories.length} command categories active; preview ${saved.contextLines?.before ?? 3} before and ${saved.contextLines?.after ?? 3} after.`,
24043
+ level: saved.enabled ? "info" : "warn",
24044
+ });
24045
+ closeNativeCommandDialog();
24046
+ } catch (error) {
24047
+ setNativeCommandError(error.message || String(error));
24048
+ } finally {
24049
+ setNativeActionBusy(save, false);
24050
+ }
24051
+ }, "primary");
24052
+ }
24053
+
22648
24054
  function gitWorkflowSetupModelKey(model) {
22649
24055
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
22650
24056
  }
@@ -23126,12 +24532,44 @@ function renderNativeResourceFilterActions(filter, setFilter, render) {
23126
24532
  addNativeCommandAction("Cancel", closeNativeCommandDialog);
23127
24533
  }
23128
24534
 
24535
+ function nativeResourceScopeControl(scope, { configured = false, saving = false, onChange } = {}) {
24536
+ const global = scope === "global";
24537
+ const hint = global
24538
+ ? configured
24539
+ ? "Saved as the default for future sessions. Existing session-specific choices are unchanged."
24540
+ : "No global default is saved yet. The current session is shown as the starting point."
24541
+ : "Applies immediately and persists only on the current session branch.";
24542
+ const control = nativeSettingSelect("Apply changes to", scope, [
24543
+ { value: "session", label: "Session only" },
24544
+ { value: "global", label: "Global default" },
24545
+ ], hint, global ? { label: "Global", tone: "startup" } : { label: "This session", tone: "now" });
24546
+ control.field.classList.add("native-resource-scope");
24547
+ control.select.disabled = !!saving;
24548
+ control.select.addEventListener("change", () => onChange?.(control.select.value));
24549
+ return control.field;
24550
+ }
24551
+
23129
24552
  async function openNativeToolsSelector() {
23130
- openNativeCommandDialog({ title: "Tools Setup", message: "Enable or disable tools for the active Pi tab. Changes apply to the next model turn and persist on this session branch.", searchPlaceholder: "Filter tools…" });
23131
- renderNativeLoading("Loading tools…");
24553
+ openNativeCommandDialog({ title: "Tools Setup", message: "Enable or disable tool access for this session or save a default for future sessions.", searchPlaceholder: "Filter tools…" });
23132
24554
  let tools = [];
23133
24555
  let savingName = "";
23134
24556
  let filter = "all";
24557
+ let scope = "session";
24558
+ let configured = false;
24559
+
24560
+ const load = async () => {
24561
+ renderNativeLoading(`Loading ${scope === "global" ? "global tool defaults" : "session tools"}…`);
24562
+ try {
24563
+ const response = await nativeCommandApi(`/api/tools?scope=${encodeURIComponent(scope)}`);
24564
+ tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
24565
+ configured = response.data?.configured === true;
24566
+ render();
24567
+ } catch (error) {
24568
+ setNativeCommandError(error.message || String(error));
24569
+ elements.nativeCommandBody.replaceChildren();
24570
+ }
24571
+ };
24572
+
23135
24573
  const render = () => {
23136
24574
  renderNativeResourceToggles(tools, {
23137
24575
  savingName,
@@ -23146,9 +24584,14 @@ async function openNativeToolsSelector() {
23146
24584
  setNativeCommandError("");
23147
24585
  render();
23148
24586
  try {
23149
- const response = await nativeCommandApi("/api/tools", { method: "POST", body: { enabledTools: [...enabledTools] } });
24587
+ const response = await nativeCommandApi("/api/tools", { method: "POST", body: { enabledTools: [...enabledTools], scope } });
23150
24588
  tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
23151
- addTransientMessage({ role: "native", title: "/tools", content: `Tool ${tool.name} ${enabledTools.has(tool.name) ? "enabled" : "disabled"}.`, level: "info" });
24589
+ configured = response.data?.configured === true;
24590
+ const enabled = enabledTools.has(tool.name);
24591
+ const content = scope === "global"
24592
+ ? `Global default for tool ${tool.name} ${enabled ? "enabled" : "disabled"}. Future sessions inherit it; this session is unchanged.`
24593
+ : `Tool ${tool.name} ${enabled ? "enabled" : "disabled"} for this session.`;
24594
+ addTransientMessage({ role: "native", title: "/tools", content, level: "info" });
23152
24595
  } catch (error) {
23153
24596
  setNativeCommandError(error.message || String(error));
23154
24597
  } finally {
@@ -23157,25 +24600,43 @@ async function openNativeToolsSelector() {
23157
24600
  }
23158
24601
  },
23159
24602
  });
24603
+ elements.nativeCommandBody.prepend(nativeResourceScopeControl(scope, {
24604
+ configured,
24605
+ saving: !!savingName,
24606
+ onChange: async (nextScope) => {
24607
+ if (nextScope === scope || savingName) return;
24608
+ scope = nextScope;
24609
+ await load();
24610
+ },
24611
+ }));
23160
24612
  renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render);
23161
24613
  };
23162
- try {
23163
- const response = await nativeCommandApi("/api/tools");
23164
- tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
23165
- elements.nativeCommandSearch.oninput = render;
23166
- render();
23167
- } catch (error) {
23168
- setNativeCommandError(error.message || String(error));
23169
- elements.nativeCommandBody.replaceChildren();
23170
- }
24614
+
24615
+ elements.nativeCommandSearch.oninput = render;
24616
+ await load();
23171
24617
  }
23172
24618
 
23173
24619
  async function openNativeSkillsSelector() {
23174
- openNativeCommandDialog({ title: "Skills Setup", message: "Enable or disable skills for automatic model invocation in the active Pi tab. Disabled skills are removed from the system prompt and their /skill:name commands are blocked by Web UI.", searchPlaceholder: "Filter skills…" });
23175
- renderNativeLoading("Loading skills…");
24620
+ openNativeCommandDialog({ title: "Skills Setup", message: "Enable or disable skill invocation for this session or save a default for future sessions.", searchPlaceholder: "Filter skills…" });
23176
24621
  let skills = [];
23177
24622
  let savingName = "";
23178
24623
  let filter = "all";
24624
+ let scope = "session";
24625
+ let configured = false;
24626
+
24627
+ const load = async () => {
24628
+ renderNativeLoading(`Loading ${scope === "global" ? "global skill defaults" : "session skills"}…`);
24629
+ try {
24630
+ const response = await nativeCommandApi(`/api/skills?scope=${encodeURIComponent(scope)}`);
24631
+ skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
24632
+ configured = response.data?.configured === true;
24633
+ render();
24634
+ } catch (error) {
24635
+ setNativeCommandError(error.message || String(error));
24636
+ elements.nativeCommandBody.replaceChildren();
24637
+ }
24638
+ };
24639
+
23179
24640
  const render = () => {
23180
24641
  renderNativeResourceToggles(skills, {
23181
24642
  savingName,
@@ -23189,10 +24650,15 @@ async function openNativeSkillsSelector() {
23189
24650
  setNativeCommandError("");
23190
24651
  render();
23191
24652
  try {
23192
- const response = await nativeCommandApi("/api/skills", { method: "POST", body: { enabledSkills: [...enabledSkills] } });
24653
+ const response = await nativeCommandApi("/api/skills", { method: "POST", body: { enabledSkills: [...enabledSkills], scope } });
23193
24654
  skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
23194
- addTransientMessage({ role: "native", title: "/skills", content: `Skill ${skill.name} ${enabledSkills.has(skill.name) ? "enabled" : "disabled"}.`, level: "info" });
23195
- refreshCommands(activeTabContext()).catch((error) => addEvent(error.message || String(error), "error"));
24655
+ configured = response.data?.configured === true;
24656
+ const enabled = enabledSkills.has(skill.name);
24657
+ const content = scope === "global"
24658
+ ? `Global default for skill ${skill.name} ${enabled ? "enabled" : "disabled"}. Future sessions inherit it; this session is unchanged.`
24659
+ : `Skill ${skill.name} ${enabled ? "enabled" : "disabled"} for this session.`;
24660
+ addTransientMessage({ role: "native", title: "/skills", content, level: "info" });
24661
+ if (scope === "session") refreshCommands(activeTabContext()).catch((error) => addEvent(error.message || String(error), "error"));
23196
24662
  } catch (error) {
23197
24663
  setNativeCommandError(error.message || String(error));
23198
24664
  } finally {
@@ -23201,17 +24667,20 @@ async function openNativeSkillsSelector() {
23201
24667
  }
23202
24668
  },
23203
24669
  });
24670
+ elements.nativeCommandBody.prepend(nativeResourceScopeControl(scope, {
24671
+ configured,
24672
+ saving: !!savingName,
24673
+ onChange: async (nextScope) => {
24674
+ if (nextScope === scope || savingName) return;
24675
+ scope = nextScope;
24676
+ await load();
24677
+ },
24678
+ }));
23204
24679
  renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render);
23205
24680
  };
23206
- try {
23207
- const response = await nativeCommandApi("/api/skills");
23208
- skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
23209
- elements.nativeCommandSearch.oninput = render;
23210
- render();
23211
- } catch (error) {
23212
- setNativeCommandError(error.message || String(error));
23213
- elements.nativeCommandBody.replaceChildren();
23214
- }
24681
+
24682
+ elements.nativeCommandSearch.oninput = render;
24683
+ await load();
23215
24684
  }
23216
24685
 
23217
24686
  async function openNativeAuthSelector(mode) {
@@ -23250,7 +24719,7 @@ async function openNativeAuthSelector(mode) {
23250
24719
  setNativeCommandError(`Run /login in the Pi TUI for ${item.label}. Browser login is not implemented yet.`);
23251
24720
  return;
23252
24721
  }
23253
- if (!window.confirm(`Remove stored credentials for ${item.label}?`)) return;
24722
+ if (!(await appConfirmText(`Remove stored credentials for ${item.label}?`, { affected: `${item.label} stored credentials`, confirmLabel: "Remove credentials" }))) return;
23254
24723
  setNativeCommandError("");
23255
24724
  try {
23256
24725
  const result = await nativeCommandApi("/api/auth-logout", {
@@ -23298,6 +24767,9 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
23298
24767
  case "settings":
23299
24768
  await openNativeSettingsDialog();
23300
24769
  return true;
24770
+ case "safety-guard-setup":
24771
+ await openNativeSafetyGuardSetupDialog();
24772
+ return true;
23301
24773
  case "git-workflow-setup":
23302
24774
  await openNativeGitWorkflowSetupDialog();
23303
24775
  return true;
@@ -23925,7 +25397,15 @@ function renderNetworkStatus() {
23925
25397
  : "On"
23926
25398
  : "Off";
23927
25399
  elements.openNetworkButton.disabled = rebinding;
23928
- elements.openNetworkButton.textContent = opening ? "Opening…" : closing ? "Closing…" : open ? "Close for network" : "Open to network";
25400
+ elements.openNetworkButton.textContent = opening ? "Opening…" : closing ? "Closing…" : open ? "Close remote access" : "Open for remote access";
25401
+ if (elements.remoteAccessIndicator) {
25402
+ elements.remoteAccessIndicator.hidden = !open;
25403
+ elements.remoteAccessIndicator.textContent = open ? "Remote access open" : "";
25404
+ elements.remoteAccessIndicator.title = open
25405
+ ? `Network listener exposed${networkUrls.length ? ` at ${networkUrls.join(", ")}` : ""} · ${auth.enabled ? "PIN auth on" : "PIN auth off"}`
25406
+ : "";
25407
+ }
25408
+ document.body.classList.toggle("remote-access-open", open);
23929
25409
  if (elements.showRemoteQrButton) {
23930
25410
  elements.showRemoteQrButton.hidden = !open;
23931
25411
  elements.showRemoteQrButton.disabled = rebinding || !open;
@@ -24450,10 +25930,17 @@ function cancelBangSuggestionRequest() {
24450
25930
  abortBangSuggestionRequest();
24451
25931
  }
24452
25932
 
25933
+ function showCommandSuggestionList() {
25934
+ elements.commandSuggest.hidden = false;
25935
+ elements.promptInput?.setAttribute("aria-expanded", "true");
25936
+ }
25937
+
24453
25938
  function hideCommandSuggestions() {
24454
25939
  cancelPathSuggestionRequest();
24455
25940
  cancelBangSuggestionRequest();
24456
25941
  elements.commandSuggest.hidden = true;
25942
+ elements.promptInput?.setAttribute("aria-expanded", "false");
25943
+ elements.promptInput?.removeAttribute("aria-activedescendant");
24457
25944
  elements.commandSuggest.removeAttribute("aria-busy");
24458
25945
  elements.commandSuggest.replaceChildren();
24459
25946
  commandSuggestions = [];
@@ -24473,7 +25960,10 @@ function setActiveCommandSuggestion(index) {
24473
25960
  const active = itemIndex === commandSuggestIndex;
24474
25961
  item.classList.toggle("active", active);
24475
25962
  item.setAttribute("aria-selected", active ? "true" : "false");
24476
- if (active) item.scrollIntoView({ block: "nearest" });
25963
+ if (active) {
25964
+ elements.promptInput?.setAttribute("aria-activedescendant", item.id);
25965
+ item.scrollIntoView({ block: "nearest" });
25966
+ }
24477
25967
  }
24478
25968
  }
24479
25969
 
@@ -24513,13 +26003,14 @@ function renderCommandSuggestionItems(trigger, { keepIndex = false } = {}) {
24513
26003
 
24514
26004
  if (commandSuggestions.length === 0) {
24515
26005
  elements.commandSuggest.append(make("div", "command-suggest-empty", `No command matches /${trigger.query}`));
24516
- elements.commandSuggest.hidden = false;
26006
+ showCommandSuggestionList();
24517
26007
  return;
24518
26008
  }
24519
26009
 
24520
26010
  for (const [index, command] of commandSuggestions.entries()) {
24521
26011
  const item = make("button", "command-suggest-item");
24522
26012
  item.type = "button";
26013
+ item.id = `composer-suggestion-command-${encodeURIComponent(command.name).replace(/%/g, "-")}`;
24523
26014
  item.setAttribute("role", "option");
24524
26015
  item.addEventListener("mousedown", (event) => event.preventDefault());
24525
26016
  item.addEventListener("pointermove", (event) => setActiveCommandSuggestionFromPointerMove(index, event));
@@ -24533,7 +26024,8 @@ function renderCommandSuggestionItems(trigger, { keepIndex = false } = {}) {
24533
26024
  elements.commandSuggest.append(item);
24534
26025
  }
24535
26026
 
24536
- elements.commandSuggest.hidden = false;
26027
+ showCommandSuggestionList();
26028
+ elements.promptInput?.setAttribute("aria-expanded", "true");
24537
26029
  setActiveCommandSuggestion(keepIndex ? commandSuggestIndex : 0);
24538
26030
  }
24539
26031
 
@@ -24555,7 +26047,7 @@ function renderPathSuggestionItems(trigger, { keepIndex = false } = {}) {
24555
26047
 
24556
26048
  if (pathSuggestions.length === 0) {
24557
26049
  elements.commandSuggest.append(make("div", "command-suggest-empty", `No path matches @${trigger.query}`));
24558
- elements.commandSuggest.hidden = false;
26050
+ showCommandSuggestionList();
24559
26051
  return;
24560
26052
  }
24561
26053
 
@@ -24563,6 +26055,7 @@ function renderPathSuggestionItems(trigger, { keepIndex = false } = {}) {
24563
26055
  const isDirectory = pathSuggestionIsDirectory(suggestion);
24564
26056
  const item = make("button", `command-suggest-item path-suggest-item ${isDirectory ? "directory" : "file"}`);
24565
26057
  item.type = "button";
26058
+ item.id = `composer-suggestion-path-${index}-${encodeURIComponent(suggestion.path).replace(/%/g, "-")}`;
24566
26059
  item.setAttribute("role", "option");
24567
26060
  item.addEventListener("mousedown", (event) => event.preventDefault());
24568
26061
  item.addEventListener("pointermove", (event) => setActiveCommandSuggestionFromPointerMove(index, event));
@@ -24576,7 +26069,7 @@ function renderPathSuggestionItems(trigger, { keepIndex = false } = {}) {
24576
26069
  elements.commandSuggest.append(item);
24577
26070
  }
24578
26071
 
24579
- elements.commandSuggest.hidden = false;
26072
+ showCommandSuggestionList();
24580
26073
  setActiveCommandSuggestion(keepIndex ? commandSuggestIndex : 0);
24581
26074
  }
24582
26075
 
@@ -24599,7 +26092,7 @@ async function renderPathSuggestions(trigger, { keepIndex = false } = {}) {
24599
26092
  pathSuggestions = [];
24600
26093
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", "Finding paths…"));
24601
26094
  }
24602
- elements.commandSuggest.hidden = false;
26095
+ showCommandSuggestionList();
24603
26096
  elements.commandSuggest.setAttribute("aria-busy", "true");
24604
26097
 
24605
26098
  try {
@@ -24611,7 +26104,7 @@ async function renderPathSuggestions(trigger, { keepIndex = false } = {}) {
24611
26104
  if (error?.name === "AbortError" || requestSerial !== pathSuggestRequestSerial) return;
24612
26105
  pathSuggestions = [];
24613
26106
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", `Path suggestions unavailable: ${error.message}`));
24614
- elements.commandSuggest.hidden = false;
26107
+ showCommandSuggestionList();
24615
26108
  } finally {
24616
26109
  if (requestSerial === pathSuggestRequestSerial) {
24617
26110
  pathSuggestAbortController = null;
@@ -24628,13 +26121,14 @@ function renderBangSuggestionItems(trigger, { keepIndex = false } = {}) {
24628
26121
 
24629
26122
  if (bangSuggestions.length === 0) {
24630
26123
  elements.commandSuggest.append(make("div", "command-suggest-empty", `No shell command matches !${trigger.query}`));
24631
- elements.commandSuggest.hidden = false;
26124
+ showCommandSuggestionList();
24632
26125
  return;
24633
26126
  }
24634
26127
 
24635
26128
  for (const [index, suggestion] of bangSuggestions.entries()) {
24636
26129
  const item = make("button", "command-suggest-item bang-suggest-item");
24637
26130
  item.type = "button";
26131
+ item.id = `composer-suggestion-bang-${index}-${encodeURIComponent(suggestion.insertText).replace(/%/g, "-")}`;
24638
26132
  item.setAttribute("role", "option");
24639
26133
  item.addEventListener("mousedown", (event) => event.preventDefault());
24640
26134
  item.addEventListener("pointermove", (event) => setActiveCommandSuggestionFromPointerMove(index, event));
@@ -24648,7 +26142,7 @@ function renderBangSuggestionItems(trigger, { keepIndex = false } = {}) {
24648
26142
  elements.commandSuggest.append(item);
24649
26143
  }
24650
26144
 
24651
- elements.commandSuggest.hidden = false;
26145
+ showCommandSuggestionList();
24652
26146
  setActiveCommandSuggestion(keepIndex ? commandSuggestIndex : 0);
24653
26147
  }
24654
26148
 
@@ -24673,7 +26167,7 @@ async function renderBangSuggestions(trigger, { keepIndex = false } = {}) {
24673
26167
  bangSuggestions = [];
24674
26168
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", "Finding shell commands…"));
24675
26169
  }
24676
- elements.commandSuggest.hidden = false;
26170
+ showCommandSuggestionList();
24677
26171
  elements.commandSuggest.setAttribute("aria-busy", "true");
24678
26172
 
24679
26173
  try {
@@ -24685,7 +26179,7 @@ async function renderBangSuggestions(trigger, { keepIndex = false } = {}) {
24685
26179
  if (error?.name === "AbortError" || requestSerial !== bangSuggestRequestSerial) return;
24686
26180
  bangSuggestions = [];
24687
26181
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", `Shell command suggestions unavailable: ${error.message}`));
24688
- elements.commandSuggest.hidden = false;
26182
+ showCommandSuggestionList();
24689
26183
  } finally {
24690
26184
  if (requestSerial === bangSuggestRequestSerial) {
24691
26185
  bangSuggestAbortController = null;
@@ -24952,12 +26446,14 @@ function renderCommandPaletteList({ preserveScroll = false } = {}) {
24952
26446
  list.replaceChildren();
24953
26447
  if (!commandPaletteItems.length) {
24954
26448
  list.append(make("div", "command-palette-empty muted", "No matching actions."));
26449
+ elements.commandPaletteInput?.removeAttribute("aria-activedescendant");
24955
26450
  if (preserveScroll) list.scrollTop = scrollTop;
24956
26451
  return;
24957
26452
  }
24958
26453
  commandPaletteItems.forEach((item, index) => {
24959
26454
  const button = make("button", `command-palette-item${index === commandPaletteIndex ? " active" : ""}`);
24960
26455
  button.type = "button";
26456
+ button.id = `command-palette-option-${encodeURIComponent(`${item.kind}-${item.label}`).replace(/%/g, "-")}`;
24961
26457
  button.setAttribute("role", "option");
24962
26458
  button.setAttribute("aria-selected", index === commandPaletteIndex ? "true" : "false");
24963
26459
  button.addEventListener("click", () => executeCommandPaletteItem(item));
@@ -24968,11 +26464,12 @@ function renderCommandPaletteList({ preserveScroll = false } = {}) {
24968
26464
  );
24969
26465
  list.append(button);
24970
26466
  });
26467
+ const active = list.children[commandPaletteIndex];
26468
+ if (active?.id) elements.commandPaletteInput?.setAttribute("aria-activedescendant", active.id);
24971
26469
  if (preserveScroll) {
24972
26470
  list.scrollTop = scrollTop;
24973
26471
  return;
24974
26472
  }
24975
- const active = list.children[commandPaletteIndex];
24976
26473
  active?.scrollIntoView({ block: "nearest" });
24977
26474
  }
24978
26475
 
@@ -25066,12 +26563,43 @@ function scheduleForegroundReconcile(reason = "resume", delay = FOREGROUND_RECON
25066
26563
 
25067
26564
  async function openToNetwork() {
25068
26565
  const open = !!latestNetwork?.open;
26566
+ if (!open) {
26567
+ const localUrl = latestNetwork?.localUrl || `${window.location.origin}/`;
26568
+ let interfaceName = "all network interfaces";
26569
+ let port = DEFAULT_WEBUI_PORT;
26570
+ try {
26571
+ const parsed = new URL(localUrl);
26572
+ port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
26573
+ } catch {
26574
+ // Keep explicit fallback values in the confirmation.
26575
+ }
26576
+ const confirmed = await appConfirm({
26577
+ title: "Open for remote access?",
26578
+ summary: "This changes Pi Web UI from local-only to reachable by devices on your network.",
26579
+ affected: `${interfaceName}, port ${port}, ${latestNetwork?.auth?.enabled ? "PIN authentication enabled" : "PIN authentication disabled"}`,
26580
+ undoable: true,
26581
+ confirmLabel: "Open remote access",
26582
+ });
26583
+ if (!confirmed) return;
26584
+ }
25069
26585
  elements.openNetworkButton.disabled = true;
25070
26586
  elements.openNetworkButton.textContent = open ? "Closing…" : "Opening…";
25071
26587
  try {
25072
26588
  await runRemoteWebuiCommand(remoteWebuiCommand(open ? "close" : "open", open ? "/remote close" : "/remote"));
25073
26589
  await delay(350);
25074
26590
  await refreshNetworkStatus();
26591
+ if (!open && latestNetwork?.open) {
26592
+ offerUndo({
26593
+ message: "Remote access is open.",
26594
+ undo: async () => {
26595
+ await runRemoteWebuiCommand(remoteWebuiCommand("close", "/remote close"));
26596
+ await delay(350);
26597
+ await refreshNetworkStatus();
26598
+ renderNetworkStatus();
26599
+ },
26600
+ successMessage: "Remote access closed; Pi Web UI is local-only again.",
26601
+ });
26602
+ }
25075
26603
  } catch (error) {
25076
26604
  addEvent(error.message || String(error), "error");
25077
26605
  } finally {
@@ -25144,7 +26672,13 @@ async function waitForServerRestart() {
25144
26672
  }
25145
26673
 
25146
26674
  async function restartServer() {
25147
- if (!confirm("Restart the Pi Web UI server?\n\nThis briefly disconnects browser clients and restarts the Pi tabs managed by this Web UI.")) return;
26675
+ if (!(await appConfirm({
26676
+ title: "Restart Pi Web UI server?",
26677
+ summary: "Browser clients disconnect briefly while the server restarts.",
26678
+ affected: "All connected browser clients and Pi tabs managed by this Web UI",
26679
+ undoable: false,
26680
+ confirmLabel: "Restart server",
26681
+ }))) return;
25148
26682
 
25149
26683
  setServerActionBusy("Restarting…");
25150
26684
  setServerActionStatus("Restart requested. Waiting for the server to come back…", "warn");
@@ -25185,7 +26719,13 @@ async function restartServer() {
25185
26719
  }
25186
26720
 
25187
26721
  async function stopServer() {
25188
- if (!confirm("Stop the Pi Web UI server?\n\nThis disconnects all browser clients and stops the Pi tabs managed by this Web UI.")) return;
26722
+ if (!(await appConfirm({
26723
+ title: "Stop Pi Web UI server?",
26724
+ summary: "The Web UI becomes unavailable until the server is started again.",
26725
+ affected: "All connected browser clients and Pi tabs managed by this Web UI",
26726
+ undoable: false,
26727
+ confirmLabel: "Stop server",
26728
+ }))) return;
25189
26729
 
25190
26730
  setServerActionBusy("Stopping…");
25191
26731
  setServerActionStatus("Stop requested. The Web UI will disconnect.", "warn");
@@ -25545,6 +27085,7 @@ function handleExtensionUiRequest(request) {
25545
27085
  if (statusKey === STATS_WEBUI_STATUS_KEY) handleStatsWebuiStatus(request.statusText);
25546
27086
  if (statusKey === BTW_WEBUI_STATUS_KEY) handleBtwWebuiStatus(request.statusText);
25547
27087
  if (statusKey === NATURAL_CONVERSATION_STATUS_KEY) handleNaturalConversationStatus(request.statusText, request.tabId || activeTabId);
27088
+ if (statusKey === WORKFLOW_MODE_STATUS_KEY) handleWorkflowModeStatus(request.statusText, request.tabId || activeTabId);
25548
27089
  if (statusKey === "pi-remote-webui") handleRemoteWebuiStatus(request.statusText);
25549
27090
  updateOptionalFeatureAvailability();
25550
27091
  if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) {
@@ -25562,6 +27103,21 @@ function handleExtensionUiRequest(request) {
25562
27103
  case "setWidget": {
25563
27104
  const widgetKey = request.widgetKey || request.id;
25564
27105
  const requestTabId = request.tabId || activeTabId;
27106
+ if (widgetKey === WORKFLOW_MODE_RPC_WIDGET_KEY) {
27107
+ const modeState = workflowModeStateFromRpcPayload(request.widgetLines);
27108
+ if (modeState) updateWorkflowModeForTab(requestTabId, modeState, { render: requestTabId === activeTabId });
27109
+ updateOptionalFeatureAvailability();
27110
+ return;
27111
+ }
27112
+ if (widgetKey === WORKFLOW_INSPECTOR_WIDGET_KEY) {
27113
+ const inspector = parseWorkflowInspectorPayload(request.widgetLines);
27114
+ if (inspector) updateWorkflowInspectorForTab(requestTabId, inspector);
27115
+ if (!setWidgetForTab(requestTabId, widgetKey, request)) return;
27116
+ updateOptionalFeatureAvailability();
27117
+ renderTabs();
27118
+ renderWidgets();
27119
+ return;
27120
+ }
25565
27121
  if (widgetKey === "pi-remote-webui") {
25566
27122
  setWidgetForTab(requestTabId, widgetKey, { ...request, widgetLines: undefined });
25567
27123
  if (Array.isArray(request.widgetLines)) {
@@ -25702,6 +27258,18 @@ function handleInactiveTabEvent(event) {
25702
27258
  if (event.type === "extension_ui_request" && EXTENSION_UI_BLOCKING_METHODS.has(event.method)) {
25703
27259
  if (!event.replayed) notifyBlockedTab(event.tabId, { request: event, count: event.pendingExtensionUiRequestCount });
25704
27260
  renderTabs();
27261
+ } else if (event.type === "extension_ui_request" && event.method === "setStatus" && event.statusKey === WORKFLOW_MODE_STATUS_KEY) {
27262
+ handleWorkflowModeStatus(event.statusText, event.tabId);
27263
+ renderTabs();
27264
+ } else if (event.type === "extension_ui_request" && event.method === "setWidget" && (event.widgetKey || event.id) === WORKFLOW_MODE_RPC_WIDGET_KEY) {
27265
+ const modeState = workflowModeStateFromRpcPayload(event.widgetLines);
27266
+ if (modeState) updateWorkflowModeForTab(event.tabId, modeState, { render: false });
27267
+ renderTabs();
27268
+ } else if (event.type === "extension_ui_request" && event.method === "setWidget" && (event.widgetKey || event.id) === WORKFLOW_INSPECTOR_WIDGET_KEY) {
27269
+ const inspector = parseWorkflowInspectorPayload(event.widgetLines);
27270
+ if (inspector) updateWorkflowInspectorForTab(event.tabId, inspector);
27271
+ setWidgetForTab(event.tabId, WORKFLOW_INSPECTOR_WIDGET_KEY, event);
27272
+ renderTabs();
25705
27273
  } else if (event.type === "agent_end") {
25706
27274
  notifyAgentDone(event.tabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
25707
27275
  }
@@ -25719,6 +27287,7 @@ function handleEvent(event) {
25719
27287
  switch (event.type) {
25720
27288
  case "webui_connected":
25721
27289
  setWebuiVersion(event.version);
27290
+ setPiVersion(event.piVersion);
25722
27291
  setWebuiDevServer(isWebuiDevMetadata(event));
25723
27292
  if (Object.prototype.hasOwnProperty.call(event, "activeRun")) {
25724
27293
  setAppRunnerData(event.tabId || activeTabId, { cwd: event.cwd, activeRun: event.activeRun });
@@ -25732,6 +27301,12 @@ function handleEvent(event) {
25732
27301
  applyTabMetadata(event.tab || { id: event.tabId, title: event.tabTitle, activity: event.tabActivity });
25733
27302
  addEvent(`${event.previousTabTitle || "terminal"} renamed to ${event.tabTitle || "terminal"}`);
25734
27303
  break;
27304
+ case "webui_recovery_opened":
27305
+ addEvent(`opened ${event.recoveryTabTitle || "recovery plan"}`);
27306
+ refreshTabs()
27307
+ .then(() => switchTab(event.recoveryTabId))
27308
+ .catch((error) => addEvent(error.message, "error"));
27309
+ break;
25735
27310
  case "pi_process_start":
25736
27311
  addEvent(`started pi rpc pid ${event.pid}`);
25737
27312
  refreshTabs().catch((error) => addEvent(error.message, "error"));
@@ -25911,7 +27486,7 @@ function handleEvent(event) {
25911
27486
  removeStreamingToolCallCard();
25912
27487
  handleToolExecutionStart(event);
25913
27488
  setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`);
25914
- addEvent(`tool ${event.toolName} started`);
27489
+ addEvent(`tool ${event.toolName} started`, "info", { toolCallId: event.toolCallId });
25915
27490
  break;
25916
27491
  case "tool_execution_update":
25917
27492
  handleToolExecutionUpdate(event);
@@ -25921,7 +27496,7 @@ function handleEvent(event) {
25921
27496
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
25922
27497
  handleToolExecutionEnd(event);
25923
27498
  setRunIndicatorActivity(`Tool ${runIndicatorToolName(event.toolName)} ${event.isError ? "failed" : "finished"}; waiting for the agent's next step…`);
25924
- addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info");
27499
+ addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info", { toolCallId: event.toolCallId });
25925
27500
  // No transcript refresh here: the live tool card already shows the
25926
27501
  // result via renderLiveToolRun, and message_end/agent_end reconcile the
25927
27502
  // transcript. This avoids one fetch+render per tool call.
@@ -26313,6 +27888,8 @@ elements.releaseAurButton.addEventListener("click", () => runPublishWorkflow("/r
26313
27888
  elements.nativeSkillsButton.addEventListener("click", () => runNativeCommandMenu("/skills"));
26314
27889
  elements.nativeToolsButton.addEventListener("click", () => runNativeCommandMenu("/tools"));
26315
27890
  elements.optionsCommandPaletteButton.addEventListener("click", () => openCommandPalette());
27891
+ elements.workflowModeButton?.addEventListener("click", () => toggleWorkflowMode());
27892
+ elements.workflowModeChip?.addEventListener("click", () => setWorkflowModeEnabled(false));
26316
27893
  elements.optionsConversationModeButton?.addEventListener("click", () => toggleNaturalConversationMode());
26317
27894
  elements.conversationModeChip?.addEventListener("click", () => toggleVoiceConversationPaused());
26318
27895
  elements.conversationModeEndButton?.addEventListener("click", () => setNaturalConversationModeEnabled(false));
@@ -26341,6 +27918,7 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
26341
27918
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
26342
27919
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
26343
27920
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
27921
+ elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
26344
27922
  elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
26345
27923
  elements.optionsExportButton.addEventListener("click", () => runNativeCommandMenu("/export"));
26346
27924
  elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu("/fork"));
@@ -26401,10 +27979,27 @@ elements.gitPrCreateButton?.addEventListener("click", () => {
26401
27979
  elements.gitPrDialog?.addEventListener("close", () => {
26402
27980
  if (activeGitPrDialogResolve) resolveGitPrDialog(null);
26403
27981
  });
27982
+ elements.nativeCommandDialog.addEventListener("cancel", (event) => {
27983
+ if (!nativeSettingsDirty) return;
27984
+ event.preventDefault();
27985
+ closeNativeCommandDialog();
27986
+ });
26404
27987
  elements.nativeCommandDialog.addEventListener("close", () => {
26405
27988
  elements.nativeCommandSearch.oninput = null;
27989
+ nativeSettingsDirty = false;
26406
27990
  nativeCommandTabId = null;
26407
27991
  });
27992
+ elements.undoToastButton?.addEventListener("click", () => runOfferedUndo());
27993
+ elements.undoToastDismissButton?.addEventListener("click", dismissUndoToast);
27994
+ elements.confirmationCancelButton?.addEventListener("click", () => finishApplicationConfirmation(false));
27995
+ elements.confirmationConfirmButton?.addEventListener("click", () => finishApplicationConfirmation(true));
27996
+ elements.confirmationDialog?.addEventListener("cancel", (event) => {
27997
+ event.preventDefault();
27998
+ finishApplicationConfirmation(false);
27999
+ });
28000
+ elements.confirmationDialog?.addEventListener("close", () => {
28001
+ if (activeConfirmationResolve) finishApplicationConfirmation(false);
28002
+ });
26408
28003
  elements.commandPaletteDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
26409
28004
  elements.commandPaletteDialog?.addEventListener("cancel", (event) => {
26410
28005
  event.preventDefault();
@@ -26636,7 +28231,13 @@ elements.abortButton.addEventListener("click", (event) => {
26636
28231
  elements.newSessionButton.addEventListener("click", async () => {
26637
28232
  setComposerActionsOpen(false);
26638
28233
  const tabContext = activeTabContext();
26639
- if (!confirm("Start a new Pi session?")) return;
28234
+ if (!(await appConfirm({
28235
+ title: "Start a new Pi session?",
28236
+ summary: "The active tab switches to a fresh conversation.",
28237
+ affected: "The active tab; the previous session remains resumable.",
28238
+ undoable: false,
28239
+ confirmLabel: "Start new session",
28240
+ }))) return;
26640
28241
  try {
26641
28242
  const response = await api("/api/new-session", { method: "POST", body: {}, tabId: tabContext.tabId });
26642
28243
  applyResponseTab(response);
@@ -26803,6 +28404,13 @@ if (elements.terminalTabsLayoutSelect) {
26803
28404
  setTerminalTabsLayout(elements.terminalTabsLayoutSelect.value, { announce: true });
26804
28405
  });
26805
28406
  }
28407
+ elements.piVersionButton?.addEventListener("click", () => {
28408
+ openPiReleaseNotes().catch((error) => addEvent(error.message || String(error), "error"));
28409
+ });
28410
+ elements.webuiVersionButton?.addEventListener("click", () => {
28411
+ confirmOpenWebuiNpmPage().catch((error) => addEvent(error.message || String(error), "error"));
28412
+ });
28413
+ elements.piReleaseNotesCloseButton?.addEventListener("click", () => elements.piReleaseNotesDialog?.close());
26806
28414
  elements.toggleSidePanelButton.addEventListener("click", () => {
26807
28415
  setSidePanelCollapsed(true);
26808
28416
  });
@@ -27200,6 +28808,7 @@ elements.refreshClaudeUsageButton?.addEventListener("click", () => {
27200
28808
  refreshClaudeUsage().finally(() => scheduleRefreshClaudeUsage());
27201
28809
  });
27202
28810
  elements.fileTreeRefreshButton?.addEventListener("click", () => refreshFileTreeRoot().catch((error) => addEvent(error.message || String(error), "error")));
28811
+ elements.fileTreeRoot?.addEventListener("keydown", handleFileTreeKeydown);
27203
28812
  elements.fileTreeRoot?.addEventListener("dragover", handleFileTreeRootDragOver);
27204
28813
  elements.fileTreeRoot?.addEventListener("dragleave", handleFileTreeRootDragLeave);
27205
28814
  elements.fileTreeRoot?.addEventListener("drop", (event) => handleFileTreeRootDrop(event).catch((error) => addEvent(error.message || String(error), "error")));
@@ -27214,6 +28823,21 @@ elements.fileTreeSearchInput?.addEventListener("keydown", (event) => {
27214
28823
  }
27215
28824
  });
27216
28825
  elements.fileTreeSearchClearButton?.addEventListener("click", () => clearFileTreeSearch({ focus: true }));
28826
+ elements.fileContextMenu?.addEventListener("keydown", (event) => {
28827
+ const items = [...elements.fileContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
28828
+ const index = items.indexOf(document.activeElement);
28829
+ if (event.key === "Escape") {
28830
+ event.preventDefault();
28831
+ closeFileContextMenu();
28832
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
28833
+ event.preventDefault();
28834
+ const direction = event.key === "ArrowDown" ? 1 : -1;
28835
+ items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
28836
+ } else if (event.key === "Home" || event.key === "End") {
28837
+ event.preventDefault();
28838
+ items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
28839
+ }
28840
+ });
27217
28841
  elements.fileContextMenu?.addEventListener("click", (event) => {
27218
28842
  const button = event.target?.closest?.("[data-file-menu-action]");
27219
28843
  if (!button) return;
@@ -27365,6 +28989,7 @@ elements.promptInput.addEventListener("blur", () => {
27365
28989
  }, 120);
27366
28990
  });
27367
28991
 
28992
+ installModalPrimitives();
27368
28993
  resizePromptInput();
27369
28994
  restoreFileViewerWidthPreference();
27370
28995
  focusPromptInput({ defer: true });
@@ -27391,6 +29016,7 @@ restoreTerminalTabsLayoutSetting();
27391
29016
  restoreTerminalCustomGroups();
27392
29017
  restoreToolOutputExpansionSetting();
27393
29018
  restoreWorkspaceDashboardState();
29019
+ restoreInterfaceDensity();
27394
29020
  initializeTerminalHeaderTooltips();
27395
29021
  restoreSidePanelSectionState();
27396
29022
  bindSidePanelSectionToggles();