@firstpick/pi-package-webui 0.6.7 → 0.6.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -21,6 +21,7 @@ const elements = {
21
21
  commandPaletteButton: $("#commandPaletteButton"),
22
22
  workspaceDashboardToggleButton: $("#workspaceDashboardToggleButton"),
23
23
  workspaceDashboard: $("#workspaceDashboard"),
24
+ remoteAccessIndicator: $("#remoteAccessIndicator"),
24
25
  statusBar: $("#statusBar"),
25
26
  contextMeterBar: $("#contextMeterBar"),
26
27
  serverOfflinePanel: $("#serverOfflinePanel"),
@@ -59,6 +60,7 @@ const elements = {
59
60
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
60
61
  sessionSkillTags: $("#sessionSkillTags"),
61
62
  conversationModeChip: $("#conversationModeChip"),
63
+ workflowModeChip: $("#workflowModeChip"),
62
64
  skillEditorDialog: $("#skillEditorDialog"),
63
65
  skillEditorTitle: $("#skillEditorTitle"),
64
66
  skillEditorMeta: $("#skillEditorMeta"),
@@ -85,6 +87,7 @@ const elements = {
85
87
  remoteMicStreamingConsentButton: $("#remoteMicStreamingConsentButton"),
86
88
  newSessionButton: $("#newSessionButton"),
87
89
  compactButton: $("#compactButton"),
90
+ workflowModeButton: $("#workflowModeButton"),
88
91
  gitWorkflowButton: $("#gitWorkflowButton"),
89
92
  publishButton: $("#publishButton"),
90
93
  publishMenu: $("#publishMenu"),
@@ -108,6 +111,7 @@ const elements = {
108
111
  optionsNameButton: $("#optionsNameButton"),
109
112
  optionsCloneButton: $("#optionsCloneButton"),
110
113
  optionsSettingsButton: $("#optionsSettingsButton"),
114
+ optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
111
115
  optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
112
116
  optionsExportButton: $("#optionsExportButton"),
113
117
  optionsForkButton: $("#optionsForkButton"),
@@ -242,6 +246,19 @@ const elements = {
242
246
  commandSearchInput: $("#commandSearchInput"),
243
247
  commandsBox: $("#commandsBox"),
244
248
  eventLog: $("#eventLog"),
249
+ undoToast: $("#undoToast"),
250
+ undoToastMessage: $("#undoToastMessage"),
251
+ undoToastTime: $("#undoToastTime"),
252
+ undoToastButton: $("#undoToastButton"),
253
+ undoToastDismissButton: $("#undoToastDismissButton"),
254
+ confirmationDialog: $("#confirmationDialog"),
255
+ confirmationTitle: $("#confirmationTitle"),
256
+ confirmationSummary: $("#confirmationSummary"),
257
+ confirmationAffected: $("#confirmationAffected"),
258
+ confirmationUndo: $("#confirmationUndo"),
259
+ confirmationAlternative: $("#confirmationAlternative"),
260
+ confirmationCancelButton: $("#confirmationCancelButton"),
261
+ confirmationConfirmButton: $("#confirmationConfirmButton"),
245
262
  dialog: $("#extensionDialog"),
246
263
  dialogTitle: $("#dialogTitle"),
247
264
  dialogMessage: $("#dialogMessage"),
@@ -360,12 +377,19 @@ let tabsRenderFrame = null;
360
377
  let foregroundReconcileTimer = null;
361
378
  let eventSource = null;
362
379
  let activeDialog = null;
380
+ let activeConfirmationResolve = null;
381
+ let activeUndoAction = null;
382
+ let undoToastTimer = null;
383
+ let undoToastFocusReturn = null;
384
+ const modalSurfaceState = new WeakMap();
385
+ let activeDrawerModal = null;
363
386
  let activeGitPrDialogResolve = null;
364
387
  let gitChangesState = { loading: false, pulling: false, fetching: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, data: null, operation: null, lastFetch: null, tabId: null };
365
388
  let gitToolsState = { tabId: null, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
366
389
  let gitChangesRequestSerial = 0;
367
390
  const gitChangesUntrackedContentRequests = new Set();
368
391
  let nativeCommandTabId = null;
392
+ let nativeSettingsDirty = false;
369
393
  let pathPickerState = null;
370
394
  let firstTerminalCwdPromptShown = false;
371
395
  let pathFastPicks = [];
@@ -519,6 +543,7 @@ let latestQueuedMessagesByTab = new Map();
519
543
  let loadedPromptList = null;
520
544
  let promptListRunning = false;
521
545
  let workspaceDashboardCollapsed = false;
546
+ let interfaceDensity = "comfortable";
522
547
  let commandPaletteIndex = 0;
523
548
  let commandPaletteItems = [];
524
549
  let activeEditRetry = null;
@@ -538,6 +563,7 @@ let escapeAbortHoldSuppressesDoubleEscape = false;
538
563
  let suppressEmptyPromptEscapeUntil = 0;
539
564
  const dialogQueue = [];
540
565
  const SIDE_PANEL_STORAGE_KEY = "pi-webui-side-panel-collapsed";
566
+ const INTERFACE_DENSITY_STORAGE_KEY = "pi-webui-interface-density";
541
567
  const SIDE_PANEL_SECTION_STORAGE_KEY = "pi-webui-side-panel-sections-collapsed";
542
568
  const TAB_STORAGE_KEY = "pi-webui-active-tab";
543
569
  const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
@@ -636,6 +662,15 @@ const BTW_WEBUI_PAYLOAD_TYPES = new Set(["firstpick.pi-extension-btw.overlay", "
636
662
  const WORKFLOW_WIDGET_PAYLOAD_PREFIX = "WORKFLOW_WEBUI_PAYLOAD ";
637
663
  const WORKFLOW_SUBPROCESS_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.subprocess";
638
664
  const WORKFLOW_SUBPROCESS_PAYLOAD_VERSION = 1;
665
+ const WORKFLOW_INSPECTOR_WIDGET_KEY = "workflow:rpc";
666
+ const WORKFLOW_INSPECTOR_PAYLOAD_PREFIX = "WORKFLOW_RPC_PAYLOAD ";
667
+ const WORKFLOW_INSPECTOR_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.inspector";
668
+ const WORKFLOW_INSPECTOR_PAYLOAD_VERSION = 1;
669
+ const WORKFLOW_MODE_STATUS_KEY = "workflow-mode";
670
+ const WORKFLOW_MODE_RPC_WIDGET_KEY = "workflow-mode:rpc";
671
+ const WORKFLOW_MODE_RPC_PAYLOAD_PREFIX = "WORKFLOW_MODE_RPC_PAYLOAD ";
672
+ const WORKFLOW_MODE_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.mode";
673
+ const WORKFLOW_MODE_RPC_PAYLOAD_VERSION = 1;
639
674
  const GIT_CHANGES_RENDER_ROW_LIMIT = 4000;
640
675
  const GIT_PULL_RESULT_FILE_LIMIT = 48;
641
676
  const LAST_USER_PROMPT_STORAGE_KEY = "pi-webui-last-user-prompts";
@@ -737,6 +772,10 @@ const todoProgressSignatureByTab = new Map();
737
772
  const releaseNpmOutputExpandedByTab = new Map();
738
773
  const appRunnerDataByTab = new Map();
739
774
  const conversationModeByTab = new Map();
775
+ const workflowModeByTab = new Map();
776
+ const workflowModeTogglePendingByTab = new Set();
777
+ const workflowInspectorByTab = new Map();
778
+ const workflowInspectorSelectionByTab = new Map();
740
779
  const appRunnerInputDraftByRun = new Map();
741
780
  const appRunnerContextLineDraftByRun = new Map();
742
781
  const liveToolRuns = new Map();
@@ -820,8 +859,8 @@ const OPTIONAL_FEATURES = [
820
859
  id: "safetyGuard",
821
860
  label: "Safety guard",
822
861
  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.",
862
+ capabilityLabel: "/safety-guard or /safety-guard-setup command",
863
+ description: "Configurable guardrails for dangerous bash commands and protected file edits.",
825
864
  },
826
865
  {
827
866
  id: "tuiSkillsCommand",
@@ -928,6 +967,7 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
928
967
  ["workflow", "workflows"],
929
968
  ["workflow-clear", "workflows"],
930
969
  ["safety-guard", "safetyGuard"],
970
+ ["safety-guard-setup", "safetyGuard"],
931
971
  ["skills", "tuiSkillsCommand"],
932
972
  ["tools", "tuiToolsCommand"],
933
973
  ["remote", "remoteWebui"],
@@ -943,7 +983,7 @@ const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
943
983
  HIDDEN_COMMAND_NAMES.add("stats-webui");
944
984
  HIDDEN_COMMAND_NAMES.add("btw-status");
945
985
  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"]);
986
+ 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
987
  const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
948
988
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
949
989
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
@@ -2544,11 +2584,192 @@ function setMobileTabsExpanded(expanded) {
2544
2584
  elements.terminalTabsToggleButton.setAttribute("aria-expanded", mobileTabsExpanded ? "true" : "false");
2545
2585
  }
2546
2586
 
2587
+ function modalFocusableElements(surface) {
2588
+ if (!surface) return [];
2589
+ return [...surface.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')]
2590
+ .filter((node) => !node.hidden && node.getAttribute("aria-hidden") !== "true" && node.getClientRects().length > 0);
2591
+ }
2592
+
2593
+ function installDialogModalPrimitive(dialog) {
2594
+ if (!dialog || dialog.dataset.modalPrimitive === "true") return;
2595
+ dialog.dataset.modalPrimitive = "true";
2596
+ const showModal = dialog.showModal.bind(dialog);
2597
+ dialog.showModal = () => {
2598
+ modalSurfaceState.set(dialog, { trigger: document.activeElement instanceof HTMLElement ? document.activeElement : null });
2599
+ showModal();
2600
+ };
2601
+ dialog.addEventListener("close", () => {
2602
+ const trigger = modalSurfaceState.get(dialog)?.trigger;
2603
+ modalSurfaceState.delete(dialog);
2604
+ const openModal = document.querySelector("dialog:modal");
2605
+ if (trigger?.isConnected && (!openModal || trigger.closest("dialog:modal"))) queueMicrotask(() => trigger.focus({ preventScroll: true }));
2606
+ });
2607
+ }
2608
+
2609
+ function installModalPrimitives() {
2610
+ document.querySelectorAll("dialog").forEach(installDialogModalPrimitive);
2611
+ }
2612
+
2613
+ function dismissUndoToast() {
2614
+ clearTimeout(undoToastTimer);
2615
+ undoToastTimer = null;
2616
+ activeUndoAction = null;
2617
+ if (!elements.undoToast) return;
2618
+ const returnFocus = elements.undoToast.contains(document.activeElement) ? undoToastFocusReturn : null;
2619
+ undoToastFocusReturn = null;
2620
+ elements.undoToast.hidden = true;
2621
+ elements.undoToast.classList.remove("expiring", "undoing", "error");
2622
+ elements.undoToastButton.disabled = false;
2623
+ if (returnFocus?.isConnected) queueMicrotask(() => returnFocus.focus({ preventScroll: true }));
2624
+ }
2625
+
2626
+ function settleUndoToast(message, { error = false, timeoutMs = 3500 } = {}) {
2627
+ if (!elements.undoToast) return;
2628
+ clearTimeout(undoToastTimer);
2629
+ undoToastTimer = null;
2630
+ activeUndoAction = null;
2631
+ elements.undoToast.hidden = false;
2632
+ elements.undoToast.classList.remove("undoing");
2633
+ elements.undoToast.classList.toggle("error", error);
2634
+ const hadFocus = elements.undoToast.contains(document.activeElement);
2635
+ elements.undoToastMessage.textContent = message;
2636
+ elements.undoToastTime.hidden = true;
2637
+ elements.undoToastButton.hidden = true;
2638
+ if (hadFocus) elements.undoToastDismissButton.focus({ preventScroll: true });
2639
+ undoToastTimer = setTimeout(dismissUndoToast, timeoutMs);
2640
+ }
2641
+
2642
+ function offerUndo({ message, undo, successMessage = "Action undone.", timeoutMs = 10000 } = {}) {
2643
+ if (!message || typeof undo !== "function" || !elements.undoToast) return;
2644
+ dismissUndoToast();
2645
+ undoToastFocusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
2646
+ activeUndoAction = { undo, successMessage };
2647
+ elements.undoToastMessage.textContent = message;
2648
+ elements.undoToastTime.textContent = `Undo available for ${Math.round(timeoutMs / 1000)} seconds`;
2649
+ elements.undoToastTime.hidden = false;
2650
+ elements.undoToastButton.hidden = false;
2651
+ elements.undoToastButton.disabled = false;
2652
+ elements.undoToast.hidden = false;
2653
+ elements.undoToast.style.setProperty("--undo-timeout", `${timeoutMs}ms`);
2654
+ elements.undoToast.classList.remove("expiring", "error", "undoing");
2655
+ void elements.undoToast.offsetWidth;
2656
+ elements.undoToast.classList.add("expiring");
2657
+ undoToastTimer = setTimeout(dismissUndoToast, timeoutMs);
2658
+ }
2659
+
2660
+ async function runOfferedUndo() {
2661
+ const pending = activeUndoAction;
2662
+ if (!pending || !elements.undoToast) return;
2663
+ clearTimeout(undoToastTimer);
2664
+ undoToastTimer = null;
2665
+ activeUndoAction = null;
2666
+ elements.undoToast.classList.remove("expiring");
2667
+ elements.undoToast.classList.add("undoing");
2668
+ elements.undoToastMessage.textContent = "Undoing…";
2669
+ elements.undoToastTime.hidden = true;
2670
+ elements.undoToastButton.disabled = true;
2671
+ try {
2672
+ await pending.undo();
2673
+ settleUndoToast(pending.successMessage);
2674
+ addEvent(pending.successMessage, "success");
2675
+ } catch (error) {
2676
+ const message = `Could not undo: ${error.message || String(error)}`;
2677
+ settleUndoToast(message, { error: true, timeoutMs: 7000 });
2678
+ addEvent(message, "error");
2679
+ }
2680
+ }
2681
+
2682
+ function finishApplicationConfirmation(confirmed) {
2683
+ const resolve = activeConfirmationResolve;
2684
+ activeConfirmationResolve = null;
2685
+ if (elements.confirmationDialog?.open) elements.confirmationDialog.close();
2686
+ resolve?.(!!confirmed);
2687
+ }
2688
+
2689
+ function appConfirm({ title = "Confirm action", summary = "Continue?", affected = "The selected item", undoable = false, alternative = "Cancel and review the action first.", confirmLabel = "Continue", danger = true } = {}) {
2690
+ if (!elements.confirmationDialog?.showModal) {
2691
+ return Promise.resolve(window.confirm([title, summary, affected, undoable ? "This can be undone." : "This cannot be undone.", alternative].filter(Boolean).join("\n\n")));
2692
+ }
2693
+ if (activeConfirmationResolve) finishApplicationConfirmation(false);
2694
+ elements.confirmationTitle.textContent = title;
2695
+ elements.confirmationSummary.textContent = summary;
2696
+ elements.confirmationAffected.textContent = affected;
2697
+ elements.confirmationUndo.textContent = undoable ? "This action can be undone." : "This action cannot be undone.";
2698
+ elements.confirmationAlternative.textContent = alternative;
2699
+ elements.confirmationConfirmButton.textContent = confirmLabel;
2700
+ elements.confirmationConfirmButton.classList.toggle("danger", danger);
2701
+ elements.confirmationConfirmButton.classList.toggle("primary", !danger);
2702
+ return new Promise((resolve) => {
2703
+ activeConfirmationResolve = resolve;
2704
+ elements.confirmationDialog.showModal();
2705
+ queueMicrotask(() => elements.confirmationCancelButton?.focus());
2706
+ });
2707
+ }
2708
+
2709
+ function appConfirmText(message, options = {}) {
2710
+ const text = String(message || "Continue?").trim();
2711
+ const [firstLine, ...rest] = text.split("\n");
2712
+ return appConfirm({
2713
+ title: options.title || firstLine || "Confirm action",
2714
+ summary: options.summary || rest.join("\n").trim() || firstLine || "Continue?",
2715
+ affected: options.affected || "The current workspace, session, or server state described above",
2716
+ undoable: options.undoable === true,
2717
+ alternative: options.alternative || "Cancel and review the affected state before continuing.",
2718
+ confirmLabel: options.confirmLabel || "Continue",
2719
+ danger: options.danger !== false,
2720
+ });
2721
+ }
2722
+
2723
+ function handleDrawerModalKeydown(event) {
2724
+ if (!activeDrawerModal || event.defaultPrevented) return;
2725
+ if (event.key === "Escape") {
2726
+ event.preventDefault();
2727
+ setSidePanelCollapsed(true, { persist: false });
2728
+ return;
2729
+ }
2730
+ if (event.key !== "Tab") return;
2731
+ const focusable = modalFocusableElements(activeDrawerModal.surface);
2732
+ if (!focusable.length) {
2733
+ event.preventDefault();
2734
+ activeDrawerModal.surface.focus({ preventScroll: true });
2735
+ return;
2736
+ }
2737
+ const first = focusable[0];
2738
+ const last = focusable[focusable.length - 1];
2739
+ if (event.shiftKey && document.activeElement === first) {
2740
+ event.preventDefault();
2741
+ last.focus({ preventScroll: true });
2742
+ } else if (!event.shiftKey && document.activeElement === last) {
2743
+ event.preventDefault();
2744
+ first.focus({ preventScroll: true });
2745
+ }
2746
+ }
2747
+
2748
+ function activateDrawerModal(surface, trigger) {
2749
+ if (activeDrawerModal?.surface === surface) return;
2750
+ activeDrawerModal = { surface, trigger };
2751
+ surface.setAttribute("aria-modal", "true");
2752
+ surface.setAttribute("tabindex", "-1");
2753
+ document.addEventListener("keydown", handleDrawerModalKeydown, true);
2754
+ }
2755
+
2756
+ function deactivateDrawerModal(surface) {
2757
+ if (activeDrawerModal?.surface !== surface) {
2758
+ surface?.removeAttribute("aria-modal");
2759
+ return;
2760
+ }
2761
+ const trigger = activeDrawerModal.trigger;
2762
+ activeDrawerModal = null;
2763
+ surface.removeAttribute("aria-modal");
2764
+ document.removeEventListener("keydown", handleDrawerModalKeydown, true);
2765
+ if (trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
2766
+ }
2767
+
2547
2768
  function syncMobileSidePanelState(collapsed) {
2548
2769
  const showBackdrop = !collapsed && isSidePanelOverlayView();
2549
2770
  elements.sidePanelBackdrop.hidden = !showBackdrop;
2550
- if (showBackdrop) elements.sidePanel.setAttribute("aria-modal", "true");
2551
- else elements.sidePanel.removeAttribute("aria-modal");
2771
+ if (showBackdrop) activateDrawerModal(elements.sidePanel, elements.sidePanelExpandButton);
2772
+ else deactivateDrawerModal(elements.sidePanel);
2552
2773
  }
2553
2774
 
2554
2775
  function setSidePanelCollapsed(collapsed, { persist = true, focusPanel = false } = {}) {
@@ -2615,6 +2836,32 @@ function restoreWorkspaceDashboardState() {
2615
2836
  setWorkspaceDashboardCollapsed(readStoredWorkspaceDashboardCollapsed(), { persist: false });
2616
2837
  }
2617
2838
 
2839
+ function normalizeInterfaceDensity(value) {
2840
+ return value === "compact" ? "compact" : "comfortable";
2841
+ }
2842
+
2843
+ function setInterfaceDensity(value, { persist = true } = {}) {
2844
+ interfaceDensity = normalizeInterfaceDensity(value);
2845
+ document.documentElement.dataset.density = interfaceDensity;
2846
+ if (persist) {
2847
+ try {
2848
+ localStorage.setItem(INTERFACE_DENSITY_STORAGE_KEY, interfaceDensity);
2849
+ } catch {
2850
+ // Browser storage is optional; density still applies to this page.
2851
+ }
2852
+ }
2853
+ }
2854
+
2855
+ function restoreInterfaceDensity() {
2856
+ let stored = "comfortable";
2857
+ try {
2858
+ stored = localStorage.getItem(INTERFACE_DENSITY_STORAGE_KEY) || stored;
2859
+ } catch {
2860
+ // Use the accessible default.
2861
+ }
2862
+ setInterfaceDensity(stored, { persist: false });
2863
+ }
2864
+
2618
2865
  function bindMobileViewChanges() {
2619
2866
  if (!mobileViewMedia) return;
2620
2867
  const syncForViewport = (event) => {
@@ -3076,17 +3323,28 @@ function openNativeDownloadInBrowser(download) {
3076
3323
  return true;
3077
3324
  }
3078
3325
 
3079
- function openNativeExportDownloadPrompt(download) {
3326
+ function openNativeExportDownloadPrompt(download, serverPath = "") {
3080
3327
  const url = nativeDownloadOpenUrl(download, { externalBrowser: true });
3081
3328
  if (!url) return false;
3082
3329
  const fileName = String(download?.fileName || "session export");
3330
+ const savedPath = String(serverPath || "").trim();
3083
3331
  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
- );
3332
+ const details = [make("p", "native-command-note", `File: ${fileName}`)];
3333
+ if (savedPath) details.push(make("p", "native-command-note native-export-path", `Saved to:\n${savedPath}`));
3334
+ details.push(make("p", "native-command-note muted", "Open it in your browser, or cancel and use the transcript download URL later."));
3335
+ elements.nativeCommandBody.append(...details);
3088
3336
  elements.nativeCommandActions.replaceChildren();
3089
3337
  addNativeCommandAction("Cancel", closeNativeCommandDialog);
3338
+ if (savedPath) {
3339
+ addNativeCommandAction("Copy path", async () => {
3340
+ try {
3341
+ await copyText(savedPath);
3342
+ addEvent("copied export file path", "info");
3343
+ } catch (error) {
3344
+ addEvent(`copy export path failed: ${error.message || String(error)}`, "error");
3345
+ }
3346
+ });
3347
+ }
3090
3348
  addNativeCommandAction("Copy URL", async () => {
3091
3349
  try {
3092
3350
  await copyText(url);
@@ -3103,8 +3361,8 @@ function openNativeExportDownloadPrompt(download) {
3103
3361
  return true;
3104
3362
  }
3105
3363
 
3106
- function handleNativeDownloadResponse(download, command) {
3107
- if (String(command || "").toLowerCase() === "export") return openNativeExportDownloadPrompt(download);
3364
+ function handleNativeDownloadResponse(download, command, serverPath = "") {
3365
+ if (String(command || "").toLowerCase() === "export") return openNativeExportDownloadPrompt(download, serverPath);
3108
3366
  return triggerNativeDownload(download);
3109
3367
  }
3110
3368
 
@@ -3365,7 +3623,7 @@ async function runPiUpdateAndRestart({ all = false } = {}) {
3365
3623
  renderUpdateNotification(latestUpdateStatus, { force: true });
3366
3624
  return;
3367
3625
  }
3368
- if (!confirm(piUpdateConfirmationText({ all }))) return;
3626
+ 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
3627
 
3370
3628
  const updateLabel = all ? "Pi and package updates" : "Pi update";
3371
3629
  updateRequestInProgress = true;
@@ -4312,6 +4570,155 @@ function isOptionalFeatureEnabled(featureId) {
4312
4570
  return isOptionalFeatureDetected(featureId) && !isOptionalFeatureDisabled(featureId);
4313
4571
  }
4314
4572
 
4573
+ function defaultWorkflowModeState(patch = {}) {
4574
+ return {
4575
+ available: false,
4576
+ enabled: false,
4577
+ phase: "off",
4578
+ behavior: "persistent",
4579
+ statusText: "",
4580
+ updatedAt: "",
4581
+ ...patch,
4582
+ };
4583
+ }
4584
+
4585
+ function normalizeWorkflowModeState(value = {}) {
4586
+ const source = value && typeof value === "object" ? value : {};
4587
+ const enabled = source.enabled === true;
4588
+ const phase = enabled && source.phase === "running" ? "running" : enabled ? "armed" : "off";
4589
+ const behavior = source.behavior === "once" ? "once" : "persistent";
4590
+ return defaultWorkflowModeState({
4591
+ ...source,
4592
+ available: source.available === true,
4593
+ enabled,
4594
+ phase,
4595
+ behavior,
4596
+ statusText: cleanStatusText(source.statusText || ""),
4597
+ });
4598
+ }
4599
+
4600
+ function workflowModeStateFromStatus(statusText = "") {
4601
+ const text = cleanStatusText(statusText || "");
4602
+ const match = text.match(/^workflow\s*:\s*(on|once|running)$/i);
4603
+ return normalizeWorkflowModeState({
4604
+ available: true,
4605
+ enabled: !!match,
4606
+ behavior: match?.[1]?.toLowerCase() === "once" ? "once" : "persistent",
4607
+ phase: match?.[1]?.toLowerCase() === "running" ? "running" : match ? "armed" : "off",
4608
+ statusText: text,
4609
+ updatedAt: new Date().toISOString(),
4610
+ });
4611
+ }
4612
+
4613
+ function workflowModeStateFromRpcPayload(lines) {
4614
+ const raw = String(lines?.[0] || "").trim();
4615
+ if (!raw.startsWith(WORKFLOW_MODE_RPC_PAYLOAD_PREFIX)) return null;
4616
+ try {
4617
+ const payload = JSON.parse(raw.slice(WORKFLOW_MODE_RPC_PAYLOAD_PREFIX.length));
4618
+ if (payload?.type !== WORKFLOW_MODE_RPC_PAYLOAD_TYPE || payload.version !== WORKFLOW_MODE_RPC_PAYLOAD_VERSION) return null;
4619
+ if (typeof payload.enabled !== "boolean" || !["persistent", "once"].includes(payload.behavior) || !["off", "armed", "running"].includes(payload.phase)) return null;
4620
+ return normalizeWorkflowModeState({
4621
+ available: true,
4622
+ enabled: payload.enabled,
4623
+ behavior: payload.behavior,
4624
+ phase: payload.phase,
4625
+ statusText: payload.enabled ? `Workflow: ${payload.phase === "running" ? "running" : payload.behavior === "once" ? "once" : "on"}` : "",
4626
+ updatedAt: typeof payload.updatedAt === "string" ? payload.updatedAt : new Date().toISOString(),
4627
+ });
4628
+ } catch {
4629
+ return null;
4630
+ }
4631
+ }
4632
+
4633
+ function updateWorkflowModeForTab(tabId = activeTabId, mode = {}, { render = true } = {}) {
4634
+ if (!tabId) return normalizeWorkflowModeState(mode);
4635
+ const previous = workflowModeByTab.get(tabId) || {};
4636
+ const next = normalizeWorkflowModeState({ ...previous, ...mode });
4637
+ workflowModeByTab.set(tabId, next);
4638
+ if (tabId === activeTabId && render) renderWorkflowModeControls();
4639
+ return next;
4640
+ }
4641
+
4642
+ function activeWorkflowMode() {
4643
+ return normalizeWorkflowModeState(workflowModeByTab.get(activeTabId) || {});
4644
+ }
4645
+
4646
+ function workflowModeCommandName() {
4647
+ return resolveAvailableCommandName("workflow", { rpcOnly: true }) || "";
4648
+ }
4649
+
4650
+ function renderWorkflowModeControls() {
4651
+ const mode = activeWorkflowMode();
4652
+ const commandName = workflowModeCommandName();
4653
+ const commandAvailable = !!commandName && isOptionalFeatureEnabled("workflows");
4654
+ const active = mode.enabled === true;
4655
+ const pending = !!activeTabId && workflowModeTogglePendingByTab.has(activeTabId);
4656
+ document.body.classList.toggle("workflow-mode-active", active);
4657
+ elements.composer?.classList.toggle("workflow-mode-active", active);
4658
+
4659
+ if (elements.workflowModeButton) {
4660
+ elements.workflowModeButton.hidden = !commandAvailable && !active;
4661
+ elements.workflowModeButton.disabled = !commandName || pending;
4662
+ elements.workflowModeButton.classList.toggle("active", active);
4663
+ elements.workflowModeButton.setAttribute("aria-pressed", active ? "true" : "false");
4664
+ const label = elements.workflowModeButton.querySelector("span");
4665
+ if (label) label.textContent = pending ? "Workflow…" : active ? "Workflow On" : "Workflow";
4666
+ const tooltip = commandName
4667
+ ? `${active ? "Disable" : "Enable"} JavaScript Workflow Mode for this Pi tab via /${commandName} mode ${active ? "off" : "on"}.`
4668
+ : "Workflow Mode is unavailable because the /workflow command is not loaded.";
4669
+ applyStyledTooltip(elements.workflowModeButton, tooltip, { ariaLabel: true, align: "start" });
4670
+ }
4671
+
4672
+ if (elements.workflowModeChip) {
4673
+ elements.workflowModeChip.hidden = !active;
4674
+ elements.workflowModeChip.disabled = !commandName || pending;
4675
+ elements.workflowModeChip.textContent = mode.phase === "running" ? "Workflow: running" : mode.behavior === "once" ? "Workflow: once" : "Workflow: on";
4676
+ elements.workflowModeChip.setAttribute("aria-pressed", "true");
4677
+ elements.workflowModeChip.title = "Workflow Mode is active. Click to return this tab to normal Pi prompting.";
4678
+ elements.workflowModeChip.setAttribute("aria-label", `${elements.workflowModeChip.textContent}. Click to disable Workflow Mode.`);
4679
+ }
4680
+ }
4681
+
4682
+ function handleWorkflowModeStatus(statusText, tabId = activeTabId) {
4683
+ updateWorkflowModeForTab(tabId, workflowModeStateFromStatus(statusText), { render: tabId === activeTabId });
4684
+ }
4685
+
4686
+ async function setWorkflowModeEnabled(enabled) {
4687
+ const tabContext = activeTabContext();
4688
+ if (!tabContext.tabId) return;
4689
+ const commandName = workflowModeCommandName();
4690
+ if (!commandName) {
4691
+ addEvent("Workflow Mode is unavailable because the /workflow command is not loaded.", "warn");
4692
+ await refreshCommands(tabContext);
4693
+ return;
4694
+ }
4695
+
4696
+ workflowModeTogglePendingByTab.add(tabContext.tabId);
4697
+ renderWorkflowModeControls();
4698
+ setComposerActionsOpen(false);
4699
+ try {
4700
+ await sendPrompt("prompt", `/${commandName} mode ${enabled ? "on" : "off"}`, { targetTabId: tabContext.tabId, throwOnError: true });
4701
+ if (!isCurrentTabContext(tabContext)) return;
4702
+ updateWorkflowModeForTab(tabContext.tabId, {
4703
+ available: true,
4704
+ enabled: enabled === true,
4705
+ phase: enabled ? "armed" : "off",
4706
+ statusText: enabled ? "Workflow: on" : "",
4707
+ updatedAt: new Date().toISOString(),
4708
+ });
4709
+ addEvent(enabled ? "Workflow Mode enabled for this tab." : "Workflow Mode disabled for this tab.", "info");
4710
+ } catch (error) {
4711
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
4712
+ } finally {
4713
+ workflowModeTogglePendingByTab.delete(tabContext.tabId);
4714
+ if (isCurrentTabContext(tabContext)) renderWorkflowModeControls();
4715
+ }
4716
+ }
4717
+
4718
+ function toggleWorkflowMode() {
4719
+ return setWorkflowModeEnabled(!activeWorkflowMode().enabled);
4720
+ }
4721
+
4315
4722
  function defaultConversationModeState(patch = {}) {
4316
4723
  return {
4317
4724
  featureId: "naturalConversation",
@@ -5504,7 +5911,7 @@ function fileDisplayName(path = "") {
5504
5911
  }
5505
5912
 
5506
5913
  function fileEntryIcon(entry = {}) {
5507
- if (entry.type === "directory") return "▸";
5914
+ if (entry.type === "directory") return "DIR";
5508
5915
  if (entry.type === "file") return entry.extension === ".md" || entry.extension === ".markdown" ? "Md" : "TXT";
5509
5916
  if (entry.type === "error") return "!";
5510
5917
  return "·";
@@ -5523,8 +5930,6 @@ function normalizeFileTreeGitStatus(status = {}) {
5523
5930
  }
5524
5931
 
5525
5932
  function fileTreeGitStatusForEntry(entry = {}) {
5526
- const own = normalizeFileTreeGitStatus(entry.gitStatus);
5527
- if (own) return own;
5528
5933
  return fileTreeState.gitStatusByPath.get(normalizeFileTreePath(entry.path || "")) || null;
5529
5934
  }
5530
5935
 
@@ -5655,6 +6060,7 @@ function renderFileTree() {
5655
6060
  list.setAttribute("role", "group");
5656
6061
  for (const entry of fileTreeState.searchEntries) appendFileSearchEntry(list, entry);
5657
6062
  root.append(list);
6063
+ syncFileTreeRovingTabindex();
5658
6064
  return;
5659
6065
  }
5660
6066
  const entries = fileTreeState.entriesByPath.get(FILE_TREE_ROOT_PATH) || [];
@@ -5666,6 +6072,51 @@ function renderFileTree() {
5666
6072
  list.setAttribute("role", "group");
5667
6073
  for (const entry of entries) appendFileTreeEntry(list, entry, 0);
5668
6074
  root.append(list);
6075
+ syncFileTreeRovingTabindex();
6076
+ }
6077
+
6078
+ function visibleFileTreeItems() {
6079
+ return [...elements.fileTreeRoot?.querySelectorAll('[role="treeitem"]') || []];
6080
+ }
6081
+
6082
+ function syncFileTreeRovingTabindex(preferredPath = fileTreeState.selectedPath) {
6083
+ const items = visibleFileTreeItems();
6084
+ const active = items.find((item) => normalizeFileTreePath(item.dataset.path) === normalizeFileTreePath(preferredPath)) || items[0];
6085
+ for (const item of items) item.tabIndex = item === active ? 0 : -1;
6086
+ }
6087
+
6088
+ function selectFileTreePath(path, { focus = false } = {}) {
6089
+ fileTreeState.selectedPath = normalizeFileTreePath(path);
6090
+ renderFileTree();
6091
+ if (focus) {
6092
+ const selected = visibleFileTreeItems().find((item) => normalizeFileTreePath(item.dataset.path) === fileTreeState.selectedPath);
6093
+ selected?.focus({ preventScroll: true });
6094
+ }
6095
+ }
6096
+
6097
+ function fileTreeOverflowButton(entry) {
6098
+ const button = make("button", "file-tree-overflow-button", "⋯");
6099
+ button.type = "button";
6100
+ button.setAttribute("aria-label", `Actions for ${entry.name || fileDisplayName(entry.path)}`);
6101
+ button.setAttribute("aria-haspopup", "menu");
6102
+ button.addEventListener("click", (event) => {
6103
+ event.stopPropagation();
6104
+ showFileContextMenuForElement(button, entry);
6105
+ });
6106
+ return button;
6107
+ }
6108
+
6109
+ function fileTreeExpander(entry, expanded = false, { search = false } = {}) {
6110
+ const button = make("button", "file-tree-expander", expanded ? "▾" : "▸");
6111
+ button.type = "button";
6112
+ button.setAttribute("aria-label", `${expanded ? "Collapse" : "Expand"} ${entry.name || fileDisplayName(entry.path)}`);
6113
+ button.setAttribute("aria-expanded", expanded ? "true" : "false");
6114
+ button.addEventListener("click", (event) => {
6115
+ event.stopPropagation();
6116
+ if (search) revealFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
6117
+ else toggleFileTreeDirectory(entry.path).catch((error) => addEvent(error.message || String(error), "error"));
6118
+ });
6119
+ return button;
5669
6120
  }
5670
6121
 
5671
6122
  function appendFileSearchEntry(parent, entry) {
@@ -5681,6 +6132,7 @@ function appendFileSearchEntry(parent, entry) {
5681
6132
  button.dataset.type = entry.type || "file";
5682
6133
  button.style.setProperty("--file-tree-depth", "0");
5683
6134
  button.setAttribute("role", "treeitem");
6135
+ button.setAttribute("aria-selected", fileTreeState.selectedPath === path ? "true" : "false");
5684
6136
  button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5685
6137
  const label = make("span", "file-tree-search-label");
5686
6138
  label.append(
@@ -5698,16 +6150,12 @@ function appendFileSearchEntry(parent, entry) {
5698
6150
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
5699
6151
  button.addEventListener("click", () => {
5700
6152
  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);
6153
+ if (entry.type === "file") openFileInViewer(path);
6154
+ else renderFileTree();
5707
6155
  });
5708
6156
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5709
6157
  bindFileTreeDragAndDrop(button, item, entry);
5710
- item.append(button);
6158
+ item.append(isDirectory ? fileTreeExpander(entry, false, { search: true }) : make("span", "file-tree-expander-spacer"), button, fileTreeOverflowButton(entry));
5711
6159
  parent.append(item);
5712
6160
  }
5713
6161
 
@@ -5749,6 +6197,7 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5749
6197
  button.dataset.type = entry.type || "file";
5750
6198
  button.style.setProperty("--file-tree-depth", String(depth));
5751
6199
  button.setAttribute("role", "treeitem");
6200
+ button.setAttribute("aria-selected", fileTreeState.selectedPath === path ? "true" : "false");
5752
6201
  if (isDirectory) button.setAttribute("aria-expanded", expanded ? "true" : "false");
5753
6202
  button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5754
6203
  button.append(
@@ -5761,17 +6210,12 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5761
6210
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
5762
6211
  button.addEventListener("click", () => {
5763
6212
  fileTreeState.selectedPath = path;
5764
- if (isDirectory) toggleFileTreeDirectory(path);
6213
+ if (entry.type === "file") openFileInViewer(path);
5765
6214
  else renderFileTree();
5766
6215
  });
5767
- button.addEventListener("dblclick", (event) => {
5768
- event.preventDefault();
5769
- if (isDirectory) toggleFileTreeDirectory(path, { force: true });
5770
- else openFileInViewer(path);
5771
- });
5772
6216
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5773
6217
  bindFileTreeDragAndDrop(button, item, entry);
5774
- item.append(button);
6218
+ item.append(isDirectory ? fileTreeExpander(entry, expanded) : make("span", "file-tree-expander-spacer"), button, fileTreeOverflowButton(entry));
5775
6219
  if (isDirectory && expanded) {
5776
6220
  const children = fileTreeState.entriesByPath.get(path) || [];
5777
6221
  const childList = make("ul", "file-tree-list");
@@ -5921,9 +6365,11 @@ async function toggleFileTreeDirectory(path = "", { force = false } = {}) {
5921
6365
  await loadFileTreeDirectory(normalized);
5922
6366
  }
5923
6367
 
5924
- function closeFileContextMenu() {
6368
+ function closeFileContextMenu({ returnFocus = true } = {}) {
6369
+ const trigger = fileContextMenuState?.trigger;
5925
6370
  fileContextMenuState = null;
5926
6371
  if (elements.fileContextMenu) elements.fileContextMenu.hidden = true;
6372
+ if (returnFocus && trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
5927
6373
  }
5928
6374
 
5929
6375
  function showFileContextMenu(event, entry) {
@@ -5931,7 +6377,7 @@ function showFileContextMenu(event, entry) {
5931
6377
  event.preventDefault();
5932
6378
  event.stopPropagation();
5933
6379
  const path = normalizeFileTreePath(entry?.path || "");
5934
- fileContextMenuState = { entry: { ...entry, path } };
6380
+ fileContextMenuState = { entry: { ...entry, path }, trigger: event.currentTarget || document.activeElement };
5935
6381
  const menu = elements.fileContextMenu;
5936
6382
  const webui = menu.querySelector('[data-file-menu-action="open-webui"]');
5937
6383
  if (webui) webui.textContent = entry?.type === "directory" ? "Open in WebUI" : "Open in WebUI";
@@ -5941,6 +6387,47 @@ function showFileContextMenu(event, entry) {
5941
6387
  const top = Math.min(event.clientY, Math.max(0, window.innerHeight - rect.height - 8));
5942
6388
  menu.style.left = `${left}px`;
5943
6389
  menu.style.top = `${top}px`;
6390
+ menu.querySelector('[role="menuitem"]')?.focus({ preventScroll: true });
6391
+ }
6392
+
6393
+ function showFileContextMenuForElement(element, entry) {
6394
+ const rect = element.getBoundingClientRect();
6395
+ showFileContextMenu({
6396
+ preventDefault() {},
6397
+ stopPropagation() {},
6398
+ clientX: rect.right,
6399
+ clientY: rect.bottom,
6400
+ currentTarget: element,
6401
+ }, entry);
6402
+ }
6403
+
6404
+ function handleFileTreeKeydown(event) {
6405
+ const current = event.target?.closest?.('[role="treeitem"]');
6406
+ if (!current || !elements.fileTreeRoot?.contains(current)) return;
6407
+ const items = visibleFileTreeItems();
6408
+ const index = items.indexOf(current);
6409
+ if (index < 0) return;
6410
+ const focusAt = (nextIndex) => {
6411
+ const next = items[Math.max(0, Math.min(items.length - 1, nextIndex))];
6412
+ if (!next) return;
6413
+ event.preventDefault();
6414
+ selectFileTreePath(next.dataset.path, { focus: true });
6415
+ };
6416
+ if (event.key === "ArrowDown") focusAt(index + 1);
6417
+ else if (event.key === "ArrowUp") focusAt(index - 1);
6418
+ else if (event.key === "Home") focusAt(0);
6419
+ else if (event.key === "End") focusAt(items.length - 1);
6420
+ else if (event.key === "ArrowRight" && current.dataset.type === "directory") {
6421
+ event.preventDefault();
6422
+ if (current.getAttribute("aria-expanded") !== "true") toggleFileTreeDirectory(current.dataset.path);
6423
+ else focusAt(index + 1);
6424
+ } else if (event.key === "ArrowLeft" && current.dataset.type === "directory" && current.getAttribute("aria-expanded") === "true") {
6425
+ event.preventDefault();
6426
+ toggleFileTreeDirectory(current.dataset.path);
6427
+ } else if (event.key === "Enter" && current.dataset.type === "directory") {
6428
+ event.preventDefault();
6429
+ toggleFileTreeDirectory(current.dataset.path);
6430
+ }
5944
6431
  }
5945
6432
 
5946
6433
  function currentFileViewerPath() {
@@ -6219,7 +6706,14 @@ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6219
6706
  ? "\n\nThe currently open file has unsaved edits that will be discarded from the viewer."
6220
6707
  : "";
6221
6708
  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;
6709
+ if (!(await appConfirm({
6710
+ title: `Delete ${typeLabel}?`,
6711
+ summary: `${sourcePath}${recursiveWarning}${dirtyWarning}`,
6712
+ affected: typeLabel === "directory" ? "The directory and all files beneath it" : sourcePath,
6713
+ undoable: false,
6714
+ alternative: "Cancel and move or rename it instead.",
6715
+ confirmLabel: `Delete ${typeLabel}`,
6716
+ }))) return;
6223
6717
  const tabContext = activeTabContext();
6224
6718
  setFileTreeStatus(`Deleting ${sourcePath}…`);
6225
6719
  try {
@@ -6240,27 +6734,26 @@ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6240
6734
  }
6241
6735
  }
6242
6736
 
6243
- async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "", { viaDragDrop = false, confirmMove = false } = {}) {
6737
+ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "", { viaDragDrop = false, confirmMove = false, offerMoveUndo = true, tabContext = activeTabContext() } = {}) {
6244
6738
  const sourcePath = normalizeFileTreePath(entry.path || "");
6245
6739
  const normalizedDestination = normalizeFileTreePath(destinationPath);
6246
6740
  if (!sourcePath) {
6247
6741
  addEvent("Workspace root cannot be moved from the Files panel.", "warn");
6248
- return;
6742
+ return false;
6249
6743
  }
6250
6744
  if (!normalizedDestination && normalizedDestination !== FILE_TREE_ROOT_PATH) {
6251
6745
  addEvent("Destination path is required.", "warn");
6252
- return;
6746
+ return false;
6253
6747
  }
6254
6748
  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();
6749
+ 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
6750
  const isDirectory = fileTreeEntryIsDirectory(entry);
6258
6751
  const restoreSourceExpanded = isDirectory && fileTreeState.expanded.has(sourcePath) && !fileTreeSearchQueryText();
6259
6752
  const expandDestinationDirectory = viaDragDrop && !fileTreeSearchQueryText();
6260
6753
  setFileTreeStatus(`Moving ${sourcePath}…`);
6261
6754
  try {
6262
6755
  const response = await api("/api/files/move", { method: "POST", body: { path: sourcePath, toPath: normalizedDestination || ".", confirmed: true }, tabId: tabContext.tabId });
6263
- if (!isCurrentTabContext(tabContext)) return;
6756
+ if (!isCurrentTabContext(tabContext)) return true;
6264
6757
  const data = response.data || {};
6265
6758
  const nextPath = normalizeFileTreePath(data.destination || normalizedDestination);
6266
6759
  const sourceParent = data.parentPath ?? fileParentPath(sourcePath);
@@ -6277,11 +6770,27 @@ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "",
6277
6770
  renderFileTree();
6278
6771
  setFileTreeStatus(`Moved ${sourcePath} to ${nextPath}.`, "success");
6279
6772
  addEvent(`${viaDragDrop ? "drag-moved" : "moved"} ${sourcePath} to ${nextPath}`, "info");
6773
+ if (offerMoveUndo && nextPath && nextPath !== sourcePath) {
6774
+ offerUndo({
6775
+ message: `Moved ${sourcePath} to ${nextPath}.`,
6776
+ undo: async () => {
6777
+ const restored = await moveFileTreeEntryToDestination(
6778
+ { ...entry, path: nextPath },
6779
+ sourcePath,
6780
+ { offerMoveUndo: false, tabContext },
6781
+ );
6782
+ if (!restored) throw new Error(`Could not move ${nextPath} back to ${sourcePath}.`);
6783
+ },
6784
+ successMessage: `Moved ${nextPath} back to ${sourcePath}.`,
6785
+ });
6786
+ }
6787
+ return true;
6280
6788
  } catch (error) {
6281
6789
  if (isCurrentTabContext(tabContext)) {
6282
6790
  setFileTreeStatus(error.message || String(error), "error");
6283
6791
  addEvent(`file move failed: ${error.message || String(error)}`, "error");
6284
6792
  }
6793
+ return false;
6285
6794
  }
6286
6795
  }
6287
6796
 
@@ -6768,6 +7277,10 @@ function syncTabMetadata(nextTabs = []) {
6768
7277
  widgetsByTab.delete(tabId);
6769
7278
  appRunnerDataByTab.delete(tabId);
6770
7279
  conversationModeByTab.delete(tabId);
7280
+ workflowModeByTab.delete(tabId);
7281
+ workflowModeTogglePendingByTab.delete(tabId);
7282
+ workflowInspectorByTab.delete(tabId);
7283
+ workflowInspectorSelectionByTab.delete(tabId);
6771
7284
  remoteMicConsentTabs.delete(tabId);
6772
7285
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
6773
7286
  clearGitWorkflowForTab(tabId);
@@ -6787,6 +7300,7 @@ function applyTabMetadata(tab) {
6787
7300
  if (tab.activity) setTabActivity(tab.id, tab.activity);
6788
7301
  if (Object.prototype.hasOwnProperty.call(tab, "conversationMode")) updateConversationModeForTab(tab.id, tab.conversationMode, { render: false });
6789
7302
  renderConversationModeControls();
7303
+ renderWorkflowModeControls();
6790
7304
  renderTabs();
6791
7305
  return true;
6792
7306
  }
@@ -7330,20 +7844,33 @@ function terminalConversationModeTooltip(tab) {
7330
7844
  return mode.enabled ? ` · natural conversation: ${mode.uiState || "listening"}` : "";
7331
7845
  }
7332
7846
 
7847
+ function tabWorkflowModeActive(tab) {
7848
+ return normalizeWorkflowModeState(workflowModeByTab.get(tab?.id) || {}).enabled === true;
7849
+ }
7850
+
7851
+ function terminalWorkflowTooltip(tab) {
7852
+ const count = workflowRunningCountForTab(tab?.id);
7853
+ return `${tabWorkflowModeActive(tab) ? " · workflow mode active" : ""}${count ? ` · ${count} workflow run${count === 1 ? "" : "s"} active` : ""}`;
7854
+ }
7855
+
7333
7856
  function terminalTabMeta(tab, indicator) {
7334
7857
  const parts = [tab.running ? `${indicator.meta} · pid ${tab.pid || "…"}` : "stopped"];
7335
7858
  if (tabAppRunnerRunningRun(tab)) parts.push("app runner");
7336
7859
  if (tabConversationModeActive(tab)) parts.push("voice");
7860
+ if (tabWorkflowModeActive(tab)) parts.push("workflow mode");
7861
+ const workflowCount = workflowRunningCountForTab(tab.id);
7862
+ if (workflowCount) parts.push(`${workflowCount} workflow${workflowCount === 1 ? "" : "s"}`);
7337
7863
  return parts.join(" · ");
7338
7864
  }
7339
7865
 
7340
- function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false }) {
7866
+ function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false, workflowModeActive = false, workflowCount = 0 }) {
7341
7867
  const titleRow = make("span", "terminal-tab-title-row");
7342
7868
  const indicatorDot = make("span", "terminal-tab-activity-indicator");
7343
7869
  indicatorDot.setAttribute("aria-hidden", "true");
7344
7870
  titleRow.append(indicatorDot, make("span", "terminal-tab-title", title));
7345
7871
  if (appRunnerIsRunning(appRunnerRun)) titleRow.append(make("span", "terminal-tab-app-runner-indicator", "app"));
7346
7872
  if (conversationModeActive) titleRow.append(make("span", "terminal-tab-conversation-indicator", "voice"));
7873
+ if (workflowModeActive || workflowCount) titleRow.append(make("span", "terminal-tab-workflow-indicator", workflowCount ? `wf ${workflowCount}` : "wf"));
7347
7874
  if (count !== null) titleRow.append(make("span", "terminal-tab-group-count", String(count)));
7348
7875
  button.append(titleRow, make("span", "terminal-tab-meta", meta));
7349
7876
  }
@@ -7355,7 +7882,9 @@ function renderTerminalTab(tab) {
7355
7882
  const appRunnerLabel = appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
7356
7883
  const conversationModeActive = tabConversationModeActive(tab);
7357
7884
  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" : ""}`);
7885
+ const workflowModeActive = tabWorkflowModeActive(tab);
7886
+ const workflowCount = workflowRunningCountForTab(tab.id);
7887
+ 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
7888
  wrapper.dataset.tabId = tab.id;
7360
7889
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: tab.id, target: { type: "tab", tabId: tab.id } });
7361
7890
  const button = make("button", "terminal-tab-button");
@@ -7363,10 +7892,10 @@ function renderTerminalTab(tab) {
7363
7892
  button.draggable = false;
7364
7893
  button.setAttribute("role", "tab");
7365
7894
  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`;
7895
+ button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
7896
+ 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
7897
  applyStyledTooltip(button, tooltip, { ariaLabel: false });
7369
- appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive });
7898
+ appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
7370
7899
  button.addEventListener("click", () => switchTab(tab.id));
7371
7900
  wrapper.append(button);
7372
7901
 
@@ -7393,7 +7922,9 @@ function renderTerminalTabGroupItem(tab, group) {
7393
7922
  const appRunnerLabel = appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
7394
7923
  const conversationModeActive = tabConversationModeActive(tab);
7395
7924
  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" : ""}`);
7925
+ const workflowModeActive = tabWorkflowModeActive(tab);
7926
+ const workflowCount = workflowRunningCountForTab(tab.id);
7927
+ 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
7928
  item.dataset.tabId = tab.id;
7398
7929
  bindTerminalTabDragAndDrop(item, { sourceTabId: tab.id, target: group?.custom ? { type: "group", group } : { type: "tab", tabId: tab.id } });
7399
7930
  const button = make("button", "terminal-tab-button terminal-tab-group-item-button");
@@ -7401,10 +7932,10 @@ function renderTerminalTabGroupItem(tab, group) {
7401
7932
  button.draggable = false;
7402
7933
  button.setAttribute("role", "tab");
7403
7934
  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`;
7935
+ button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
7936
+ 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
7937
  applyStyledTooltip(button, tooltip, { ariaLabel: false });
7407
- appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive });
7938
+ appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
7408
7939
  button.addEventListener("click", (event) => {
7409
7940
  event.stopPropagation();
7410
7941
  switchTab(tab.id);
@@ -7442,10 +7973,12 @@ function renderTerminalTabGroup(group, groupCount = 1) {
7442
7973
  const appRunnerCount = groupTabs.filter(tabAppRunnerRunningRun).length;
7443
7974
  const appRunnerSummary = appRunnerCount > 1 ? `${appRunnerCount} app runners running` : appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
7444
7975
  const groupAppRunnerMeta = appRunnerCount > 1 ? `${appRunnerCount} app runners` : appRunnerRun ? "app runner" : "";
7976
+ const workflowCount = groupTabs.reduce((total, tab) => total + workflowRunningCountForTab(tab.id), 0);
7977
+ const workflowModeActive = groupTabs.some(tabWorkflowModeActive);
7445
7978
  const groupTitle = terminalDisplayGroupTitle(group, activeGroupTab?.title || "group");
7446
7979
  const activeTitle = activeGroupTab?.title || groupTitle;
7447
7980
  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" : ""}`);
7981
+ 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
7982
  wrapper.dataset.groupKey = group.key;
7450
7983
  if (group.customGroupId) wrapper.dataset.customGroupId = group.customGroupId;
7451
7984
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: activeGroupTab?.id || "", target: { type: "group", group } });
@@ -7464,10 +7997,10 @@ function renderTerminalTabGroup(group, groupCount = 1) {
7464
7997
  button.setAttribute("aria-selected", isActive ? "true" : "false");
7465
7998
  button.setAttribute("aria-haspopup", "true");
7466
7999
  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`;
8000
+ 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}`);
8001
+ 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
8002
  applyStyledTooltip(button, tooltip, { ariaLabel: false });
7470
- appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}`, appRunnerRun, count: groupTabs.length });
8003
+ appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}${workflowModeActive ? " · workflow mode" : ""}${workflowCount ? ` · ${workflowCount} workflows` : ""}`, appRunnerRun, count: groupTabs.length, workflowModeActive, workflowCount });
7471
8004
  button.addEventListener("click", () => switchTab(activeGroupTab.id));
7472
8005
  wrapper.append(button);
7473
8006
 
@@ -7810,7 +8343,7 @@ function shouldOpenCwdChangeInNewTab(tab) {
7810
8343
  || tabHasActiveAgent(tab);
7811
8344
  }
7812
8345
 
7813
- function confirmCloseTerminalTabs(targetTabs, label) {
8346
+ async function confirmCloseTerminalTabs(targetTabs, label) {
7814
8347
  const count = targetTabs.length;
7815
8348
  const noun = count === 1 ? "tab" : "tabs";
7816
8349
  const activeAgentTabs = targetTabs.filter(tabHasActiveAgent);
@@ -7823,23 +8356,27 @@ function confirmCloseTerminalTabs(targetTabs, label) {
7823
8356
  count > 1 ? `\nTabs to close:\n${tabList}` : "",
7824
8357
  ].filter(Boolean).join("\n");
7825
8358
  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);
8359
+ ? `WARNING: ${activeAgentTabs.length} ${activeAgentTabs.length === 1 ? "tab has an agent" : "tabs have agents"} still running or waiting for input:\n${activeList}`
8360
+ : "No agent work is currently running in these tabs.";
8361
+ return appConfirm({
8362
+ title: `Close ${count === 1 ? "tab" : `${count} tabs`}?`,
8363
+ summary: `${base}\n\n${warning}`,
8364
+ affected: tabList || label || `${count} terminal ${noun}`,
8365
+ undoable: false,
8366
+ alternative: activeAgentTabs.length
8367
+ ? "Cancel and wait for or abort the running work first."
8368
+ : count === 1
8369
+ ? "Cancel and keep this tab open."
8370
+ : "Cancel and close individual tabs instead.",
8371
+ confirmLabel: activeAgentTabs.length ? "Close and stop work" : count === 1 ? "Close tab" : "Close tabs",
8372
+ });
7836
8373
  }
7837
8374
 
7838
8375
  async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } = {}) {
7839
8376
  const targetIds = [...new Set(tabIds.filter(Boolean))];
7840
8377
  const targetTabs = targetIds.map((id) => tabs.find((item) => item.id === id)).filter(Boolean);
7841
8378
  if (!targetTabs.length) return;
7842
- if (!confirmCloseTerminalTabs(targetTabs, label)) return;
8379
+ if (!(await confirmCloseTerminalTabs(targetTabs, label))) return;
7843
8380
 
7844
8381
  const closedActiveTab = targetTabs.some((tab) => tab.id === activeTabId);
7845
8382
  const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
@@ -7916,10 +8453,67 @@ async function initializeTabs() {
7916
8453
  }
7917
8454
  }
7918
8455
 
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}`;
8456
+ function chatEventTargetForLine(line) {
8457
+ const toolCallId = line?.dataset.chatToolCallId || "";
8458
+ if (toolCallId) {
8459
+ const toolTarget = elements.chat.querySelector(`.message[data-tool-call-id="${CSS.escape(toolCallId)}"]`);
8460
+ if (toolTarget) return toolTarget;
8461
+ }
8462
+
8463
+ const eventTimestamp = Number(line?.dataset.chatEventTimestamp);
8464
+ let closestTarget = null;
8465
+ let closestDistance = Number.POSITIVE_INFINITY;
8466
+ for (const candidate of elements.chat.querySelectorAll(".message[data-chat-timestamp]")) {
8467
+ const candidateTimestamp = Number(candidate.dataset.chatTimestamp);
8468
+ if (!Number.isFinite(eventTimestamp) || !Number.isFinite(candidateTimestamp)) continue;
8469
+ const distance = Math.abs(candidateTimestamp - eventTimestamp);
8470
+ if (distance <= closestDistance) {
8471
+ closestTarget = candidate;
8472
+ closestDistance = distance;
8473
+ }
8474
+ }
8475
+ return closestTarget || Array.from(elements.chat.querySelectorAll(".message:not(.runIndicator)")).at(-1) || null;
8476
+ }
8477
+
8478
+ function highlightChatEventTarget(target) {
8479
+ clearTimeout(target._chatEventHighlightTimer);
8480
+ target.classList.remove("chat-event-target");
8481
+ void target.offsetWidth;
8482
+ target.classList.add("chat-event-target");
8483
+ target._chatEventHighlightTimer = setTimeout(() => target.classList.remove("chat-event-target"), 1600);
8484
+ }
8485
+
8486
+ function jumpToChatEvent(line) {
8487
+ const revealTarget = () => {
8488
+ const target = chatEventTargetForLine(line);
8489
+ if (!target) return;
8490
+ autoFollowChat = false;
8491
+ lastChatProgrammaticScrollAt = performance.now();
8492
+ const centeredTop = chatScrollTopForNode(target) - Math.max(stickyUserPromptViewportGap(), (elements.chat.clientHeight - target.offsetHeight) / 2);
8493
+ setChatScrollTopInstant(Math.max(0, centeredTop));
8494
+ highlightChatEventTarget(target);
8495
+ updateJumpToLatestButton();
8496
+ updateStickyUserPromptButton();
8497
+ };
8498
+
8499
+ if (isSidePanelOverlayView() && !document.body.classList.contains("side-panel-collapsed")) {
8500
+ setSidePanelCollapsed(true, { persist: false });
8501
+ requestAnimationFrame(revealTarget);
8502
+ } else {
8503
+ revealTarget();
8504
+ }
8505
+ }
8506
+
8507
+ function addEvent(message, level = "info", { toolCallId = "" } = {}) {
8508
+ const occurredAt = Date.now();
8509
+ const line = make("button", `event ${level}`.trim());
8510
+ line.type = "button";
8511
+ line.dataset.chatEventTimestamp = String(occurredAt);
8512
+ if (toolCallId) line.dataset.chatToolCallId = String(toolCallId);
8513
+ line.textContent = `[${new Date(occurredAt).toLocaleTimeString()}] ${message}`;
8514
+ line.title = "Jump to this event in the chat";
8515
+ line.setAttribute("aria-label", `${line.textContent}. Jump to this event in the chat.`);
8516
+ line.addEventListener("click", () => jumpToChatEvent(line));
7923
8517
  elements.eventLog.prepend(line);
7924
8518
  while (elements.eventLog.children.length > 120) elements.eventLog.lastElementChild?.remove();
7925
8519
  }
@@ -8555,7 +9149,7 @@ async function runGitFooterPiCalibration(mode = "current", tabContext = activeTa
8555
9149
  addEvent("PI calibration unavailable: /calibrate is not loaded in this Pi tab.", "warn");
8556
9150
  return;
8557
9151
  }
8558
- if (mode === "probe" && !confirm("Start an isolated PI calibration probe? This sends one tiny model request and may incur provider token usage.")) return;
9152
+ 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
9153
 
8560
9154
  const command = mode === "probe" ? `/${commandName}` : `/${commandName} current`;
8561
9155
  gitFooterPiCalibrationInFlightByTab.add(tabContext.tabId);
@@ -9566,7 +10160,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
9566
10160
  const protectedWarning = ["main", "master"].includes(branch)
9567
10161
  ? `\n\nWarning: ${branch} is usually a protected/shared branch. Consider pushing a feature branch and opening a PR instead.`
9568
10162
  : "";
9569
- if (!window.confirm(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?${protectedWarning}`)) return;
10163
+ 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
10164
 
9571
10165
  gitFooterSyncPushInFlightByTab.add(tabId);
9572
10166
  if (isCurrentTabContext(tabContext)) renderFooter();
@@ -9574,7 +10168,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
9574
10168
  const response = await api("/api/git-workflow/push", { method: "POST", body: {}, tabId });
9575
10169
  if (!response.ok) {
9576
10170
  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?`);
10171
+ 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
10172
  if (publish) {
9579
10173
  const upstreamResponse = await api("/api/git-workflow/push", { method: "POST", body: { setUpstream: true }, tabId });
9580
10174
  if (!upstreamResponse.ok) throw new Error([upstreamResponse.error, upstreamResponse.hint].filter(Boolean).join("\n"));
@@ -9585,7 +10179,7 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
9585
10179
  throw new Error([response.error, response.hint].filter(Boolean).join("\n"));
9586
10180
  }
9587
10181
  if (response.code === "NON_FAST_FORWARD") {
9588
- const forcePush = window.confirm([
10182
+ const forcePush = await appConfirmText([
9589
10183
  response.error,
9590
10184
  "",
9591
10185
  response.hint || "",
@@ -10599,7 +11193,7 @@ async function pullGitChangesDialog() {
10599
11193
  if (behind <= 0 || gitChangesState.pulling || gitChangesState.loading || gitChangesState.fetching) return;
10600
11194
  if (gitChangesState.data?.remote?.diverged === true) return;
10601
11195
  const root = gitChangesState.data?.root || "the current repository";
10602
- if (!window.confirm(`Run git pull --ff-only in ${root}?`)) return;
11196
+ if (!(await appConfirmText(`Run git pull --ff-only in ${root}?`, { affected: root, confirmLabel: "Pull changes" }))) return;
10603
11197
 
10604
11198
  const requestSerial = ++gitChangesRequestSerial;
10605
11199
  gitChangesState = { ...gitChangesState, pulling: true, loading: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId };
@@ -10692,13 +11286,13 @@ async function integrateGitChangesDialog(mode) {
10692
11286
  const data = gitChangesState.data;
10693
11287
  const upstream = data?.remote?.upstream || "@{upstream}";
10694
11288
  const command = mode === "merge" ? `git merge --no-edit ${upstream}` : `git rebase ${upstream}`;
10695
- if (!window.confirm([
11289
+ if (!(await appConfirmText([
10696
11290
  `${mode === "merge" ? "Merge" : "Rebase onto"} ${upstream} in ${data?.root || "the current repository"}?`,
10697
11291
  "",
10698
11292
  `Command: ${command}`,
10699
11293
  mode === "rebase" ? "Rebase rewrites local commits. Conflicts open the conflicts panel." : "Conflicts open the conflicts panel.",
10700
11294
  "For risky integration, prefer a separate worktree instead.",
10701
- ].join("\n"))) return;
11295
+ ].join("\n"), { affected: data?.root || "the current repository", confirmLabel: mode === "merge" ? "Merge" : "Rebase" }))) return;
10702
11296
  gitChangesState = { ...gitChangesState, pulling: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null };
10703
11297
  renderGitChangesDialog();
10704
11298
  try {
@@ -10741,7 +11335,7 @@ async function runGitFileAction(action, path) {
10741
11335
  },
10742
11336
  }[action];
10743
11337
  if (!config) return;
10744
- if (config.confirm && !window.confirm(config.confirm)) return;
11338
+ if (config.confirm && !(await appConfirmText(config.confirm, { affected: path, confirmLabel: action }))) return;
10745
11339
  try {
10746
11340
  const response = await api(config.url, { method: "POST", body: config.body, tabId });
10747
11341
  if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || `git ${action} failed`);
@@ -10801,7 +11395,7 @@ async function runGitOperationRequest(url, body, successLabel) {
10801
11395
  function renderGitOperationPanel(operation) {
10802
11396
  const kind = operation?.operation;
10803
11397
  if (!kind) return null;
10804
- const busy = gitToolsState.busy.has("operation") || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
11398
+ const busy = gitToolsState.busy.has("operation") || gitToolsState.busy.has("conflict-agent") || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
10805
11399
  const conflicts = operation.conflicts || [];
10806
11400
  const panel = make("section", "git-operation-panel");
10807
11401
  const header = make("div", "git-operation-header");
@@ -10826,8 +11420,8 @@ function renderGitOperationPanel(operation) {
10826
11420
  reset.type = "button";
10827
11421
  reset.disabled = busy;
10828
11422
  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;
11423
+ reset.addEventListener("click", async () => {
11424
+ 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
11425
  runGitOperationRequest("/api/git-operation/bisect", { verdict: "reset", confirmed: true }, "Reset the bisect session");
10832
11426
  });
10833
11427
  row.append(reset);
@@ -10870,6 +11464,32 @@ function renderGitOperationPanel(operation) {
10870
11464
  refresh.addEventListener("click", refreshGitChangesDialog);
10871
11465
  row.append(refresh);
10872
11466
 
11467
+ if (conflicts.length) {
11468
+ const resolveWithAgent = make("button", "git-operation-button primary", "Resolve with agent");
11469
+ resolveWithAgent.type = "button";
11470
+ resolveWithAgent.disabled = busy;
11471
+ resolveWithAgent.title = `Open a new Pi tab in ${operation.root} and send it the ${kind} conflict context`;
11472
+ resolveWithAgent.addEventListener("click", async () => {
11473
+ const sourceTabId = gitChangesState.tabId || activeTabId;
11474
+ gitToolsState.busy.add("conflict-agent");
11475
+ renderGitChangesDialog();
11476
+ try {
11477
+ const response = await api("/api/git-operation/resolve-with-agent", { method: "POST", body: {}, tabId: sourceTabId });
11478
+ if (!response.ok) throw new Error(response.error || "Failed to open a conflict-resolution agent");
11479
+ closeGitChangesDialog();
11480
+ const targetTab = await switchToResponseTab(response);
11481
+ addEvent(`Opened ${targetTab?.title || "a new Pi tab"} and sent the ${kind} conflict context.`, "success");
11482
+ } catch (error) {
11483
+ gitChangesState = { ...gitChangesState, error: error.message || String(error) };
11484
+ renderGitChangesDialog();
11485
+ } finally {
11486
+ gitToolsState.busy.delete("conflict-agent");
11487
+ if (elements.gitChangesDialog?.open) renderGitChangesDialog();
11488
+ }
11489
+ });
11490
+ row.append(resolveWithAgent);
11491
+ }
11492
+
10873
11493
  const cont = make("button", "git-operation-button primary", kind === "merge" ? "Continue (commit merge)" : "Continue");
10874
11494
  cont.type = "button";
10875
11495
  cont.disabled = busy || operation.canContinue !== true;
@@ -10882,8 +11502,8 @@ function renderGitOperationPanel(operation) {
10882
11502
  skip.type = "button";
10883
11503
  skip.disabled = busy;
10884
11504
  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;
11505
+ skip.addEventListener("click", async () => {
11506
+ 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
11507
  runGitOperationRequest("/api/git-operation/skip", {}, `Skipped the current ${kind} step`);
10888
11508
  });
10889
11509
  row.append(skip);
@@ -10893,16 +11513,16 @@ function renderGitOperationPanel(operation) {
10893
11513
  abort.type = "button";
10894
11514
  abort.disabled = busy;
10895
11515
  abort.title = operation.commands?.abort || "";
10896
- abort.addEventListener("click", () => {
11516
+ abort.addEventListener("click", async () => {
10897
11517
  const summary = operation.summary || {};
10898
- if (!window.confirm([
11518
+ if (!(await appConfirmText([
10899
11519
  `Abort the ${kind} in ${operation.root}?`,
10900
11520
  "",
10901
11521
  `Command: ${operation.commands?.abort || `git ${kind} --abort`}`,
10902
11522
  `Working tree: ${summary.staged || 0} staged · ${summary.unstaged || 0} unstaged · ${conflicts.length} conflicted`,
10903
11523
  "",
10904
11524
  "This discards the in-progress operation state and returns to the pre-operation HEAD.",
10905
- ].join("\n"))) return;
11525
+ ].join("\n"), { affected: operation.root, confirmLabel: `Abort ${kind}` }))) return;
10906
11526
  runGitOperationRequest("/api/git-operation/abort", { confirmed: true }, `Aborted the ${kind}`);
10907
11527
  });
10908
11528
  row.append(abort);
@@ -10983,7 +11603,7 @@ async function loadGitToolsSection(key, { force = false } = {}) {
10983
11603
 
10984
11604
  async function runGitToolAction(sectionKey, { url, method = "POST", body, confirm, success, successMessage, refreshChanges = false }) {
10985
11605
  const tabId = gitChangesState.tabId || activeTabId;
10986
- if (confirm && !window.confirm(confirm)) return;
11606
+ if (confirm && !(await appConfirmText(confirm, { affected: gitChangesState.data?.root || "the current repository", confirmLabel: success || "Continue" }))) return;
10987
11607
  gitToolsState.busy.add(sectionKey);
10988
11608
  renderGitChangesDialog();
10989
11609
  try {
@@ -11025,13 +11645,13 @@ async function confirmGitStashActionWithPreview(stash, question) {
11025
11645
  } catch {
11026
11646
  // Preview is best-effort; the confirmation still shows the stash subject.
11027
11647
  }
11028
- return window.confirm([
11648
+ return appConfirmText([
11029
11649
  question,
11030
11650
  "",
11031
11651
  stash.subject || stash.ref,
11032
11652
  "",
11033
11653
  statText ? `Preview (git stash show --stat):\n${statText.slice(0, 2000)}` : "Preview unavailable.",
11034
- ].join("\n"));
11654
+ ].join("\n"), { affected: stash.subject || stash.ref, confirmLabel: "Continue" });
11035
11655
  }
11036
11656
 
11037
11657
  function renderGitStashTools(body, data, busy) {
@@ -11951,7 +12571,7 @@ function footerBranchDirtySummaryLines() {
11951
12571
  ];
11952
12572
  }
11953
12573
 
11954
- function confirmFooterGitBranchAction(branch, { create = false, requireConfirm = false, tabContext = activeTabContext() } = {}) {
12574
+ async function confirmFooterGitBranchAction(branch, { create = false, requireConfirm = false, tabContext = activeTabContext() } = {}) {
11955
12575
  const branchName = cleanStatusText(branch);
11956
12576
  const warningLines = footerBranchAgentWarningLines(tabContext);
11957
12577
  const dirtyLines = footerBranchDirtySummaryLines();
@@ -11966,10 +12586,10 @@ function confirmFooterGitBranchAction(branch, { create = false, requireConfirm =
11966
12586
  "",
11967
12587
  "Continue?",
11968
12588
  ].join("\n");
11969
- return window.confirm(message);
12589
+ return appConfirmText(message, { affected: branchName || "the current branch", confirmLabel: create ? "Create branch" : "Switch branch" });
11970
12590
  }
11971
12591
 
11972
- function confirmFooterGitWorktreeAction(branch, { path = "", create = false, requireConfirm = false } = {}) {
12592
+ async function confirmFooterGitWorktreeAction(branch, { path = "", create = false, requireConfirm = false } = {}) {
11973
12593
  const branchName = cleanStatusText(branch);
11974
12594
  if (!requireConfirm) return true;
11975
12595
  const targetPath = cleanFooterPayloadText(path, "", 4000);
@@ -11984,7 +12604,7 @@ function confirmFooterGitWorktreeAction(branch, { path = "", create = false, req
11984
12604
  "",
11985
12605
  "Continue?",
11986
12606
  ].join("\n");
11987
- return window.confirm(message);
12607
+ return appConfirmText(message, { affected: targetPath || branchName, confirmLabel: create ? "Create worktree" : "Open worktree", danger: false });
11988
12608
  }
11989
12609
 
11990
12610
  function footerBranchCreateType(value = footerBranchCreateDraft.type) {
@@ -12075,7 +12695,7 @@ async function createFooterGitBranch(branch = footerBranchCreateName()) {
12075
12695
  return;
12076
12696
  }
12077
12697
  const tabContext = activeTabContext();
12078
- if (!confirmFooterGitBranchAction(branchName, { create: true, requireConfirm: true, tabContext })) return;
12698
+ if (!(await confirmFooterGitBranchAction(branchName, { create: true, requireConfirm: true, tabContext }))) return;
12079
12699
  await applyFooterGitBranch(branchName, { create: true, tabContext, skipConfirm: true });
12080
12700
  }
12081
12701
 
@@ -12108,7 +12728,7 @@ async function createFooterGitBranchWorktree(branch = footerBranchCreateName(),
12108
12728
  addEvent("Enter a branch name before creating a branch worktree.", "warn");
12109
12729
  return;
12110
12730
  }
12111
- if (!skipConfirm && !confirmFooterGitWorktreeAction(branchName, { create: true, requireConfirm: true })) return;
12731
+ if (!skipConfirm && !(await confirmFooterGitWorktreeAction(branchName, { create: true, requireConfirm: true }))) return;
12112
12732
  const tabId = tabContext.tabId || activeTabId;
12113
12733
  try {
12114
12734
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName, tabId };
@@ -12128,7 +12748,7 @@ async function createFooterGitBranchWorktree(branch = footerBranchCreateName(),
12128
12748
  async function openFooterGitWorktree(path, { branchName = "", tabContext = activeTabContext(), skipConfirm = false } = {}) {
12129
12749
  const worktreePath = cleanFooterPayloadText(path, "", 4000);
12130
12750
  if (!worktreePath) return;
12131
- if (!skipConfirm && !confirmFooterGitWorktreeAction(branchName, { path: worktreePath, requireConfirm: false })) return;
12751
+ if (!skipConfirm && !(await confirmFooterGitWorktreeAction(branchName, { path: worktreePath, requireConfirm: false }))) return;
12132
12752
  const tabId = tabContext.tabId || activeTabId;
12133
12753
  try {
12134
12754
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName || worktreePath, tabId };
@@ -12149,7 +12769,7 @@ async function applyFooterGitBranch(branch, { create = false, tabContext = activ
12149
12769
  const branchName = cleanStatusText(branch);
12150
12770
  if (!branchName) return;
12151
12771
  const tabId = tabContext.tabId || activeTabId;
12152
- if (!skipConfirm && !confirmFooterGitBranchAction(branchName, { create, tabContext })) return;
12772
+ if (!skipConfirm && !(await confirmFooterGitBranchAction(branchName, { create, tabContext }))) return;
12153
12773
  try {
12154
12774
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName, tabId };
12155
12775
  renderFooter();
@@ -12350,13 +12970,13 @@ function renderFooterBranchOption(branch, state = footerBranchPickerState) {
12350
12970
 
12351
12971
  async function removeFooterGitWorktree(worktree, tabContext = activeTabContext()) {
12352
12972
  const tabId = tabContext.tabId || activeTabId;
12353
- if (!window.confirm([
12973
+ if (!(await appConfirmText([
12354
12974
  `Remove worktree ${worktree.path}?`,
12355
12975
  "",
12356
12976
  `Branch: ${worktree.branch || "detached"}`,
12357
12977
  "Command: git worktree remove",
12358
12978
  "This deletes the checkout directory. Dirty worktrees and worktrees with open tabs are refused.",
12359
- ].join("\n"))) return;
12979
+ ].join("\n"), { affected: worktree.path, confirmLabel: "Remove worktree" }))) return;
12360
12980
  footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "" };
12361
12981
  renderFooter();
12362
12982
  try {
@@ -12381,7 +13001,7 @@ async function pruneFooterGitWorktrees(tabContext = activeTabContext()) {
12381
13001
  return;
12382
13002
  }
12383
13003
  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;
13004
+ 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
13005
  const response = await api("/api/git-worktrees/prune", { method: "POST", body: { confirmed: true }, tabId });
12386
13006
  if (!response.ok) throw new Error(response.error || "Failed to prune worktrees");
12387
13007
  addEvent("Pruned stale worktree records.", "success");
@@ -13115,7 +13735,7 @@ async function changeActiveTabCwd() {
13115
13735
  return;
13116
13736
  }
13117
13737
 
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;
13738
+ 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
13739
 
13120
13740
  saveActiveDraft();
13121
13741
  try {
@@ -13819,12 +14439,62 @@ function initializeSubagents() {
13819
14439
  refreshSubagents().finally(() => scheduleRefreshSubagents());
13820
14440
  }
13821
14441
 
14442
+ function sessionCopyButton(label, value) {
14443
+ const button = make("button", "session-copy-button", "Copy");
14444
+ button.type = "button";
14445
+ button.title = `Copy ${label.toLowerCase()}`;
14446
+ button.setAttribute("aria-label", button.title);
14447
+ button.addEventListener("click", async () => {
14448
+ const original = button.textContent;
14449
+ try {
14450
+ await copyText(value);
14451
+ button.textContent = "Copied";
14452
+ button.classList.add("copied");
14453
+ } catch {
14454
+ button.textContent = "Failed";
14455
+ }
14456
+ setTimeout(() => {
14457
+ if (!button.isConnected) return;
14458
+ button.textContent = original;
14459
+ button.classList.remove("copied");
14460
+ }, 1400);
14461
+ });
14462
+ return button;
14463
+ }
14464
+
14465
+ function sessionDetailField(label, value, { secondary = "", copyValue = "", mono = false, truncate = false, wide = false } = {}) {
14466
+ const field = make("div", `session-detail-field${wide ? " wide" : ""}`);
14467
+ const labelNode = make("span", "session-detail-label", label);
14468
+ const valueRow = make("div", "session-detail-value-row");
14469
+ const valueCopy = make("div", `session-detail-value${mono ? " mono" : ""}${truncate ? " truncate" : ""}`);
14470
+ const primary = make("span", "session-detail-primary", value);
14471
+ primary.title = copyValue || value;
14472
+ valueCopy.append(primary);
14473
+ if (secondary) {
14474
+ const secondaryNode = make("span", "session-detail-secondary", secondary);
14475
+ secondaryNode.title = copyValue || secondary;
14476
+ valueCopy.append(secondaryNode);
14477
+ }
14478
+ valueRow.append(valueCopy);
14479
+ if (copyValue) valueRow.append(sessionCopyButton(label, copyValue));
14480
+ field.append(labelNode, valueRow);
14481
+ return field;
14482
+ }
14483
+
14484
+ function splitSessionFilePath(sessionFile) {
14485
+ const value = String(sessionFile || "");
14486
+ const separator = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
14487
+ if (separator < 0) return { name: value || "in-memory", directory: "" };
14488
+ const directory = value.slice(0, separator).replace(/^\/home\/[^/]+(?=\/|$)/, "~");
14489
+ return { name: value.slice(separator + 1) || value, directory };
14490
+ }
14491
+
13822
14492
  function renderStatus() {
13823
14493
  if (deferUiRenderDuringPointerActivation("status", renderStatus)) return;
13824
14494
  const state = currentState;
13825
14495
  updateComposerModeButtons();
13826
- const running = state?.isStreaming ? "running" : "idle";
13827
- const compacting = state?.isCompacting ? " · compacting" : "";
14496
+ const statusKey = state?.isCompacting ? "compacting" : state?.isStreaming ? "running" : "idle";
14497
+ const statusLabel = statusKey[0].toUpperCase() + statusKey.slice(1);
13828
14498
 
13829
14499
  elements.stateDetails.replaceChildren();
13830
14500
  const pendingThinkingLevel = state?.pendingThinkingLevel || null;
@@ -13832,19 +14502,43 @@ function renderStatus() {
13832
14502
  const thinkingDetail = pendingThinkingLevel && pendingThinkingLevel !== state?.thinkingLevel
13833
14503
  ? `${state?.thinkingLevel || "unknown"} → ${pendingThinkingLevel} next prompt`
13834
14504
  : 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
- }
14505
+ const overview = make("div", "session-overview");
14506
+ const statusCard = make("div", `session-status-card ${statusKey}`);
14507
+ const statusDot = make("span", "session-status-dot");
14508
+ statusDot.setAttribute("aria-hidden", "true");
14509
+ const statusCopy = make("span", "session-overview-copy");
14510
+ statusCopy.append(make("span", "session-overview-label", "Status"), make("strong", undefined, statusLabel));
14511
+ statusCard.append(statusDot, statusCopy);
14512
+ const messagesCard = make("div", "session-metric-card");
14513
+ messagesCard.append(make("span", "session-overview-label", "Messages"), make("strong", undefined, String(state?.messageCount ?? "?")));
14514
+ const queueCard = make("div", "session-metric-card");
14515
+ queueCard.append(make("span", "session-overview-label", "Queue"), make("strong", undefined, String(state?.pendingMessageCount ?? 0)));
14516
+ overview.append(statusCard, messagesCard, queueCard);
14517
+
14518
+ const sessionId = state?.sessionId || "unknown";
14519
+ const sessionName = state?.sessionName && state.sessionName !== sessionId ? state.sessionName : "";
14520
+ const sessionFile = state?.sessionFile || "";
14521
+ const fileParts = splitSessionFilePath(sessionFile);
14522
+ const infoGrid = make("div", "session-info-grid");
14523
+ infoGrid.append(
14524
+ sessionDetailField("Model", modelLabel(state?.model), { wide: true, truncate: true }),
14525
+ sessionDetailField("Thinking", thinkingDetail, { truncate: true }),
14526
+ sessionDetailField("Auto compact", footerAutoCompactionEnabled(state) ? "On" : "Off"),
14527
+ sessionDetailField("Session ID", sessionName || sessionId, {
14528
+ secondary: sessionName ? sessionId : "",
14529
+ copyValue: sessionId !== "unknown" ? sessionId : "",
14530
+ mono: !sessionName,
14531
+ wide: true,
14532
+ }),
14533
+ sessionDetailField("Session file", fileParts.name, {
14534
+ secondary: fileParts.directory,
14535
+ copyValue: sessionFile,
14536
+ mono: true,
14537
+ truncate: true,
14538
+ wide: true,
14539
+ }),
14540
+ );
14541
+ elements.stateDetails.append(overview, infoGrid);
13848
14542
 
13849
14543
  if (shownThinkingLevel) elements.thinkingSelect.value = shownThinkingLevel;
13850
14544
  elements.compactButton.disabled = !!state?.isCompacting;
@@ -14401,6 +15095,191 @@ function renderReleaseAurLogWidget() {
14401
15095
  return node;
14402
15096
  }
14403
15097
 
15098
+ function parseWorkflowInspectorPayload(lines) {
15099
+ const raw = String(lines?.[0] || "").trim();
15100
+ if (!raw.startsWith(WORKFLOW_INSPECTOR_PAYLOAD_PREFIX)) return null;
15101
+ try {
15102
+ const payload = JSON.parse(raw.slice(WORKFLOW_INSPECTOR_PAYLOAD_PREFIX.length));
15103
+ if (payload?.type !== WORKFLOW_INSPECTOR_PAYLOAD_TYPE || payload.version !== WORKFLOW_INSPECTOR_PAYLOAD_VERSION || !Array.isArray(payload.runs)) return null;
15104
+ if (!payload.runs.every((run) => run && typeof run.runId === "string" && Array.isArray(run.phases) && run.controls && typeof run.controls === "object")) return null;
15105
+ return payload;
15106
+ } catch {
15107
+ return null;
15108
+ }
15109
+ }
15110
+
15111
+ function updateWorkflowInspectorForTab(tabId, payload) {
15112
+ if (!tabId || !payload) return;
15113
+ workflowInspectorByTab.set(tabId, payload);
15114
+ if (payload.mode) updateWorkflowModeForTab(tabId, { ...payload.mode, available: true, updatedAt: payload.updatedAt }, { render: tabId === activeTabId });
15115
+ const selection = workflowInspectorSelectionByTab.get(tabId) || {};
15116
+ if (selection.runId && !payload.runs.some((run) => run.runId === selection.runId)) workflowInspectorSelectionByTab.delete(tabId);
15117
+ }
15118
+
15119
+ function activeWorkflowInspectorPayload() {
15120
+ const cached = workflowInspectorByTab.get(activeTabId);
15121
+ if (cached) return cached;
15122
+ const parsed = parseWorkflowInspectorPayload(getWidgetLines(WORKFLOW_INSPECTOR_WIDGET_KEY));
15123
+ if (parsed && activeTabId) updateWorkflowInspectorForTab(activeTabId, parsed);
15124
+ return parsed;
15125
+ }
15126
+
15127
+ function workflowRunIsLive(run) {
15128
+ return ["queued", "validating", "awaiting_approval", "running", "paused"].includes(run?.status);
15129
+ }
15130
+
15131
+ function workflowRunningCountForTab(tabId) {
15132
+ const payload = workflowInspectorByTab.get(tabId);
15133
+ return Array.isArray(payload?.runs) ? payload.runs.filter(workflowRunIsLive).length : 0;
15134
+ }
15135
+
15136
+ function workflowInspectorSelection(payload) {
15137
+ const existing = workflowInspectorSelectionByTab.get(activeTabId) || {};
15138
+ const run = payload.runs.find((candidate) => candidate.runId === existing.runId)
15139
+ || payload.runs.find(workflowRunIsLive)
15140
+ || payload.runs[0];
15141
+ const phase = run?.phases?.find((candidate) => candidate.phaseId === existing.phaseId) || run?.phases?.[0];
15142
+ const agent = phase?.agents?.find((candidate) => candidate.callId === existing.callId) || phase?.agents?.[0];
15143
+ const next = { runId: run?.runId || "", phaseId: phase?.phaseId || "", callId: agent?.callId || "" };
15144
+ if (activeTabId) workflowInspectorSelectionByTab.set(activeTabId, next);
15145
+ return { run, phase, agent, selection: next };
15146
+ }
15147
+
15148
+ function workflowInspectorSetSelection(patch) {
15149
+ if (!activeTabId) return;
15150
+ workflowInspectorSelectionByTab.set(activeTabId, { ...(workflowInspectorSelectionByTab.get(activeTabId) || {}), ...patch });
15151
+ renderWidgets();
15152
+ }
15153
+
15154
+ function workflowInspectorJson(value) {
15155
+ if (value === undefined) return "—";
15156
+ if (typeof value === "string") return value;
15157
+ try { return JSON.stringify(value, null, 2); } catch { return String(value); }
15158
+ }
15159
+
15160
+ async function sendWorkflowInspectorCommand(command, { confirmMessage = "" } = {}) {
15161
+ const tabContext = activeTabContext();
15162
+ if (!tabContext.tabId || !command) return;
15163
+ if (confirmMessage && !window.confirm(confirmMessage)) return;
15164
+ try {
15165
+ await sendPrompt("prompt", command, { targetTabId: tabContext.tabId, throwOnError: true });
15166
+ if (isCurrentTabContext(tabContext)) addEvent(`workflow action sent: ${command}`, "info");
15167
+ } catch (error) {
15168
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
15169
+ }
15170
+ }
15171
+
15172
+ function workflowInspectorActionButton(label, command, { danger = false, confirmMessage = "" } = {}) {
15173
+ const button = make("button", `release-npm-action${danger ? " danger" : ""}`, label);
15174
+ button.type = "button";
15175
+ button.addEventListener("click", () => void sendWorkflowInspectorCommand(command, { confirmMessage }));
15176
+ return button;
15177
+ }
15178
+
15179
+ function renderWorkflowInspectorAgent(agent, run) {
15180
+ const details = make("details", "workflow-inspector-agent");
15181
+ const summary = make("summary", "workflow-inspector-agent-summary");
15182
+ summary.append(
15183
+ make("span", `workflow-inspector-status status-${agent.status || "unknown"}`, agent.status || "unknown"),
15184
+ make("strong", undefined, agent.name || agent.label || agent.taskId || agent.callId),
15185
+ );
15186
+ details.append(summary);
15187
+ const body = make("div", "workflow-inspector-agent-body");
15188
+ const prompt = make("details", "workflow-inspector-block");
15189
+ prompt.append(make("summary", undefined, "Prompt"), make("pre", undefined, agent.prompt || "—"));
15190
+ body.append(prompt);
15191
+ if (Array.isArray(agent.recentEvents) && agent.recentEvents.length) {
15192
+ const activity = make("details", "workflow-inspector-block");
15193
+ activity.append(make("summary", undefined, `Recent activity (${agent.recentEvents.length})`));
15194
+ 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")));
15195
+ body.append(activity);
15196
+ }
15197
+ const result = make("details", "workflow-inspector-block");
15198
+ 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}` : ""}`));
15199
+ body.append(result);
15200
+ if (run.controls?.canRetry) {
15201
+ const controls = make("div", "workflow-inspector-inline-actions");
15202
+ controls.append(workflowInspectorActionButton("Retry agent", `/workflow retry ${run.runId} ${agent.callId}`, {
15203
+ confirmMessage: `Retry ${agent.name || agent.callId}? Unrelated completed calls will remain cached.`,
15204
+ }));
15205
+ body.append(controls);
15206
+ }
15207
+ details.append(body);
15208
+ return details;
15209
+ }
15210
+
15211
+ function renderWorkflowInspectorWidget() {
15212
+ if (!isOptionalFeatureEnabled("workflows")) return null;
15213
+ const payload = activeWorkflowInspectorPayload();
15214
+ if (!payload?.runs?.length) return null;
15215
+ const { run, phase } = workflowInspectorSelection(payload);
15216
+ if (!run) return null;
15217
+
15218
+ const node = make("section", "widget release-npm-widget workflow-widget workflow-inspector-widget");
15219
+ node.setAttribute("aria-label", "workflow run inspector");
15220
+ const header = make("div", "release-npm-header");
15221
+ const titleWrap = make("div", "release-npm-title-wrap");
15222
+ titleWrap.append(make("span", "release-npm-kicker", "workflows"), make("strong", "release-npm-title", `${payload.runs.length} run${payload.runs.length === 1 ? "" : "s"}`));
15223
+ const meta = make("div", "release-npm-meta");
15224
+ meta.append(make("span", "release-npm-pill", payload.mode?.enabled ? `mode ${payload.mode.phase}` : "mode off"));
15225
+ const liveCount = payload.runs.filter(workflowRunIsLive).length;
15226
+ if (liveCount) meta.append(make("span", "release-npm-pill workflow-status running", `${liveCount} active`));
15227
+ header.append(titleWrap, meta);
15228
+
15229
+ const layout = make("div", "workflow-inspector-layout");
15230
+ const runList = make("nav", "workflow-inspector-run-list");
15231
+ runList.setAttribute("aria-label", "Workflow runs");
15232
+ for (const candidate of payload.runs) {
15233
+ const button = make("button", `workflow-inspector-run${candidate.runId === run.runId ? " active" : ""}`);
15234
+ button.type = "button";
15235
+ button.append(make("span", `workflow-inspector-status status-${candidate.status}`, candidate.status), make("strong", undefined, candidate.workflowName || candidate.workflowKey), make("small", undefined, candidate.runId));
15236
+ button.addEventListener("click", () => workflowInspectorSetSelection({ runId: candidate.runId, phaseId: "", callId: "" }));
15237
+ runList.append(button);
15238
+ }
15239
+
15240
+ const detail = make("div", "workflow-inspector-detail");
15241
+ const runHeader = make("div", "workflow-inspector-run-header");
15242
+ runHeader.append(make("div", undefined, `${run.workflowName || run.workflowKey}\n${run.runId}`));
15243
+ const actions = make("div", "release-npm-actions workflow-inspector-actions");
15244
+ if (run.controls?.canPause) actions.append(workflowInspectorActionButton("Pause", `/workflow pause ${run.runId}`));
15245
+ if (run.status === "paused") actions.append(workflowInspectorActionButton("Resume", `/workflow resume ${run.runId}`));
15246
+ else if (run.controls?.canResume) actions.append(workflowInspectorActionButton("Replay", `/workflow resume ${run.runId}`, { confirmMessage: `Replay ${run.workflowName || run.runId}?` }));
15247
+ if (run.controls?.canAbort) actions.append(workflowInspectorActionButton("Abort", `/workflow abort ${run.runId}`, { danger: true, confirmMessage: `Abort ${run.workflowName || run.runId} and active subprocesses?` }));
15248
+ if (run.controls?.canSave) {
15249
+ actions.append(workflowInspectorActionButton("Save user", `/workflow save ${run.runId} --user`));
15250
+ actions.append(workflowInspectorActionButton("Save project", `/workflow save ${run.runId} --project`));
15251
+ }
15252
+ runHeader.append(actions);
15253
+ detail.append(runHeader);
15254
+ 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}` : ""}`);
15255
+ detail.append(summary);
15256
+
15257
+ if (run.phases?.length) {
15258
+ const phaseTabs = make("div", "workflow-inspector-phase-tabs");
15259
+ for (const candidate of run.phases) {
15260
+ const button = make("button", `workflow-inspector-phase-tab${candidate.phaseId === phase?.phaseId ? " active" : ""}`, `${candidate.name} · ${candidate.status}`);
15261
+ button.type = "button";
15262
+ button.addEventListener("click", () => workflowInspectorSetSelection({ phaseId: candidate.phaseId, callId: "" }));
15263
+ phaseTabs.append(button);
15264
+ }
15265
+ detail.append(phaseTabs);
15266
+ if (phase) {
15267
+ const agents = make("div", "workflow-inspector-agent-list");
15268
+ for (const agent of phase.agents || []) agents.append(renderWorkflowInspectorAgent(agent, run));
15269
+ if (!phase.agents?.length) agents.append(make("p", "muted", "This phase has no agent calls."));
15270
+ detail.append(agents);
15271
+ }
15272
+ }
15273
+ if (run.script) {
15274
+ const raw = make("details", "workflow-inspector-raw-script");
15275
+ raw.append(make("summary", undefined, "Raw workflow script"), make("pre", undefined, run.script));
15276
+ detail.append(raw);
15277
+ }
15278
+ layout.append(runList, detail);
15279
+ node.append(header, layout);
15280
+ return node;
15281
+ }
15282
+
14404
15283
  function parseWorkflowSubprocessPayload(lines) {
14405
15284
  const raw = String(lines?.[0] || "").trim();
14406
15285
  if (!raw) return null;
@@ -14871,7 +15750,16 @@ async function saveAppRunnerCustomRunner(form) {
14871
15750
  }
14872
15751
  }
14873
15752
 
14874
- async function deleteAppRunnerCustomRunner(id) {
15753
+ async function deleteAppRunnerCustomRunner(runner = {}) {
15754
+ const id = String(runner.id || "");
15755
+ if (!id) return;
15756
+ const restoreRunner = {
15757
+ id,
15758
+ label: runner.label || "",
15759
+ command: runner.command || "./",
15760
+ path: runner.path || "",
15761
+ args: appRunnerCustomArgsText(runner.args),
15762
+ };
14875
15763
  const tabContext = activeTabContext();
14876
15764
  try {
14877
15765
  const response = await api("/api/app-runner-config", { method: "DELETE", body: { id }, tabId: tabContext.tabId });
@@ -14883,6 +15771,20 @@ async function deleteAppRunnerCustomRunner(id) {
14883
15771
  renderWidgets();
14884
15772
  renderAppRunnerInfoDialog();
14885
15773
  addEvent("deleted custom app runner", "warn");
15774
+ offerUndo({
15775
+ message: `Deleted custom app runner “${runner.label || runner.path || id}”.`,
15776
+ undo: async () => {
15777
+ const restored = await api("/api/app-runner-config", { method: "POST", body: { runner: restoreRunner }, tabId: tabContext.tabId });
15778
+ if (isCurrentTabContext(tabContext)) {
15779
+ setAppRunnerData(tabContext.tabId, restored.data || {});
15780
+ setAppRunnerCustomFeedback("success", "Restored custom app runner.");
15781
+ renderAppRunnerControls();
15782
+ renderWidgets();
15783
+ renderAppRunnerInfoDialog();
15784
+ }
15785
+ },
15786
+ successMessage: `Restored custom app runner “${runner.label || runner.path || id}”.`,
15787
+ });
14886
15788
  } catch (error) {
14887
15789
  if (!isCurrentTabContext(tabContext)) return;
14888
15790
  const message = error.message || String(error);
@@ -14987,10 +15889,7 @@ function renderAppRunnerCustomSection() {
14987
15889
  });
14988
15890
  const remove = make("button", "danger", "Delete");
14989
15891
  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
- });
15892
+ remove.addEventListener("click", () => deleteAppRunnerCustomRunner(runner));
14994
15893
  actions.append(edit, remove);
14995
15894
  row.append(details, actions);
14996
15895
  existing.append(row);
@@ -15596,7 +16495,7 @@ async function runStatsCalibration(mode) {
15596
16495
  renderStatsOverlay();
15597
16496
  return;
15598
16497
  }
15599
- if (mode === "probe" && !confirm("Start an isolated calibration probe? This sends one tiny model request and may incur provider token usage.")) return;
16498
+ 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
16499
 
15601
16500
  const command = mode === "current" ? `/${commandName} current` : `/${commandName}`;
15602
16501
  statsOverlayCalibrationBusy = mode;
@@ -16320,6 +17219,8 @@ function renderWidgets() {
16320
17219
  if (releaseAurOutput) elements.widgetArea.append(releaseAurOutput);
16321
17220
  const releaseAurLog = renderReleaseAurLogWidget();
16322
17221
  if (releaseAurLog) elements.widgetArea.append(releaseAurLog);
17222
+ const workflowInspectorWidget = renderWorkflowInspectorWidget();
17223
+ if (workflowInspectorWidget) elements.widgetArea.append(workflowInspectorWidget);
16323
17224
  const workflowSubprocessWidget = renderWorkflowSubprocessWidget();
16324
17225
  if (workflowSubprocessWidget) elements.widgetArea.append(workflowSubprocessWidget);
16325
17226
  const appRunnerWidget = renderAppRunnerWidget();
@@ -17100,8 +18001,9 @@ async function gitWorkflowRequest(path, { method = "POST", body = {}, runId, tab
17100
18001
  }
17101
18002
  if (expectedRunId !== undefined && !isCurrentGitWorkflowRun(expectedRunId, tabId)) return null;
17102
18003
  if (!response.ok) {
18004
+ const hint = response.hint ? `\n\nHint: ${response.hint}` : "";
17103
18005
  const detail = response.data ? `\n\n${formatGitCommandResult(response.data)}` : "";
17104
- throw new Error(`${response.error || "Git workflow request failed"}${detail}`);
18006
+ throw new Error(`${response.error || "Git workflow request failed"}${hint}${detail}`);
17105
18007
  }
17106
18008
  return response.data;
17107
18009
  }
@@ -17160,7 +18062,7 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
17160
18062
  }
17161
18063
 
17162
18064
  const workflow = gitWorkflowForTab(tabId);
17163
- if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !confirm("Restart the active git workflow?")) return;
18065
+ 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
18066
  const preferences = setupData.preferences;
17165
18067
  workflow.runId += 1;
17166
18068
  setGitWorkflow({
@@ -17194,10 +18096,10 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
17194
18096
  }, { tabId });
17195
18097
  }
17196
18098
 
17197
- function startGitInitWorkflow(tabId = activeTabId) {
18099
+ async function startGitInitWorkflow(tabId = activeTabId) {
17198
18100
  if (!tabId) return;
17199
18101
  const workflow = gitWorkflowForTab(tabId);
17200
- if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !confirm("Restart the active git repository setup workflow?")) return;
18102
+ 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
18103
  const setup = readGitFooterStatusSetup().githubUsername ? readGitFooterStatusSetup() : configureGitFooterStatusSetup({ force: true });
17202
18104
  const githubUsername = setup?.githubUsername || "";
17203
18105
  const repoName = defaultGitInitRepoName(tabs.find((tab) => tab.id === tabId) || activeTab());
@@ -17847,14 +18749,14 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
17847
18749
  const failureStep = variant === "input" && workflow.step === "generate" ? "generate" : "message";
17848
18750
  const inputMessage = variant === "input" ? gitWorkflowManualCommitInputMessage(workflow) : "";
17849
18751
  if (workflow.preferences?.verificationPolicy === "ask" && !workflow.verificationConfirmed) {
17850
- const proceed = window.confirm([
18752
+ const proceed = await appConfirmText([
17851
18753
  "Pre-commit verification reminder",
17852
18754
  "",
17853
18755
  "Review the staged diff and any relevant test, lint, or build results before committing.",
17854
18756
  "Git hooks and signing configuration will still run normally.",
17855
18757
  "",
17856
18758
  "Continue with this commit?",
17857
- ].join("\n"));
18759
+ ].join("\n"), { affected: "The staged Git changes", confirmLabel: "Continue to commit" });
17858
18760
  if (!proceed) return;
17859
18761
  workflow.verificationConfirmed = true;
17860
18762
  }
@@ -17883,7 +18785,7 @@ async function pushGitWorkflow(tabId = gitWorkflowActionTabId()) {
17883
18785
  const tabContext = activeTabContext(tabId);
17884
18786
  const workflow = gitWorkflowForTab(tabId, { create: false });
17885
18787
  if (!workflow) return;
17886
- if (!window.confirm("Push the committed changes to the configured upstream?\n\nGuided Git never force-pushes automatically.")) return;
18788
+ 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
18789
  const runId = workflow.runId;
17888
18790
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: "Running git push…" }, { tabId });
17889
18791
  try {
@@ -17975,7 +18877,7 @@ async function pushAndCreatePrGitWorkflow(tabId = gitWorkflowActionTabId()) {
17975
18877
  const workflow = gitWorkflowForTab(tabId, { create: false });
17976
18878
  if (!workflow) return;
17977
18879
  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;
18880
+ 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
18881
  const runId = workflow.runId;
17980
18882
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: `Pushing PR branch ${branch}…` }, { tabId });
17981
18883
  try {
@@ -18378,13 +19280,12 @@ function loadSelectedPromptListIntoEditor() {
18378
19280
  if (loadPromptListIntoEditor(list, { updateLoaded: true })) elements.promptListDialog?.close();
18379
19281
  }
18380
19282
 
18381
- function deleteSelectedPromptList() {
19283
+ async function deleteSelectedPromptList() {
18382
19284
  const list = savedPromptListById(elements.promptListSelect?.value);
18383
19285
  if (!list) {
18384
19286
  setPromptListStatus("No saved prompt list selected to delete.", "warn");
18385
19287
  return;
18386
19288
  }
18387
- if (!window.confirm(`Delete prompt list “${list.name}”? This cannot be undone.`)) return;
18388
19289
  const deleted = deleteStoredPromptList(list.id);
18389
19290
  if (!deleted) {
18390
19291
  setPromptListStatus("Prompt list was already deleted.", "warn");
@@ -18400,6 +19301,15 @@ function deleteSelectedPromptList() {
18400
19301
  populatePromptListSelect();
18401
19302
  setPromptListStatus(`Deleted “${deleted.name}”.`, "success");
18402
19303
  addEvent(`deleted prompt list “${deleted.name}”`);
19304
+ offerUndo({
19305
+ message: `Deleted prompt list “${deleted.name}”.`,
19306
+ undo: () => {
19307
+ upsertStoredPromptList(deleted);
19308
+ populatePromptListSelect(deleted.id);
19309
+ setPromptListStatus(`Restored “${deleted.name}”.`, "success");
19310
+ },
19311
+ successMessage: `Restored prompt list “${deleted.name}”.`,
19312
+ });
18403
19313
  }
18404
19314
 
18405
19315
  function openPromptListDialog({ mode = "create", list = null } = {}) {
@@ -19968,6 +20878,115 @@ function appendChatMessageBubble(bubble) {
19968
20878
  }
19969
20879
  }
19970
20880
 
20881
+ function emptyStartRecentWorkspaces() {
20882
+ const seen = new Set();
20883
+ return pathFastPicks.map((item) => {
20884
+ const cwd = typeof item === "string" ? item.trim() : typeof item?.cwd === "string" ? item.cwd.trim() : "";
20885
+ const rawLabel = typeof item === "string" ? item : typeof item?.displayCwd === "string" ? item.displayCwd : cwd;
20886
+ const label = String(rawLabel || "").trim();
20887
+ if (!cwd || !label || /^\[object Object\]$/i.test(label) || seen.has(cwd)) return null;
20888
+ seen.add(cwd);
20889
+ return { cwd, label: normalizeDisplayPath(label) };
20890
+ }).filter(Boolean).slice(0, 4);
20891
+ }
20892
+
20893
+ function emptyStartAction({ title, description, symbol, className = "", onClick }) {
20894
+ const button = make("button", `empty-start-action ${className}`.trim());
20895
+ button.type = "button";
20896
+ const icon = make("span", "empty-start-action-icon", symbol);
20897
+ icon.setAttribute("aria-hidden", "true");
20898
+ const copy = make("span", "empty-start-action-copy");
20899
+ copy.append(make("strong", undefined, title), make("span", undefined, description));
20900
+ const arrow = make("span", "empty-start-action-arrow", "→");
20901
+ arrow.setAttribute("aria-hidden", "true");
20902
+ button.append(icon, copy, arrow);
20903
+ button.addEventListener("click", () => onClick(button));
20904
+ return button;
20905
+ }
20906
+
20907
+ function renderEmptyStartState() {
20908
+ if (elements.chat.querySelector(".empty-start-state")) return;
20909
+ const tab = activeTab();
20910
+ const workspace = latestWorkspace?.displayCwd || (tab?.cwd ? normalizeDisplayPath(tab.cwd) : "");
20911
+ const workspaceInfo = normalizeGitWorkspaceInfo(tab?.gitWorkspace);
20912
+ const branch = workspaceInfo?.branch || "";
20913
+ const model = currentState?.model ? shortModelLabel(currentState.model) : "";
20914
+ const usage = contextUsageDisplay();
20915
+ const card = make("section", "empty-start-state");
20916
+ card.setAttribute("aria-labelledby", "emptyStartTitle");
20917
+
20918
+ const intro = make("header", "empty-start-intro");
20919
+ const mark = make("span", "empty-start-mark", "π");
20920
+ mark.setAttribute("aria-hidden", "true");
20921
+ const heading = make("div", "empty-start-heading");
20922
+ const title = make("h1", undefined, "Choose where to work");
20923
+ title.id = "emptyStartTitle";
20924
+ heading.append(title, make("p", undefined, "Open a workspace, return to a session, or isolate branch work. To start here, just type below."));
20925
+ intro.append(mark, heading);
20926
+
20927
+ const actions = make("div", "empty-start-actions");
20928
+ actions.append(
20929
+ emptyStartAction({
20930
+ title: "Open workspace",
20931
+ description: "Choose a folder for a new Pi tab",
20932
+ symbol: "+",
20933
+ className: "primary",
20934
+ onClick: (button) => createTerminalTabFromChosenDirectory({ triggerButton: button }),
20935
+ }),
20936
+ emptyStartAction({
20937
+ title: "Resume session",
20938
+ description: "Continue previous work and context",
20939
+ symbol: "↶",
20940
+ onClick: () => runNativeCommandMenu("/resume"),
20941
+ }),
20942
+ emptyStartAction({
20943
+ title: "Branch worktree",
20944
+ description: "Work on a branch in an isolated checkout",
20945
+ symbol: "⑂",
20946
+ className: "worktree",
20947
+ onClick: () => openBranchWorktreePicker(),
20948
+ }),
20949
+ );
20950
+
20951
+ const recentWorkspaces = emptyStartRecentWorkspaces();
20952
+ const recent = recentWorkspaces.length ? make("section", "empty-start-recent") : null;
20953
+ if (recent) {
20954
+ const recentHeading = make("div", "empty-start-section-heading");
20955
+ recentHeading.append(make("strong", undefined, "Recent workspaces"), make("span", undefined, `${recentWorkspaces.length} available`));
20956
+ const recentList = make("div", "empty-start-recent-list");
20957
+ for (const item of recentWorkspaces) {
20958
+ const button = make("button", "empty-start-recent-item");
20959
+ button.type = "button";
20960
+ button.title = `Open ${item.cwd}`;
20961
+ button.append(make("span", "empty-start-recent-icon", "▰"), make("span", "empty-start-recent-path", item.label), make("span", "empty-start-recent-arrow", "→"));
20962
+ button.addEventListener("click", () => createTerminalTab(item.cwd, { triggerButton: button }));
20963
+ recentList.append(button);
20964
+ }
20965
+ recent.append(recentHeading, recentList);
20966
+ }
20967
+
20968
+ const contextItems = [];
20969
+ if (workspace) contextItems.push(["Workspace", workspace]);
20970
+ if (branch) contextItems.push(["Branch", branch]);
20971
+ if (model) contextItems.push(["Model", model]);
20972
+ if (usage && !/^0(?:\.0+)?%/.test(usage)) contextItems.push(["Context", usage]);
20973
+ const context = contextItems.length ? make("footer", "empty-start-context") : null;
20974
+ if (context) {
20975
+ context.append(make("span", "empty-start-context-label", "Current"));
20976
+ for (const [label, value] of contextItems) {
20977
+ const item = make("span", "empty-start-context-item");
20978
+ item.append(make("span", undefined, label), make("strong", undefined, value));
20979
+ context.append(item);
20980
+ }
20981
+ }
20982
+
20983
+ card.append(intro, actions);
20984
+ if (recent) card.append(recent);
20985
+ if (context) card.append(context);
20986
+ appendChatMessageBubble(card);
20987
+ if (elements.workspaceDashboard) elements.workspaceDashboard.hidden = true;
20988
+ }
20989
+
19971
20990
  function userPromptTargets() {
19972
20991
  return [...elements.chat.querySelectorAll('.message[data-user-prompt="true"][data-message-index]')]
19973
20992
  .map((node) => {
@@ -20500,7 +21519,14 @@ function liveToolRunMessage(run) {
20500
21519
  };
20501
21520
  }
20502
21521
 
21522
+ function applyChatEventMetadata(bubble, message) {
21523
+ const timestamp = messageTimestampMs(message);
21524
+ if (timestamp > 0) bubble.dataset.chatTimestamp = String(timestamp);
21525
+ else bubble.removeAttribute("data-chat-timestamp");
21526
+ }
21527
+
20503
21528
  function applyToolExecutionBubbleState(bubble, message) {
21529
+ applyChatEventMetadata(bubble, message);
20504
21530
  const status = toolExecutionStatus(message);
20505
21531
  const nextClass = `tool-${status}`;
20506
21532
  if (bubble.dataset.toolStatus !== status || !bubble.classList.contains(nextClass)) {
@@ -20721,6 +21747,7 @@ function appendMessage(message, { streaming = false, messageIndex = -1, transien
20721
21747
  const role = String(message.role || "message");
20722
21748
  const safeRole = role.replace(/[^a-z0-9_-]/gi, "");
20723
21749
  const bubble = make("article", `message ${safeRole}${message.level ? ` ${message.level}` : ""}${streaming ? " streaming" : ""}${animateEntry ? " action-enter" : ""}`);
21750
+ applyChatEventMetadata(bubble, message);
20724
21751
  if (message.role === "toolExecution") applyToolExecutionBubbleState(bubble, message);
20725
21752
  if (!transient && messageIndex >= 0) {
20726
21753
  bubble.dataset.messageIndex = String(messageIndex);
@@ -21264,6 +22291,8 @@ function renderAllMessages({ preserveScroll = false, forceRebuild = false } = {}
21264
22291
  });
21265
22292
  }
21266
22293
  pruneDisconnectedLiveToolCards();
22294
+ if (nextEntries.length === 0 && !runIndicatorIsActive()) renderEmptyStartState();
22295
+ else if (elements.workspaceDashboard) elements.workspaceDashboard.hidden = workspaceDashboardCollapsed;
21267
22296
  renderedTranscriptState = { epoch, entries: nextEntries.map(({ key, sig }) => ({ key, sig })) };
21268
22297
  rememberActionEntries(transcriptItems);
21269
22298
  applyToolOutputExpansionToDom();
@@ -21300,7 +22329,7 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
21300
22329
  });
21301
22330
  }
21302
22331
 
21303
- if (data.download && handleNativeDownloadResponse(data.download, data.command)) {
22332
+ if (data.download && handleNativeDownloadResponse(data.download, data.command, data.serverPath)) {
21304
22333
  addEvent(data.command === "export" ? `export ready: ${data.download.fileName || data.download.url}` : `download started: ${data.download.fileName || data.download.url}`, "info");
21305
22334
  }
21306
22335
 
@@ -21772,7 +22801,7 @@ function updateOptionalFeatureAvailability() {
21772
22801
  optionalFeatureAvailability.releaseNpm = hasAvailableCommand("release-npm");
21773
22802
  optionalFeatureAvailability.releaseAur = hasAvailableCommand("release-aur");
21774
22803
  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");
22804
+ optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || hasAvailableCommand("safety-guard-setup") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
21776
22805
  optionalFeatureAvailability.statsCommand = hasAvailableCommand("stats");
21777
22806
  optionalFeatureAvailability.gitFooterStatus = hasAvailableCommand("git-footer-refresh") || hasAvailableCommand("git-footer-visibility") || optionalFeatureAvailability.gitFooterStatus || statusEntries.has("git-footer") || statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY);
21778
22807
  optionalFeatureAvailability.tuiSkillsCommand = hasLoadedRpcCommand("skills");
@@ -21846,7 +22875,7 @@ function optionalFeatureWidgetFeatureId(key) {
21846
22875
  }
21847
22876
 
21848
22877
  function optionalFeatureWidgetHasSpecializedRenderer(key) {
21849
- return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === "workflow:subprocess";
22878
+ return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === "workflow:subprocess" || key === WORKFLOW_INSPECTOR_WIDGET_KEY;
21850
22879
  }
21851
22880
 
21852
22881
  function renderOptionalFeaturePanel() {
@@ -21961,7 +22990,15 @@ function renderOptionalFeatureRow(feature) {
21961
22990
  action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
21962
22991
  } else if (detected) {
21963
22992
  action.textContent = enabled ? "Disable" : "Enable";
21964
- action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, enabled));
22993
+ action.addEventListener("click", () => {
22994
+ const disabled = enabled;
22995
+ setOptionalFeatureDisabled(feature.id, disabled);
22996
+ offerUndo({
22997
+ message: `${feature.label} was ${disabled ? "disabled" : "enabled"}.`,
22998
+ undo: () => setOptionalFeatureDisabled(feature.id, !disabled),
22999
+ successMessage: `${feature.label} was ${disabled ? "re-enabled" : "disabled again"}.`,
23000
+ });
23001
+ });
21965
23002
  } else if (packageStatus?.installed) {
21966
23003
  action.textContent = "Reload";
21967
23004
  action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
@@ -22027,6 +23064,16 @@ function renderOptionalFeatureControls() {
22027
23064
  );
22028
23065
  if (!hasNativeCommandMenu && nativeCommandMenuOpen) setNativeCommandMenuOpen(false);
22029
23066
 
23067
+ const hasSafetyGuardSetup = isOptionalFeatureEnabled("safetyGuard") && hasAvailableCommand("safety-guard-setup");
23068
+ if (elements.optionsSafetyGuardSetupButton) {
23069
+ elements.optionsSafetyGuardSetupButton.hidden = !hasSafetyGuardSetup;
23070
+ setOptionalControlState(
23071
+ elements.optionsSafetyGuardSetupButton,
23072
+ hasSafetyGuardSetup,
23073
+ commandUnavailableMessage("safety-guard-setup"),
23074
+ );
23075
+ }
23076
+
22030
23077
  const hasStatsCommand = isOptionalFeatureEnabled("statsCommand");
22031
23078
  if (elements.optionsStatsButton) {
22032
23079
  elements.optionsStatsButton.hidden = !hasStatsCommand;
@@ -22052,6 +23099,7 @@ function renderOptionalFeatureControls() {
22052
23099
  elements.optionsConversationModeButton.hidden = !hasNaturalConversation;
22053
23100
  }
22054
23101
  renderConversationModeControls();
23102
+ renderWorkflowModeControls();
22055
23103
 
22056
23104
  const hasRemoteWebuiCommand = isOptionalFeatureEnabled("remoteWebui") && hasAvailableCommand("remote");
22057
23105
  if (elements.optionsRemoteButton) {
@@ -22100,7 +23148,7 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
22100
23148
  "",
22101
23149
  "Continue?",
22102
23150
  ].join("\n");
22103
- if (!confirm(warning)) return;
23151
+ if (!(await appConfirmText(warning, { affected: feature.packageName, confirmLabel: update ? "Update feature" : "Install feature" }))) return;
22104
23152
 
22105
23153
  const startedAt = Date.now();
22106
23154
  optionalFeatureInstallInProgress.add(featureId);
@@ -22156,7 +23204,7 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
22156
23204
  hint: "Use Reload if this row still says Installed instead of Enabled.",
22157
23205
  command,
22158
23206
  });
22159
- if (confirm(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to enable newly loaded resources?`)) {
23207
+ 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
23208
  sendPrompt("prompt", "/reload");
22161
23209
  } else {
22162
23210
  const tabContext = activeTabContext();
@@ -22249,9 +23297,25 @@ function openNativeCommandDialog({ title, message = "", searchPlaceholder = "" }
22249
23297
  if (searchPlaceholder) queueMicrotask(() => elements.nativeCommandSearch.focus());
22250
23298
  }
22251
23299
 
22252
- function closeNativeCommandDialog() {
23300
+ function closeNativeCommandDialog({ force = false } = {}) {
23301
+ if (nativeSettingsDirty && !force) {
23302
+ appConfirm({
23303
+ title: "Discard unsaved settings?",
23304
+ summary: "Your changes have not been applied.",
23305
+ affected: "All changed fields in this settings window",
23306
+ undoable: false,
23307
+ alternative: "Cancel and choose Apply to keep the changes.",
23308
+ confirmLabel: "Discard changes",
23309
+ }).then((confirmed) => {
23310
+ if (!confirmed) return;
23311
+ nativeSettingsDirty = false;
23312
+ closeNativeCommandDialog({ force: true });
23313
+ });
23314
+ return;
23315
+ }
22253
23316
  if (elements.nativeCommandDialog.open) elements.nativeCommandDialog.close();
22254
23317
  elements.nativeCommandSearch.oninput = null;
23318
+ nativeSettingsDirty = false;
22255
23319
  nativeCommandTabId = null;
22256
23320
  }
22257
23321
 
@@ -22419,8 +23483,18 @@ function nativeSettingsBadge(label, tone = "") {
22419
23483
 
22420
23484
  function normalizedSettingsBadge(badge) {
22421
23485
  if (!badge) return null;
22422
- if (typeof badge === "string") return { label: badge, tone: "" };
22423
- return badge;
23486
+ const normalized = typeof badge === "string" ? { label: badge, tone: "" } : { ...badge };
23487
+ const scopeLabels = {
23488
+ now: "This tab",
23489
+ browser: "This browser",
23490
+ reload: "Global · reload",
23491
+ TUI: "Native TUI",
23492
+ tui: "Native TUI",
23493
+ startup: "Global · next start",
23494
+ safety: "Global",
23495
+ };
23496
+ normalized.label = scopeLabels[normalized.label] || normalized.label;
23497
+ return normalized;
22424
23498
  }
22425
23499
 
22426
23500
  function nativeSettingsLabelRow(label, badge) {
@@ -22533,7 +23607,7 @@ function nativeSettingsChangedMessage(response, reloadRequested) {
22533
23607
  }
22534
23608
 
22535
23609
  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." });
23610
+ 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
23611
  renderNativeLoading("Loading settings…");
22538
23612
  let settingsData;
22539
23613
  try {
@@ -22566,6 +23640,10 @@ async function openNativeSettingsDialog() {
22566
23640
  { value: "followUp", label: "follow-up" },
22567
23641
  { value: "steer", label: "steer" },
22568
23642
  ], "When you submit a normal prompt while a tab is already busy.", { label: "browser", tone: "browser" }),
23643
+ density: nativeSettingSelect("Interface density", interfaceDensity, [
23644
+ { value: "comfortable", label: "Comfortable" },
23645
+ { value: "compact", label: "Compact" },
23646
+ ], "Compact reduces spacing while preserving the 12 px text floor.", { label: "browser", tone: "browser" }),
22569
23647
  thinkingOutput: nativeSettingToggle("Show thinking output", settings.hideThinkingBlock !== true, "Browser transcript visibility; also writes Pi's hide-thinking setting.", { label: "browser", tone: "browser" }),
22570
23648
  doneNotifications: nativeSettingToggle("Agent done notifications", agentDoneNotificationsEnabled, "Browser notification after background tab work completes.", { label: "browser", tone: "browser" }),
22571
23649
  autocompleteMax: nativeSettingSelect("Autocomplete max items", settings.autocompleteMaxVisible ?? autocompleteMaxVisible, SETTINGS_AUTOCOMPLETE_OPTIONS, "Maximum visible slash/path suggestions.", { label: "browser", tone: "browser" }),
@@ -22586,11 +23664,47 @@ async function openNativeSettingsDialog() {
22586
23664
  terminalProgress: nativeSettingToggle("Terminal progress", settings.showTerminalProgress === true, "Native TUI OSC 9;4 terminal progress indicators.", { label: "TUI", tone: "tui" }),
22587
23665
  };
22588
23666
 
23667
+ const remoteAccessSection = make("details", "native-settings-section native-settings-remote-access");
23668
+ remoteAccessSection.open = false;
23669
+ remoteAccessSection.append(make("summary", "native-settings-section-summary", "Remote access"));
23670
+ const remoteAccessBody = make("div", "native-settings-grid");
23671
+ const renderRemoteAccessSettings = () => {
23672
+ const open = !!latestNetwork?.open;
23673
+ const auth = latestNetwork?.auth || {};
23674
+ const status = make("div", `native-settings-note ${open ? "warning" : ""}`.trim());
23675
+ status.append(
23676
+ make("strong", undefined, open ? "Open to the network" : "Closed · local only"),
23677
+ 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."}`),
23678
+ );
23679
+ const actions = make("div", "native-settings-remote-actions");
23680
+ const listenerButton = make("button", open ? "danger" : "", open ? "Close remote access" : "Open for remote access");
23681
+ listenerButton.type = "button";
23682
+ listenerButton.addEventListener("click", async () => {
23683
+ await openToNetwork();
23684
+ renderRemoteAccessSettings();
23685
+ });
23686
+ const authButton = make("button", undefined, auth.enabled ? "Disable remote PIN auth" : "Enable remote PIN auth");
23687
+ authButton.type = "button";
23688
+ authButton.addEventListener("click", async () => {
23689
+ await toggleRemoteAuth();
23690
+ renderRemoteAccessSettings();
23691
+ });
23692
+ const qrButton = make("button", undefined, "Show QR code");
23693
+ qrButton.type = "button";
23694
+ qrButton.hidden = !open;
23695
+ qrButton.addEventListener("click", () => showRemoteWebuiQrPopupFromNetwork().catch((error) => addEvent(error.message || String(error), "error")));
23696
+ actions.append(listenerButton, authButton, qrButton);
23697
+ remoteAccessBody.replaceChildren(status, actions);
23698
+ };
23699
+ renderRemoteAccessSettings();
23700
+ remoteAccessSection.append(remoteAccessBody);
23701
+
22589
23702
  const body = make("div", "native-settings-panel");
22590
23703
  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."),
23704
+ nativeSettingsNote("Scopes", "Each field says whether it affects this tab, this browser, global Pi settings, or the native TUI."),
23705
+ remoteAccessSection,
22592
23706
  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 }),
23707
+ 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
23708
  nativeSettingsSection("Images", "Provider image policy and native terminal image display.", [controls.autoResizeImages, controls.blockImages, controls.showImages, controls.imageWidth], { open: true }),
22595
23709
  nativeSettingsSection("Startup & safety", "Command registration, warnings, update/startup behavior.", [controls.skillCommands, controls.anthropicWarning, controls.collapseChangelog, controls.quietStartup, controls.installTelemetry], { open: false }),
22596
23710
  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 +23713,46 @@ async function openNativeSettingsDialog() {
22599
23713
  elements.nativeCommandActions.replaceChildren();
22600
23714
  addNativeCommandAction("Model…", () => openNativeModelSelector());
22601
23715
  addNativeCommandAction("Theme…", () => openNativeThemeSelector());
22602
- addNativeCommandAction("Cancel", closeNativeCommandDialog);
23716
+ addNativeCommandAction("Cancel", () => closeNativeCommandDialog());
23717
+
23718
+ const initialPayload = collectNativeSettingsPayload(controls);
23719
+ const initialRuntime = JSON.stringify({
23720
+ thinking: state.thinkingLevel || "off",
23721
+ autoCompact: state.autoCompactionEnabled !== false,
23722
+ steering: state.steeringMode || "one-at-a-time",
23723
+ followUp: state.followUpMode || "one-at-a-time",
23724
+ busyBehavior,
23725
+ density: interfaceDensity,
23726
+ doneNotifications: agentDoneNotificationsEnabled,
23727
+ });
23728
+ const reloadKeys = new Set(["transport", "httpIdleTimeoutMs", "autoResizeImages", "blockImages", "enableSkillCommands"]);
23729
+ const reloadNeeded = () => {
23730
+ const payload = collectNativeSettingsPayload(controls);
23731
+ return [...reloadKeys].some((key) => JSON.stringify(payload[key]) !== JSON.stringify(initialPayload[key]));
23732
+ };
23733
+ const currentRuntime = () => JSON.stringify({
23734
+ thinking: controls.thinking.select.value,
23735
+ autoCompact: controls.autoCompact.input.checked,
23736
+ steering: controls.steering.select.value,
23737
+ followUp: controls.followUp.select.value,
23738
+ busyBehavior: controls.busyBehavior.select.value,
23739
+ density: controls.density.select.value,
23740
+ doneNotifications: controls.doneNotifications.input.checked,
23741
+ });
23742
+ let applyButton;
23743
+ const updateDirtyState = () => {
23744
+ nativeSettingsDirty = currentRuntime() !== initialRuntime || JSON.stringify(collectNativeSettingsPayload(controls)) !== JSON.stringify(initialPayload);
23745
+ if (applyButton) {
23746
+ applyButton.disabled = !nativeSettingsDirty;
23747
+ applyButton.textContent = reloadNeeded() ? "Apply and reload" : "Apply";
23748
+ }
23749
+ };
23750
+ body.addEventListener("input", updateDirtyState);
23751
+ body.addEventListener("change", updateDirtyState);
22603
23752
 
22604
- const applySettings = async (reload, button) => {
22605
- setNativeActionBusy(button, true, reload ? "Applying & reloading…" : "Applying…");
23753
+ const applySettings = async (button) => {
23754
+ const reload = reloadNeeded();
23755
+ setNativeActionBusy(button, true, reload ? "Applying and reloading…" : "Applying…");
22606
23756
  setNativeCommandError("");
22607
23757
  try {
22608
23758
  const requests = [];
@@ -22612,15 +23762,18 @@ async function openNativeSettingsDialog() {
22612
23762
  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
23763
  if (controls.autoCompact.input.checked !== (state.autoCompactionEnabled !== false)) requests.push(nativeCommandApi("/api/auto-compaction", { method: "POST", body: { enabled: controls.autoCompact.input.checked } }));
22614
23764
  setBusyPromptBehavior(controls.busyBehavior.select.value);
23765
+ setInterfaceDensity(controls.density.select.value);
22615
23766
  if (controls.thinkingOutput.input.checked !== thinkingOutputVisible) setThinkingOutputVisible(controls.thinkingOutput.input.checked);
22616
23767
  if (controls.doneNotifications.input.checked !== agentDoneNotificationsEnabled) await setAgentDoneNotificationsEnabled(controls.doneNotifications.input.checked);
22617
23768
  await Promise.all(requests);
22618
- const response = await nativeCommandApi("/api/settings", { method: "POST", body: { settings: collectNativeSettingsPayload(controls), reload } });
23769
+ const payload = collectNativeSettingsPayload(controls);
23770
+ const response = await nativeCommandApi("/api/settings", { method: "POST", body: { settings: payload, reload } });
22619
23771
  applyResponseTab(response);
22620
- applyNativeSettingsForBrowser(response.data?.settings || collectNativeSettingsPayload(controls));
23772
+ applyNativeSettingsForBrowser(response.data?.settings || payload);
22621
23773
  if (thinkingLevelChanged) requestGitFooterWebuiPayload(activeTabContext(), { force: true });
22622
23774
  addTransientMessage({ role: "native", title: "/settings", content: nativeSettingsChangedMessage(response, reload), level: response.data?.reloadRecommended?.length && !response.data?.reloaded ? "warn" : "info" });
22623
- closeNativeCommandDialog();
23775
+ nativeSettingsDirty = false;
23776
+ closeNativeCommandDialog({ force: true });
22624
23777
  await refreshAll();
22625
23778
  } catch (error) {
22626
23779
  setNativeCommandError(error.message || String(error));
@@ -22629,8 +23782,8 @@ async function openNativeSettingsDialog() {
22629
23782
  }
22630
23783
  };
22631
23784
 
22632
- const reloadButton = addNativeCommandAction("Apply & reload tab", () => applySettings(true, reloadButton));
22633
- const save = addNativeCommandAction("Apply", () => applySettings(false, save), "primary");
23785
+ applyButton = addNativeCommandAction("Apply", () => applySettings(applyButton), "primary");
23786
+ updateDirtyState();
22634
23787
  }
22635
23788
 
22636
23789
  function replaceNativeSettingSelectOptions(select, options, preferredValue) {
@@ -22645,6 +23798,124 @@ function replaceNativeSettingSelectOptions(select, options, preferredValue) {
22645
23798
  select.value = values.includes(String(preferredValue)) ? String(preferredValue) : values[0] || "";
22646
23799
  }
22647
23800
 
23801
+ const SAFETY_GUARD_CATEGORY_LABELS = Object.freeze({
23802
+ git: "Git history and destructive operations",
23803
+ filesystem: "Filesystem deletion and overwrite",
23804
+ docker: "Docker and Podman destruction",
23805
+ package: "Package removal",
23806
+ system: "System state and permissions",
23807
+ database: "Dangerous SQL",
23808
+ secrets: "Secret file access",
23809
+ });
23810
+
23811
+ async function openNativeSafetyGuardSetupDialog() {
23812
+ openNativeCommandDialog({
23813
+ title: "/safety-guard-setup",
23814
+ message: "Configure persistent command categories, protected-path checks, and the context shown around dangerous matches.",
23815
+ });
23816
+ renderNativeLoading("Loading safety guard setup…");
23817
+
23818
+ let data;
23819
+ try {
23820
+ const response = await nativeCommandApi("/api/safety-guard/config");
23821
+ data = response.data || {};
23822
+ } catch (error) {
23823
+ setNativeCommandError(error.message || String(error));
23824
+ elements.nativeCommandBody.replaceChildren();
23825
+ return;
23826
+ }
23827
+
23828
+ const config = data.config || {};
23829
+ const defaults = data.defaults || {};
23830
+ const categories = Array.isArray(data.categories) && data.categories.length
23831
+ ? data.categories
23832
+ : Object.keys(SAFETY_GUARD_CATEGORY_LABELS);
23833
+ const minimumContext = Number.isInteger(data.contextLines?.min) ? data.contextLines.min : 0;
23834
+ const maximumContext = Number.isInteger(data.contextLines?.max) ? data.contextLines.max : 20;
23835
+ const contextOptions = Array.from(
23836
+ { length: Math.max(1, maximumContext - minimumContext + 1) },
23837
+ (_, index) => String(index + minimumContext),
23838
+ );
23839
+ const categoryControls = Object.fromEntries(categories.map((category) => [
23840
+ category,
23841
+ nativeSettingToggle(
23842
+ SAFETY_GUARD_CATEGORY_LABELS[category] || category,
23843
+ config.categories?.[category] !== false,
23844
+ `Prompt when a command matches the ${category} guard category.`,
23845
+ { label: category, tone: "safety" },
23846
+ ),
23847
+ ]));
23848
+ const controls = {
23849
+ enabled: nativeSettingToggle("Safety guard enabled", config.enabled !== false, "Master switch for command and protected-path guards.", { label: "global", tone: "safety" }),
23850
+ before: nativeSettingSelect("Lines before a match", config.contextLines?.before ?? 3, contextOptions, "Number of command lines shown before each matched line.", { label: "preview", tone: "browser" }),
23851
+ after: nativeSettingSelect("Lines after a match", config.contextLines?.after ?? 3, contextOptions, "Number of command lines shown after each matched line.", { label: "preview", tone: "browser" }),
23852
+ 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" }),
23853
+ 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" }),
23854
+ };
23855
+
23856
+ const collectConfig = () => ({
23857
+ version: data.version || 1,
23858
+ enabled: controls.enabled.input.checked,
23859
+ categories: Object.fromEntries(categories.map((category) => [category, categoryControls[category].input.checked])),
23860
+ protectedPaths: {
23861
+ write: controls.protectedWrite.input.checked,
23862
+ edit: controls.protectedEdit.input.checked,
23863
+ },
23864
+ contextLines: {
23865
+ before: Number.parseInt(controls.before.select.value, 10),
23866
+ after: Number.parseInt(controls.after.select.value, 10),
23867
+ },
23868
+ });
23869
+ const applyConfig = (value) => {
23870
+ controls.enabled.input.checked = value?.enabled !== false;
23871
+ controls.before.select.value = String(value?.contextLines?.before ?? 3);
23872
+ controls.after.select.value = String(value?.contextLines?.after ?? 3);
23873
+ controls.protectedWrite.input.checked = value?.protectedPaths?.write !== false;
23874
+ controls.protectedEdit.input.checked = value?.protectedPaths?.edit !== false;
23875
+ for (const category of categories) categoryControls[category].input.checked = value?.categories?.[category] !== false;
23876
+ };
23877
+
23878
+ const body = make("div", "native-settings-panel");
23879
+ body.append(
23880
+ nativeSettingsNote("Persistence", `Saved globally in ${data.path || "~/.pi/agent/safety-guard.json"}. Changes are reloaded before guard checks.`),
23881
+ nativeSettingsSection("General", "Enable or disable all guard behavior.", [controls.enabled], { open: true }),
23882
+ nativeSettingsSection("Command preview", "Choose independent context limits before and after each dangerous matched line.", [controls.before, controls.after], { open: true }),
23883
+ nativeSettingsSection("Command categories", "Disable only categories you intentionally do not want guarded.", categories.map((category) => categoryControls[category]), { open: true }),
23884
+ nativeSettingsSection("Protected paths", "Control write/edit prompts for secret-bearing files and credential paths.", [controls.protectedWrite, controls.protectedEdit], { open: true }),
23885
+ );
23886
+ elements.nativeCommandBody.replaceChildren(body);
23887
+ elements.nativeCommandActions.replaceChildren();
23888
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
23889
+ addNativeCommandAction("Reset defaults", () => {
23890
+ applyConfig(defaults);
23891
+ setNativeCommandError("");
23892
+ });
23893
+
23894
+ const save = addNativeCommandAction("Save setup", async () => {
23895
+ setNativeActionBusy(save, true, "Saving…");
23896
+ setNativeCommandError("");
23897
+ try {
23898
+ const response = await nativeCommandApi("/api/safety-guard/config", {
23899
+ method: "POST",
23900
+ body: { config: collectConfig() },
23901
+ });
23902
+ const saved = response.data?.config || collectConfig();
23903
+ const activeCategories = categories.filter((category) => saved.categories?.[category]).length;
23904
+ addTransientMessage({
23905
+ role: "native",
23906
+ title: "/safety-guard-setup",
23907
+ 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.`,
23908
+ level: saved.enabled ? "info" : "warn",
23909
+ });
23910
+ closeNativeCommandDialog();
23911
+ } catch (error) {
23912
+ setNativeCommandError(error.message || String(error));
23913
+ } finally {
23914
+ setNativeActionBusy(save, false);
23915
+ }
23916
+ }, "primary");
23917
+ }
23918
+
22648
23919
  function gitWorkflowSetupModelKey(model) {
22649
23920
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
22650
23921
  }
@@ -23126,12 +24397,44 @@ function renderNativeResourceFilterActions(filter, setFilter, render) {
23126
24397
  addNativeCommandAction("Cancel", closeNativeCommandDialog);
23127
24398
  }
23128
24399
 
24400
+ function nativeResourceScopeControl(scope, { configured = false, saving = false, onChange } = {}) {
24401
+ const global = scope === "global";
24402
+ const hint = global
24403
+ ? configured
24404
+ ? "Saved as the default for future sessions. Existing session-specific choices are unchanged."
24405
+ : "No global default is saved yet. The current session is shown as the starting point."
24406
+ : "Applies immediately and persists only on the current session branch.";
24407
+ const control = nativeSettingSelect("Apply changes to", scope, [
24408
+ { value: "session", label: "Session only" },
24409
+ { value: "global", label: "Global default" },
24410
+ ], hint, global ? { label: "Global", tone: "startup" } : { label: "This session", tone: "now" });
24411
+ control.field.classList.add("native-resource-scope");
24412
+ control.select.disabled = !!saving;
24413
+ control.select.addEventListener("change", () => onChange?.(control.select.value));
24414
+ return control.field;
24415
+ }
24416
+
23129
24417
  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…");
24418
+ openNativeCommandDialog({ title: "Tools Setup", message: "Enable or disable tool access for this session or save a default for future sessions.", searchPlaceholder: "Filter tools…" });
23132
24419
  let tools = [];
23133
24420
  let savingName = "";
23134
24421
  let filter = "all";
24422
+ let scope = "session";
24423
+ let configured = false;
24424
+
24425
+ const load = async () => {
24426
+ renderNativeLoading(`Loading ${scope === "global" ? "global tool defaults" : "session tools"}…`);
24427
+ try {
24428
+ const response = await nativeCommandApi(`/api/tools?scope=${encodeURIComponent(scope)}`);
24429
+ tools = Array.isArray(response.data?.tools) ? response.data.tools : [];
24430
+ configured = response.data?.configured === true;
24431
+ render();
24432
+ } catch (error) {
24433
+ setNativeCommandError(error.message || String(error));
24434
+ elements.nativeCommandBody.replaceChildren();
24435
+ }
24436
+ };
24437
+
23135
24438
  const render = () => {
23136
24439
  renderNativeResourceToggles(tools, {
23137
24440
  savingName,
@@ -23146,9 +24449,14 @@ async function openNativeToolsSelector() {
23146
24449
  setNativeCommandError("");
23147
24450
  render();
23148
24451
  try {
23149
- const response = await nativeCommandApi("/api/tools", { method: "POST", body: { enabledTools: [...enabledTools] } });
24452
+ const response = await nativeCommandApi("/api/tools", { method: "POST", body: { enabledTools: [...enabledTools], scope } });
23150
24453
  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" });
24454
+ configured = response.data?.configured === true;
24455
+ const enabled = enabledTools.has(tool.name);
24456
+ const content = scope === "global"
24457
+ ? `Global default for tool ${tool.name} ${enabled ? "enabled" : "disabled"}. Future sessions inherit it; this session is unchanged.`
24458
+ : `Tool ${tool.name} ${enabled ? "enabled" : "disabled"} for this session.`;
24459
+ addTransientMessage({ role: "native", title: "/tools", content, level: "info" });
23152
24460
  } catch (error) {
23153
24461
  setNativeCommandError(error.message || String(error));
23154
24462
  } finally {
@@ -23157,25 +24465,43 @@ async function openNativeToolsSelector() {
23157
24465
  }
23158
24466
  },
23159
24467
  });
24468
+ elements.nativeCommandBody.prepend(nativeResourceScopeControl(scope, {
24469
+ configured,
24470
+ saving: !!savingName,
24471
+ onChange: async (nextScope) => {
24472
+ if (nextScope === scope || savingName) return;
24473
+ scope = nextScope;
24474
+ await load();
24475
+ },
24476
+ }));
23160
24477
  renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render);
23161
24478
  };
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
- }
24479
+
24480
+ elements.nativeCommandSearch.oninput = render;
24481
+ await load();
23171
24482
  }
23172
24483
 
23173
24484
  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…");
24485
+ openNativeCommandDialog({ title: "Skills Setup", message: "Enable or disable skill invocation for this session or save a default for future sessions.", searchPlaceholder: "Filter skills…" });
23176
24486
  let skills = [];
23177
24487
  let savingName = "";
23178
24488
  let filter = "all";
24489
+ let scope = "session";
24490
+ let configured = false;
24491
+
24492
+ const load = async () => {
24493
+ renderNativeLoading(`Loading ${scope === "global" ? "global skill defaults" : "session skills"}…`);
24494
+ try {
24495
+ const response = await nativeCommandApi(`/api/skills?scope=${encodeURIComponent(scope)}`);
24496
+ skills = Array.isArray(response.data?.skills) ? response.data.skills : [];
24497
+ configured = response.data?.configured === true;
24498
+ render();
24499
+ } catch (error) {
24500
+ setNativeCommandError(error.message || String(error));
24501
+ elements.nativeCommandBody.replaceChildren();
24502
+ }
24503
+ };
24504
+
23179
24505
  const render = () => {
23180
24506
  renderNativeResourceToggles(skills, {
23181
24507
  savingName,
@@ -23189,10 +24515,15 @@ async function openNativeSkillsSelector() {
23189
24515
  setNativeCommandError("");
23190
24516
  render();
23191
24517
  try {
23192
- const response = await nativeCommandApi("/api/skills", { method: "POST", body: { enabledSkills: [...enabledSkills] } });
24518
+ const response = await nativeCommandApi("/api/skills", { method: "POST", body: { enabledSkills: [...enabledSkills], scope } });
23193
24519
  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"));
24520
+ configured = response.data?.configured === true;
24521
+ const enabled = enabledSkills.has(skill.name);
24522
+ const content = scope === "global"
24523
+ ? `Global default for skill ${skill.name} ${enabled ? "enabled" : "disabled"}. Future sessions inherit it; this session is unchanged.`
24524
+ : `Skill ${skill.name} ${enabled ? "enabled" : "disabled"} for this session.`;
24525
+ addTransientMessage({ role: "native", title: "/skills", content, level: "info" });
24526
+ if (scope === "session") refreshCommands(activeTabContext()).catch((error) => addEvent(error.message || String(error), "error"));
23196
24527
  } catch (error) {
23197
24528
  setNativeCommandError(error.message || String(error));
23198
24529
  } finally {
@@ -23201,17 +24532,20 @@ async function openNativeSkillsSelector() {
23201
24532
  }
23202
24533
  },
23203
24534
  });
24535
+ elements.nativeCommandBody.prepend(nativeResourceScopeControl(scope, {
24536
+ configured,
24537
+ saving: !!savingName,
24538
+ onChange: async (nextScope) => {
24539
+ if (nextScope === scope || savingName) return;
24540
+ scope = nextScope;
24541
+ await load();
24542
+ },
24543
+ }));
23204
24544
  renderNativeResourceFilterActions(filter, (value) => { filter = value; }, render);
23205
24545
  };
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
- }
24546
+
24547
+ elements.nativeCommandSearch.oninput = render;
24548
+ await load();
23215
24549
  }
23216
24550
 
23217
24551
  async function openNativeAuthSelector(mode) {
@@ -23250,7 +24584,7 @@ async function openNativeAuthSelector(mode) {
23250
24584
  setNativeCommandError(`Run /login in the Pi TUI for ${item.label}. Browser login is not implemented yet.`);
23251
24585
  return;
23252
24586
  }
23253
- if (!window.confirm(`Remove stored credentials for ${item.label}?`)) return;
24587
+ if (!(await appConfirmText(`Remove stored credentials for ${item.label}?`, { affected: `${item.label} stored credentials`, confirmLabel: "Remove credentials" }))) return;
23254
24588
  setNativeCommandError("");
23255
24589
  try {
23256
24590
  const result = await nativeCommandApi("/api/auth-logout", {
@@ -23298,6 +24632,9 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
23298
24632
  case "settings":
23299
24633
  await openNativeSettingsDialog();
23300
24634
  return true;
24635
+ case "safety-guard-setup":
24636
+ await openNativeSafetyGuardSetupDialog();
24637
+ return true;
23301
24638
  case "git-workflow-setup":
23302
24639
  await openNativeGitWorkflowSetupDialog();
23303
24640
  return true;
@@ -23925,7 +25262,15 @@ function renderNetworkStatus() {
23925
25262
  : "On"
23926
25263
  : "Off";
23927
25264
  elements.openNetworkButton.disabled = rebinding;
23928
- elements.openNetworkButton.textContent = opening ? "Opening…" : closing ? "Closing…" : open ? "Close for network" : "Open to network";
25265
+ elements.openNetworkButton.textContent = opening ? "Opening…" : closing ? "Closing…" : open ? "Close remote access" : "Open for remote access";
25266
+ if (elements.remoteAccessIndicator) {
25267
+ elements.remoteAccessIndicator.hidden = !open;
25268
+ elements.remoteAccessIndicator.textContent = open ? "Remote access open" : "";
25269
+ elements.remoteAccessIndicator.title = open
25270
+ ? `Network listener exposed${networkUrls.length ? ` at ${networkUrls.join(", ")}` : ""} · ${auth.enabled ? "PIN auth on" : "PIN auth off"}`
25271
+ : "";
25272
+ }
25273
+ document.body.classList.toggle("remote-access-open", open);
23929
25274
  if (elements.showRemoteQrButton) {
23930
25275
  elements.showRemoteQrButton.hidden = !open;
23931
25276
  elements.showRemoteQrButton.disabled = rebinding || !open;
@@ -24450,10 +25795,17 @@ function cancelBangSuggestionRequest() {
24450
25795
  abortBangSuggestionRequest();
24451
25796
  }
24452
25797
 
25798
+ function showCommandSuggestionList() {
25799
+ elements.commandSuggest.hidden = false;
25800
+ elements.promptInput?.setAttribute("aria-expanded", "true");
25801
+ }
25802
+
24453
25803
  function hideCommandSuggestions() {
24454
25804
  cancelPathSuggestionRequest();
24455
25805
  cancelBangSuggestionRequest();
24456
25806
  elements.commandSuggest.hidden = true;
25807
+ elements.promptInput?.setAttribute("aria-expanded", "false");
25808
+ elements.promptInput?.removeAttribute("aria-activedescendant");
24457
25809
  elements.commandSuggest.removeAttribute("aria-busy");
24458
25810
  elements.commandSuggest.replaceChildren();
24459
25811
  commandSuggestions = [];
@@ -24473,7 +25825,10 @@ function setActiveCommandSuggestion(index) {
24473
25825
  const active = itemIndex === commandSuggestIndex;
24474
25826
  item.classList.toggle("active", active);
24475
25827
  item.setAttribute("aria-selected", active ? "true" : "false");
24476
- if (active) item.scrollIntoView({ block: "nearest" });
25828
+ if (active) {
25829
+ elements.promptInput?.setAttribute("aria-activedescendant", item.id);
25830
+ item.scrollIntoView({ block: "nearest" });
25831
+ }
24477
25832
  }
24478
25833
  }
24479
25834
 
@@ -24513,13 +25868,14 @@ function renderCommandSuggestionItems(trigger, { keepIndex = false } = {}) {
24513
25868
 
24514
25869
  if (commandSuggestions.length === 0) {
24515
25870
  elements.commandSuggest.append(make("div", "command-suggest-empty", `No command matches /${trigger.query}`));
24516
- elements.commandSuggest.hidden = false;
25871
+ showCommandSuggestionList();
24517
25872
  return;
24518
25873
  }
24519
25874
 
24520
25875
  for (const [index, command] of commandSuggestions.entries()) {
24521
25876
  const item = make("button", "command-suggest-item");
24522
25877
  item.type = "button";
25878
+ item.id = `composer-suggestion-command-${encodeURIComponent(command.name).replace(/%/g, "-")}`;
24523
25879
  item.setAttribute("role", "option");
24524
25880
  item.addEventListener("mousedown", (event) => event.preventDefault());
24525
25881
  item.addEventListener("pointermove", (event) => setActiveCommandSuggestionFromPointerMove(index, event));
@@ -24533,7 +25889,8 @@ function renderCommandSuggestionItems(trigger, { keepIndex = false } = {}) {
24533
25889
  elements.commandSuggest.append(item);
24534
25890
  }
24535
25891
 
24536
- elements.commandSuggest.hidden = false;
25892
+ showCommandSuggestionList();
25893
+ elements.promptInput?.setAttribute("aria-expanded", "true");
24537
25894
  setActiveCommandSuggestion(keepIndex ? commandSuggestIndex : 0);
24538
25895
  }
24539
25896
 
@@ -24555,7 +25912,7 @@ function renderPathSuggestionItems(trigger, { keepIndex = false } = {}) {
24555
25912
 
24556
25913
  if (pathSuggestions.length === 0) {
24557
25914
  elements.commandSuggest.append(make("div", "command-suggest-empty", `No path matches @${trigger.query}`));
24558
- elements.commandSuggest.hidden = false;
25915
+ showCommandSuggestionList();
24559
25916
  return;
24560
25917
  }
24561
25918
 
@@ -24563,6 +25920,7 @@ function renderPathSuggestionItems(trigger, { keepIndex = false } = {}) {
24563
25920
  const isDirectory = pathSuggestionIsDirectory(suggestion);
24564
25921
  const item = make("button", `command-suggest-item path-suggest-item ${isDirectory ? "directory" : "file"}`);
24565
25922
  item.type = "button";
25923
+ item.id = `composer-suggestion-path-${index}-${encodeURIComponent(suggestion.path).replace(/%/g, "-")}`;
24566
25924
  item.setAttribute("role", "option");
24567
25925
  item.addEventListener("mousedown", (event) => event.preventDefault());
24568
25926
  item.addEventListener("pointermove", (event) => setActiveCommandSuggestionFromPointerMove(index, event));
@@ -24576,7 +25934,7 @@ function renderPathSuggestionItems(trigger, { keepIndex = false } = {}) {
24576
25934
  elements.commandSuggest.append(item);
24577
25935
  }
24578
25936
 
24579
- elements.commandSuggest.hidden = false;
25937
+ showCommandSuggestionList();
24580
25938
  setActiveCommandSuggestion(keepIndex ? commandSuggestIndex : 0);
24581
25939
  }
24582
25940
 
@@ -24599,7 +25957,7 @@ async function renderPathSuggestions(trigger, { keepIndex = false } = {}) {
24599
25957
  pathSuggestions = [];
24600
25958
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", "Finding paths…"));
24601
25959
  }
24602
- elements.commandSuggest.hidden = false;
25960
+ showCommandSuggestionList();
24603
25961
  elements.commandSuggest.setAttribute("aria-busy", "true");
24604
25962
 
24605
25963
  try {
@@ -24611,7 +25969,7 @@ async function renderPathSuggestions(trigger, { keepIndex = false } = {}) {
24611
25969
  if (error?.name === "AbortError" || requestSerial !== pathSuggestRequestSerial) return;
24612
25970
  pathSuggestions = [];
24613
25971
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", `Path suggestions unavailable: ${error.message}`));
24614
- elements.commandSuggest.hidden = false;
25972
+ showCommandSuggestionList();
24615
25973
  } finally {
24616
25974
  if (requestSerial === pathSuggestRequestSerial) {
24617
25975
  pathSuggestAbortController = null;
@@ -24628,13 +25986,14 @@ function renderBangSuggestionItems(trigger, { keepIndex = false } = {}) {
24628
25986
 
24629
25987
  if (bangSuggestions.length === 0) {
24630
25988
  elements.commandSuggest.append(make("div", "command-suggest-empty", `No shell command matches !${trigger.query}`));
24631
- elements.commandSuggest.hidden = false;
25989
+ showCommandSuggestionList();
24632
25990
  return;
24633
25991
  }
24634
25992
 
24635
25993
  for (const [index, suggestion] of bangSuggestions.entries()) {
24636
25994
  const item = make("button", "command-suggest-item bang-suggest-item");
24637
25995
  item.type = "button";
25996
+ item.id = `composer-suggestion-bang-${index}-${encodeURIComponent(suggestion.insertText).replace(/%/g, "-")}`;
24638
25997
  item.setAttribute("role", "option");
24639
25998
  item.addEventListener("mousedown", (event) => event.preventDefault());
24640
25999
  item.addEventListener("pointermove", (event) => setActiveCommandSuggestionFromPointerMove(index, event));
@@ -24648,7 +26007,7 @@ function renderBangSuggestionItems(trigger, { keepIndex = false } = {}) {
24648
26007
  elements.commandSuggest.append(item);
24649
26008
  }
24650
26009
 
24651
- elements.commandSuggest.hidden = false;
26010
+ showCommandSuggestionList();
24652
26011
  setActiveCommandSuggestion(keepIndex ? commandSuggestIndex : 0);
24653
26012
  }
24654
26013
 
@@ -24673,7 +26032,7 @@ async function renderBangSuggestions(trigger, { keepIndex = false } = {}) {
24673
26032
  bangSuggestions = [];
24674
26033
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", "Finding shell commands…"));
24675
26034
  }
24676
- elements.commandSuggest.hidden = false;
26035
+ showCommandSuggestionList();
24677
26036
  elements.commandSuggest.setAttribute("aria-busy", "true");
24678
26037
 
24679
26038
  try {
@@ -24685,7 +26044,7 @@ async function renderBangSuggestions(trigger, { keepIndex = false } = {}) {
24685
26044
  if (error?.name === "AbortError" || requestSerial !== bangSuggestRequestSerial) return;
24686
26045
  bangSuggestions = [];
24687
26046
  elements.commandSuggest.replaceChildren(make("div", "command-suggest-empty", `Shell command suggestions unavailable: ${error.message}`));
24688
- elements.commandSuggest.hidden = false;
26047
+ showCommandSuggestionList();
24689
26048
  } finally {
24690
26049
  if (requestSerial === bangSuggestRequestSerial) {
24691
26050
  bangSuggestAbortController = null;
@@ -24952,12 +26311,14 @@ function renderCommandPaletteList({ preserveScroll = false } = {}) {
24952
26311
  list.replaceChildren();
24953
26312
  if (!commandPaletteItems.length) {
24954
26313
  list.append(make("div", "command-palette-empty muted", "No matching actions."));
26314
+ elements.commandPaletteInput?.removeAttribute("aria-activedescendant");
24955
26315
  if (preserveScroll) list.scrollTop = scrollTop;
24956
26316
  return;
24957
26317
  }
24958
26318
  commandPaletteItems.forEach((item, index) => {
24959
26319
  const button = make("button", `command-palette-item${index === commandPaletteIndex ? " active" : ""}`);
24960
26320
  button.type = "button";
26321
+ button.id = `command-palette-option-${encodeURIComponent(`${item.kind}-${item.label}`).replace(/%/g, "-")}`;
24961
26322
  button.setAttribute("role", "option");
24962
26323
  button.setAttribute("aria-selected", index === commandPaletteIndex ? "true" : "false");
24963
26324
  button.addEventListener("click", () => executeCommandPaletteItem(item));
@@ -24968,11 +26329,12 @@ function renderCommandPaletteList({ preserveScroll = false } = {}) {
24968
26329
  );
24969
26330
  list.append(button);
24970
26331
  });
26332
+ const active = list.children[commandPaletteIndex];
26333
+ if (active?.id) elements.commandPaletteInput?.setAttribute("aria-activedescendant", active.id);
24971
26334
  if (preserveScroll) {
24972
26335
  list.scrollTop = scrollTop;
24973
26336
  return;
24974
26337
  }
24975
- const active = list.children[commandPaletteIndex];
24976
26338
  active?.scrollIntoView({ block: "nearest" });
24977
26339
  }
24978
26340
 
@@ -25066,12 +26428,44 @@ function scheduleForegroundReconcile(reason = "resume", delay = FOREGROUND_RECON
25066
26428
 
25067
26429
  async function openToNetwork() {
25068
26430
  const open = !!latestNetwork?.open;
26431
+ if (!open) {
26432
+ const localUrl = latestNetwork?.localUrl || `${window.location.origin}/`;
26433
+ let interfaceName = "all network interfaces";
26434
+ let port = DEFAULT_WEBUI_PORT;
26435
+ try {
26436
+ const parsed = new URL(localUrl);
26437
+ port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
26438
+ } catch {
26439
+ // Keep explicit fallback values in the confirmation.
26440
+ }
26441
+ const confirmed = await appConfirm({
26442
+ title: "Open for remote access?",
26443
+ summary: "This changes Pi Web UI from local-only to reachable by devices on your network.",
26444
+ affected: `${interfaceName}, port ${port}, ${latestNetwork?.auth?.enabled ? "PIN authentication enabled" : "PIN authentication disabled"}`,
26445
+ undoable: true,
26446
+ alternative: "Keep local-only access and use this browser on the host machine.",
26447
+ confirmLabel: "Open remote access",
26448
+ });
26449
+ if (!confirmed) return;
26450
+ }
25069
26451
  elements.openNetworkButton.disabled = true;
25070
26452
  elements.openNetworkButton.textContent = open ? "Closing…" : "Opening…";
25071
26453
  try {
25072
26454
  await runRemoteWebuiCommand(remoteWebuiCommand(open ? "close" : "open", open ? "/remote close" : "/remote"));
25073
26455
  await delay(350);
25074
26456
  await refreshNetworkStatus();
26457
+ if (!open && latestNetwork?.open) {
26458
+ offerUndo({
26459
+ message: "Remote access is open.",
26460
+ undo: async () => {
26461
+ await runRemoteWebuiCommand(remoteWebuiCommand("close", "/remote close"));
26462
+ await delay(350);
26463
+ await refreshNetworkStatus();
26464
+ renderNetworkStatus();
26465
+ },
26466
+ successMessage: "Remote access closed; Pi Web UI is local-only again.",
26467
+ });
26468
+ }
25075
26469
  } catch (error) {
25076
26470
  addEvent(error.message || String(error), "error");
25077
26471
  } finally {
@@ -25144,7 +26538,14 @@ async function waitForServerRestart() {
25144
26538
  }
25145
26539
 
25146
26540
  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;
26541
+ if (!(await appConfirm({
26542
+ title: "Restart Pi Web UI server?",
26543
+ summary: "Browser clients disconnect briefly while the server restarts.",
26544
+ affected: "All connected browser clients and Pi tabs managed by this Web UI",
26545
+ undoable: false,
26546
+ alternative: "Cancel and continue using the current server process.",
26547
+ confirmLabel: "Restart server",
26548
+ }))) return;
25148
26549
 
25149
26550
  setServerActionBusy("Restarting…");
25150
26551
  setServerActionStatus("Restart requested. Waiting for the server to come back…", "warn");
@@ -25185,7 +26586,14 @@ async function restartServer() {
25185
26586
  }
25186
26587
 
25187
26588
  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;
26589
+ if (!(await appConfirm({
26590
+ title: "Stop Pi Web UI server?",
26591
+ summary: "The Web UI becomes unavailable until the server is started again.",
26592
+ affected: "All connected browser clients and Pi tabs managed by this Web UI",
26593
+ undoable: false,
26594
+ alternative: "Cancel, or restart instead if you only need to reload the server.",
26595
+ confirmLabel: "Stop server",
26596
+ }))) return;
25189
26597
 
25190
26598
  setServerActionBusy("Stopping…");
25191
26599
  setServerActionStatus("Stop requested. The Web UI will disconnect.", "warn");
@@ -25545,6 +26953,7 @@ function handleExtensionUiRequest(request) {
25545
26953
  if (statusKey === STATS_WEBUI_STATUS_KEY) handleStatsWebuiStatus(request.statusText);
25546
26954
  if (statusKey === BTW_WEBUI_STATUS_KEY) handleBtwWebuiStatus(request.statusText);
25547
26955
  if (statusKey === NATURAL_CONVERSATION_STATUS_KEY) handleNaturalConversationStatus(request.statusText, request.tabId || activeTabId);
26956
+ if (statusKey === WORKFLOW_MODE_STATUS_KEY) handleWorkflowModeStatus(request.statusText, request.tabId || activeTabId);
25548
26957
  if (statusKey === "pi-remote-webui") handleRemoteWebuiStatus(request.statusText);
25549
26958
  updateOptionalFeatureAvailability();
25550
26959
  if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) {
@@ -25562,6 +26971,21 @@ function handleExtensionUiRequest(request) {
25562
26971
  case "setWidget": {
25563
26972
  const widgetKey = request.widgetKey || request.id;
25564
26973
  const requestTabId = request.tabId || activeTabId;
26974
+ if (widgetKey === WORKFLOW_MODE_RPC_WIDGET_KEY) {
26975
+ const modeState = workflowModeStateFromRpcPayload(request.widgetLines);
26976
+ if (modeState) updateWorkflowModeForTab(requestTabId, modeState, { render: requestTabId === activeTabId });
26977
+ updateOptionalFeatureAvailability();
26978
+ return;
26979
+ }
26980
+ if (widgetKey === WORKFLOW_INSPECTOR_WIDGET_KEY) {
26981
+ const inspector = parseWorkflowInspectorPayload(request.widgetLines);
26982
+ if (inspector) updateWorkflowInspectorForTab(requestTabId, inspector);
26983
+ if (!setWidgetForTab(requestTabId, widgetKey, request)) return;
26984
+ updateOptionalFeatureAvailability();
26985
+ renderTabs();
26986
+ renderWidgets();
26987
+ return;
26988
+ }
25565
26989
  if (widgetKey === "pi-remote-webui") {
25566
26990
  setWidgetForTab(requestTabId, widgetKey, { ...request, widgetLines: undefined });
25567
26991
  if (Array.isArray(request.widgetLines)) {
@@ -25702,6 +27126,18 @@ function handleInactiveTabEvent(event) {
25702
27126
  if (event.type === "extension_ui_request" && EXTENSION_UI_BLOCKING_METHODS.has(event.method)) {
25703
27127
  if (!event.replayed) notifyBlockedTab(event.tabId, { request: event, count: event.pendingExtensionUiRequestCount });
25704
27128
  renderTabs();
27129
+ } else if (event.type === "extension_ui_request" && event.method === "setStatus" && event.statusKey === WORKFLOW_MODE_STATUS_KEY) {
27130
+ handleWorkflowModeStatus(event.statusText, event.tabId);
27131
+ renderTabs();
27132
+ } else if (event.type === "extension_ui_request" && event.method === "setWidget" && (event.widgetKey || event.id) === WORKFLOW_MODE_RPC_WIDGET_KEY) {
27133
+ const modeState = workflowModeStateFromRpcPayload(event.widgetLines);
27134
+ if (modeState) updateWorkflowModeForTab(event.tabId, modeState, { render: false });
27135
+ renderTabs();
27136
+ } else if (event.type === "extension_ui_request" && event.method === "setWidget" && (event.widgetKey || event.id) === WORKFLOW_INSPECTOR_WIDGET_KEY) {
27137
+ const inspector = parseWorkflowInspectorPayload(event.widgetLines);
27138
+ if (inspector) updateWorkflowInspectorForTab(event.tabId, inspector);
27139
+ setWidgetForTab(event.tabId, WORKFLOW_INSPECTOR_WIDGET_KEY, event);
27140
+ renderTabs();
25705
27141
  } else if (event.type === "agent_end") {
25706
27142
  notifyAgentDone(event.tabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
25707
27143
  }
@@ -25911,7 +27347,7 @@ function handleEvent(event) {
25911
27347
  removeStreamingToolCallCard();
25912
27348
  handleToolExecutionStart(event);
25913
27349
  setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`);
25914
- addEvent(`tool ${event.toolName} started`);
27350
+ addEvent(`tool ${event.toolName} started`, "info", { toolCallId: event.toolCallId });
25915
27351
  break;
25916
27352
  case "tool_execution_update":
25917
27353
  handleToolExecutionUpdate(event);
@@ -25921,7 +27357,7 @@ function handleEvent(event) {
25921
27357
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
25922
27358
  handleToolExecutionEnd(event);
25923
27359
  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");
27360
+ addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info", { toolCallId: event.toolCallId });
25925
27361
  // No transcript refresh here: the live tool card already shows the
25926
27362
  // result via renderLiveToolRun, and message_end/agent_end reconcile the
25927
27363
  // transcript. This avoids one fetch+render per tool call.
@@ -26313,6 +27749,8 @@ elements.releaseAurButton.addEventListener("click", () => runPublishWorkflow("/r
26313
27749
  elements.nativeSkillsButton.addEventListener("click", () => runNativeCommandMenu("/skills"));
26314
27750
  elements.nativeToolsButton.addEventListener("click", () => runNativeCommandMenu("/tools"));
26315
27751
  elements.optionsCommandPaletteButton.addEventListener("click", () => openCommandPalette());
27752
+ elements.workflowModeButton?.addEventListener("click", () => toggleWorkflowMode());
27753
+ elements.workflowModeChip?.addEventListener("click", () => setWorkflowModeEnabled(false));
26316
27754
  elements.optionsConversationModeButton?.addEventListener("click", () => toggleNaturalConversationMode());
26317
27755
  elements.conversationModeChip?.addEventListener("click", () => toggleVoiceConversationPaused());
26318
27756
  elements.conversationModeEndButton?.addEventListener("click", () => setNaturalConversationModeEnabled(false));
@@ -26341,6 +27779,7 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
26341
27779
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
26342
27780
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
26343
27781
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
27782
+ elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
26344
27783
  elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
26345
27784
  elements.optionsExportButton.addEventListener("click", () => runNativeCommandMenu("/export"));
26346
27785
  elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu("/fork"));
@@ -26401,10 +27840,27 @@ elements.gitPrCreateButton?.addEventListener("click", () => {
26401
27840
  elements.gitPrDialog?.addEventListener("close", () => {
26402
27841
  if (activeGitPrDialogResolve) resolveGitPrDialog(null);
26403
27842
  });
27843
+ elements.nativeCommandDialog.addEventListener("cancel", (event) => {
27844
+ if (!nativeSettingsDirty) return;
27845
+ event.preventDefault();
27846
+ closeNativeCommandDialog();
27847
+ });
26404
27848
  elements.nativeCommandDialog.addEventListener("close", () => {
26405
27849
  elements.nativeCommandSearch.oninput = null;
27850
+ nativeSettingsDirty = false;
26406
27851
  nativeCommandTabId = null;
26407
27852
  });
27853
+ elements.undoToastButton?.addEventListener("click", () => runOfferedUndo());
27854
+ elements.undoToastDismissButton?.addEventListener("click", dismissUndoToast);
27855
+ elements.confirmationCancelButton?.addEventListener("click", () => finishApplicationConfirmation(false));
27856
+ elements.confirmationConfirmButton?.addEventListener("click", () => finishApplicationConfirmation(true));
27857
+ elements.confirmationDialog?.addEventListener("cancel", (event) => {
27858
+ event.preventDefault();
27859
+ finishApplicationConfirmation(false);
27860
+ });
27861
+ elements.confirmationDialog?.addEventListener("close", () => {
27862
+ if (activeConfirmationResolve) finishApplicationConfirmation(false);
27863
+ });
26408
27864
  elements.commandPaletteDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
26409
27865
  elements.commandPaletteDialog?.addEventListener("cancel", (event) => {
26410
27866
  event.preventDefault();
@@ -26636,7 +28092,14 @@ elements.abortButton.addEventListener("click", (event) => {
26636
28092
  elements.newSessionButton.addEventListener("click", async () => {
26637
28093
  setComposerActionsOpen(false);
26638
28094
  const tabContext = activeTabContext();
26639
- if (!confirm("Start a new Pi session?")) return;
28095
+ if (!(await appConfirm({
28096
+ title: "Start a new Pi session?",
28097
+ summary: "The active tab switches to a fresh conversation.",
28098
+ affected: "The active tab; the previous session remains resumable.",
28099
+ undoable: false,
28100
+ alternative: "Cancel and open a separate tab to keep both sessions visible.",
28101
+ confirmLabel: "Start new session",
28102
+ }))) return;
26640
28103
  try {
26641
28104
  const response = await api("/api/new-session", { method: "POST", body: {}, tabId: tabContext.tabId });
26642
28105
  applyResponseTab(response);
@@ -27200,6 +28663,7 @@ elements.refreshClaudeUsageButton?.addEventListener("click", () => {
27200
28663
  refreshClaudeUsage().finally(() => scheduleRefreshClaudeUsage());
27201
28664
  });
27202
28665
  elements.fileTreeRefreshButton?.addEventListener("click", () => refreshFileTreeRoot().catch((error) => addEvent(error.message || String(error), "error")));
28666
+ elements.fileTreeRoot?.addEventListener("keydown", handleFileTreeKeydown);
27203
28667
  elements.fileTreeRoot?.addEventListener("dragover", handleFileTreeRootDragOver);
27204
28668
  elements.fileTreeRoot?.addEventListener("dragleave", handleFileTreeRootDragLeave);
27205
28669
  elements.fileTreeRoot?.addEventListener("drop", (event) => handleFileTreeRootDrop(event).catch((error) => addEvent(error.message || String(error), "error")));
@@ -27214,6 +28678,21 @@ elements.fileTreeSearchInput?.addEventListener("keydown", (event) => {
27214
28678
  }
27215
28679
  });
27216
28680
  elements.fileTreeSearchClearButton?.addEventListener("click", () => clearFileTreeSearch({ focus: true }));
28681
+ elements.fileContextMenu?.addEventListener("keydown", (event) => {
28682
+ const items = [...elements.fileContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
28683
+ const index = items.indexOf(document.activeElement);
28684
+ if (event.key === "Escape") {
28685
+ event.preventDefault();
28686
+ closeFileContextMenu();
28687
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
28688
+ event.preventDefault();
28689
+ const direction = event.key === "ArrowDown" ? 1 : -1;
28690
+ items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
28691
+ } else if (event.key === "Home" || event.key === "End") {
28692
+ event.preventDefault();
28693
+ items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
28694
+ }
28695
+ });
27217
28696
  elements.fileContextMenu?.addEventListener("click", (event) => {
27218
28697
  const button = event.target?.closest?.("[data-file-menu-action]");
27219
28698
  if (!button) return;
@@ -27365,6 +28844,7 @@ elements.promptInput.addEventListener("blur", () => {
27365
28844
  }, 120);
27366
28845
  });
27367
28846
 
28847
+ installModalPrimitives();
27368
28848
  resizePromptInput();
27369
28849
  restoreFileViewerWidthPreference();
27370
28850
  focusPromptInput({ defer: true });
@@ -27391,6 +28871,7 @@ restoreTerminalTabsLayoutSetting();
27391
28871
  restoreTerminalCustomGroups();
27392
28872
  restoreToolOutputExpansionSetting();
27393
28873
  restoreWorkspaceDashboardState();
28874
+ restoreInterfaceDensity();
27394
28875
  initializeTerminalHeaderTooltips();
27395
28876
  restoreSidePanelSectionState();
27396
28877
  bindSidePanelSectionToggles();