@firstpick/pi-package-webui 0.7.8 → 0.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -17,6 +17,7 @@ const elements = {
17
17
  tabBar: $("#tabBar"),
18
18
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
19
19
  splitTabButton: $("#splitTabButton"),
20
+ workspaceSaveButton: $("#workspaceSaveButton"),
20
21
  newTabMenu: $("#newTabMenu"),
21
22
  newTabButton: $("#newTabButton"),
22
23
  newTabMenuPanel: $("#newTabMenuPanel"),
@@ -57,7 +58,15 @@ const elements = {
57
58
  subagentTerminalStatus: $("#subagentTerminalStatus"),
58
59
  subagentTerminalCopyButton: $("#subagentTerminalCopyButton"),
59
60
  subagentTerminalRefreshButton: $("#subagentTerminalRefreshButton"),
61
+ subagentTerminalCancelButton: $("#subagentTerminalCancelButton"),
60
62
  subagentTerminalInput: $("#subagentTerminalInput"),
63
+ subagentCancelDialog: $("#subagentCancelDialog"),
64
+ subagentCancelDialogSubtitle: $("#subagentCancelDialogSubtitle"),
65
+ subagentCancelReason: $("#subagentCancelReason"),
66
+ subagentCancelNote: $("#subagentCancelNote"),
67
+ subagentCancelStatus: $("#subagentCancelStatus"),
68
+ subagentCancelKeepRunningButton: $("#subagentCancelKeepRunningButton"),
69
+ subagentCancelSubmitButton: $("#subagentCancelSubmitButton"),
61
70
  stickyUserPromptButton: $("#stickyUserPromptButton"),
62
71
  chat: $("#chat"),
63
72
  chatSearchBar: $("#chatSearchBar"),
@@ -75,6 +84,13 @@ const elements = {
75
84
  composerActionsButton: $("#composerActionsButton"),
76
85
  composerActionsPanel: $("#composerActionsPanel"),
77
86
  promptInput: $("#promptInput"),
87
+ followUpQueueTrigger: $("#followUpQueueTrigger"),
88
+ followUpQueueTriggerCount: $("#followUpQueueTriggerCount"),
89
+ followUpQueueOverlay: $("#followUpQueueOverlay"),
90
+ followUpQueueOverlayCount: $("#followUpQueueOverlayCount"),
91
+ followUpQueueRows: $("#followUpQueueRows"),
92
+ followUpQueueStatus: $("#followUpQueueStatus"),
93
+ followUpQueueCloseButton: $("#followUpQueueCloseButton"),
78
94
  busyPromptBehaviorTag: $("#busyPromptBehaviorTag"),
79
95
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
80
96
  sessionSkillTags: $("#sessionSkillTags"),
@@ -235,6 +251,12 @@ const elements = {
235
251
  fileViewerPreview: $("#fileViewerPreview"),
236
252
  fileViewerChanges: $("#fileViewerChanges"),
237
253
  fileViewerStatus: $("#fileViewerStatus"),
254
+ fileViewerSearchBar: $("#fileViewerSearchBar"),
255
+ fileViewerSearchInput: $("#fileViewerSearchInput"),
256
+ fileViewerSearchCount: $("#fileViewerSearchCount"),
257
+ fileViewerSearchPrevButton: $("#fileViewerSearchPrevButton"),
258
+ fileViewerSearchNextButton: $("#fileViewerSearchNextButton"),
259
+ fileViewerSearchCloseButton: $("#fileViewerSearchCloseButton"),
238
260
  fileSelectionBar: $("#fileSelectionBar"),
239
261
  fileSelectionSummary: $("#fileSelectionSummary"),
240
262
  fileSelectionCommentInput: $("#fileSelectionCommentInput"),
@@ -326,6 +348,19 @@ const elements = {
326
348
  confirmationUndo: $("#confirmationUndo"),
327
349
  confirmationCancelButton: $("#confirmationCancelButton"),
328
350
  confirmationConfirmButton: $("#confirmationConfirmButton"),
351
+ workspaceLoadDialog: $("#workspaceLoadDialog"),
352
+ workspaceLoadDialogCloseButton: $("#workspaceLoadDialogCloseButton"),
353
+ workspaceLoadDialogStatus: $("#workspaceLoadDialogStatus"),
354
+ workspaceLoadDialogList: $("#workspaceLoadDialogList"),
355
+ workspaceReplaceDialog: $("#workspaceReplaceDialog"),
356
+ workspaceReplaceTargetName: $("#workspaceReplaceTargetName"),
357
+ workspaceReplaceCurrentTabsCount: $("#workspaceReplaceCurrentTabsCount"),
358
+ workspaceReplaceCurrentTabsList: $("#workspaceReplaceCurrentTabsList"),
359
+ workspaceReplaceSaveName: $("#workspaceReplaceSaveName"),
360
+ workspaceReplaceDialogStatus: $("#workspaceReplaceDialogStatus"),
361
+ workspaceReplaceCancelButton: $("#workspaceReplaceCancelButton"),
362
+ workspaceReplaceDiscardButton: $("#workspaceReplaceDiscardButton"),
363
+ workspaceReplaceSaveButton: $("#workspaceReplaceSaveButton"),
329
364
  gitWorktreeBaseDialog: $("#gitWorktreeBaseDialog"),
330
365
  gitWorktreeBaseBranch: $("#gitWorktreeBaseBranch"),
331
366
  gitWorktreeBaseOriginMain: $("#gitWorktreeBaseOriginMain"),
@@ -411,9 +446,16 @@ let activeTextAttachmentEditor = null;
411
446
  let activeSkillEditor = null;
412
447
  let fileTreeState = { root: "", entriesByPath: new Map(), expanded: new Set(), loading: new Set(), selectedPath: "", requestSerial: 0, searchQuery: "", searchEntries: [], searchLoading: false, searchTruncated: false, searchTotal: 0, gitStatusRoot: "", gitStatusByPath: new Map() };
413
448
  let activeFileViewer = null;
449
+ let fileViewersByTab = new Map();
414
450
  let fileViewerOpenRequestSerial = 0;
415
451
  let fileViewerGitChangesRequestSerial = 0;
416
452
  let fileViewerSelection = null;
453
+ let fileViewerSelectionsByTab = new Map();
454
+ let fileViewerSearchMatches = [];
455
+ let fileViewerSearchIndex = -1;
456
+ let fileViewerSearchTruncated = false;
457
+ let fileViewerSearchTimer = null;
458
+ let fileViewerSearchHighlightElement = null;
417
459
  let fileContextMenuState = null;
418
460
  let sidePanelContextMenuState = null;
419
461
  let fileTreeDragState = null;
@@ -482,6 +524,8 @@ const supervisorContinuityRefreshes = new Map();
482
524
  const supervisorEnvelopeWarnings = new Set();
483
525
  let activeDialog = null;
484
526
  let activeConfirmationResolve = null;
527
+ let activeWorkspaceReplacementResolve = null;
528
+ let workspaceLoadPickerFocusReturn = null;
485
529
  let activeGitWorktreeBaseResolve = null;
486
530
  let activeUndoAction = null;
487
531
  let undoToastTimer = null;
@@ -515,6 +559,11 @@ let mobileTabsExpanded = false;
515
559
  let openTerminalTabGroupKey = null;
516
560
  let terminalCustomGroups = new Map();
517
561
  let terminalCustomGroupSerial = 1;
562
+ let savedWorkspaces = [];
563
+ let savedWorkspacesLoaded = false;
564
+ let savedWorkspacesLoading = false;
565
+ let savedWorkspacesError = "";
566
+ let savedWorkspacesRefreshPromise = null;
518
567
  let terminalTabDragId = null;
519
568
  let splitTabId = null;
520
569
  let newTabMenuOpen = false;
@@ -587,7 +636,10 @@ let subagentOverlayLoading = false;
587
636
  let subagentOverlayRefreshTimer = null;
588
637
  let subagentOverlayRequestSerial = 0;
589
638
  let subagentOpenMode = "overlay";
639
+ let subagentCancelSelection = null;
640
+ let subagentCancelSubmitting = false;
590
641
  const subagentTerminalViews = new Map();
642
+ const subagentTerminalRestoredParentTabs = new Set();
591
643
  let activeSubagentTerminalId = null;
592
644
  let subagentTerminalRefreshTimer = null;
593
645
  let subagentLaunchSlotConfig = null;
@@ -679,6 +731,12 @@ let abortRequestInFlight = false;
679
731
  let userBashByTab = new Map();
680
732
  let userBashQueuesByTab = new Map();
681
733
  let latestQueuedMessagesByTab = new Map();
734
+ let followUpQueueOpen = false;
735
+ const followUpQueueMutationsInFlightByTab = new Set();
736
+ let followUpQueueStatus = { text: "", level: "" };
737
+ let followUpQueueRestoreFocus = null;
738
+ let followUpQueueDrag = null;
739
+ let followUpQueueSuppressBlurFor = null;
682
740
  let loadedPromptList = null;
683
741
  let promptListRunning = false;
684
742
  let workspaceDashboardCollapsed = false;
@@ -1869,6 +1927,7 @@ function isInteractiveDropdownOpen() {
1869
1927
  || optionsMenuOpen
1870
1928
  || conversationVoiceMenuOpen
1871
1929
  || busyPromptBehaviorMenuOpen
1930
+ || followUpQueueOpen
1872
1931
  || newTabMenuOpen
1873
1932
  || isFooterPickerOpen()
1874
1933
  || elements.commandSuggest?.hidden === false
@@ -2362,7 +2421,9 @@ function setSubagentOpenMode(mode, { persist = true, announce = false } = {}) {
2362
2421
  subagentOpenMode = normalizeSubagentOpenMode(mode);
2363
2422
  if (persist) persistSubagentOpenMode(subagentOpenMode);
2364
2423
  renderSubagentOpenModeControl();
2424
+ const materializedTerminalViews = subagentOpenMode === "tab" && materializeRetainedSubagentTerminalViews();
2365
2425
  renderSubagents();
2426
+ if (materializedTerminalViews) renderTabs();
2366
2427
  if (announce) addEvent(`subagents now open in ${SUBAGENT_OPEN_MODE_LABELS[subagentOpenMode].toLowerCase()}`);
2367
2428
  }
2368
2429
 
@@ -2433,6 +2494,384 @@ function persistTerminalCustomGroups() {
2433
2494
  }
2434
2495
  }
2435
2496
 
2497
+ function workspaceGroupsForSave() {
2498
+ const liveTabIds = new Set(tabs.map((tab) => tab.id).filter(Boolean));
2499
+ return [...terminalCustomGroups.values()].map((group) => ({
2500
+ title: normalizeTerminalCustomGroupTitle(group.title),
2501
+ tabIds: normalizeTerminalCustomGroupTabIds(group.tabIds).filter((tabId) => liveTabIds.has(tabId)),
2502
+ })).filter((group) => group.tabIds.length >= 2);
2503
+ }
2504
+
2505
+ function workspaceDefaultName() {
2506
+ const cwd = String(activeTab()?.cwd || tabs[0]?.cwd || "workspace").replace(/[\\/]+$/, "");
2507
+ const base = cwd.split(/[\\/]/).pop() || "workspace";
2508
+ return `${base} ${new Date().toISOString().slice(0, 10)}`;
2509
+ }
2510
+
2511
+ function setSavedWorkspaces(workspaces) {
2512
+ savedWorkspaces = Array.isArray(workspaces) ? workspaces.filter((workspace) => workspace?.id && workspace?.name) : [];
2513
+ savedWorkspacesLoaded = true;
2514
+ savedWorkspacesError = "";
2515
+ }
2516
+
2517
+ async function refreshSavedWorkspaces({ force = false } = {}) {
2518
+ if (!force && savedWorkspacesLoaded) return savedWorkspaces;
2519
+ if (savedWorkspacesRefreshPromise) return savedWorkspacesRefreshPromise;
2520
+ savedWorkspacesLoading = true;
2521
+ savedWorkspacesError = "";
2522
+ renderWorkspaceDashboard();
2523
+ savedWorkspacesRefreshPromise = api("/api/workspaces", { scoped: false })
2524
+ .then((response) => {
2525
+ setSavedWorkspaces(response.data?.workspaces);
2526
+ return savedWorkspaces;
2527
+ })
2528
+ .catch((error) => {
2529
+ savedWorkspacesError = error.message || String(error);
2530
+ throw error;
2531
+ })
2532
+ .finally(() => {
2533
+ savedWorkspacesLoading = false;
2534
+ savedWorkspacesRefreshPromise = null;
2535
+ renderWorkspaceDashboard();
2536
+ });
2537
+ return savedWorkspacesRefreshPromise;
2538
+ }
2539
+
2540
+ function installLoadedWorkspaceGroups(groups, idMap = {}) {
2541
+ const liveTabIds = new Set(tabs.map((tab) => tab.id).filter(Boolean));
2542
+ const claimedTabIds = new Set();
2543
+ terminalCustomGroups = new Map();
2544
+ terminalCustomGroupSerial = 1;
2545
+ for (const savedGroup of Array.isArray(groups) ? groups : []) {
2546
+ const tabIds = normalizeTerminalCustomGroupTabIds(savedGroup?.tabIds)
2547
+ .map((tabId) => idMap?.[tabId] || tabId)
2548
+ .filter((tabId) => liveTabIds.has(tabId) && !claimedTabIds.has(tabId));
2549
+ if (tabIds.length < 2) continue;
2550
+ for (const tabId of tabIds) claimedTabIds.add(tabId);
2551
+ let id = nextTerminalCustomGroupId();
2552
+ while (terminalCustomGroups.has(id)) id = nextTerminalCustomGroupId();
2553
+ terminalCustomGroups.set(id, {
2554
+ id,
2555
+ title: normalizeTerminalCustomGroupTitle(savedGroup?.title, `Group ${terminalCustomGroups.size + 1}`),
2556
+ tabIds,
2557
+ });
2558
+ }
2559
+ persistTerminalCustomGroups();
2560
+ }
2561
+
2562
+ function workspaceRestoreSummary(restoredCount, warnings) {
2563
+ const restored = `${restoredCount} tab${restoredCount === 1 ? "" : "s"} restored`;
2564
+ if (!warnings.length) return restored;
2565
+ return `${restored}; ${warnings.length} warning${warnings.length === 1 ? "" : "s"}`;
2566
+ }
2567
+
2568
+ async function hydrateLoadedWorkspaceActiveTab(requestedTabId) {
2569
+ const targetTabId = requestedTabId && tabs.some((tab) => tab.id === requestedTabId) ? requestedTabId : tabs[0]?.id || null;
2570
+ if (!targetTabId) return;
2571
+ if (targetTabId !== activeTabId) {
2572
+ await switchTab(targetTabId);
2573
+ return;
2574
+ }
2575
+ const tabContext = setActiveTabId(targetTabId, { remember: true });
2576
+ resetActiveTabUi();
2577
+ renderTabs();
2578
+ restoreActiveDraft();
2579
+ focusPromptInput({ defer: true });
2580
+ connectEvents(tabContext);
2581
+ await refreshAll(tabContext);
2582
+ if (isCurrentTabContext(tabContext)) markTabOutputSeen();
2583
+ }
2584
+
2585
+ async function saveWebuiWorkspace({ triggerButton = elements.workspaceSaveButton } = {}) {
2586
+ if (!tabs.length) return;
2587
+ const promptedName = window.prompt("Save workspace as:", workspaceDefaultName());
2588
+ if (promptedName === null) return;
2589
+ const body = {
2590
+ name: promptedName.trim() || workspaceDefaultName(),
2591
+ groups: workspaceGroupsForSave(),
2592
+ activeTabId,
2593
+ };
2594
+ const controls = new Set([elements.workspaceSaveButton, triggerButton].filter(Boolean));
2595
+ for (const control of controls) control.disabled = true;
2596
+ try {
2597
+ let response;
2598
+ try {
2599
+ response = await api("/api/workspaces", { method: "POST", body, scoped: false });
2600
+ } catch (error) {
2601
+ if (error.statusCode !== 409) throw error;
2602
+ const overwrite = await appConfirm({
2603
+ title: "Overwrite saved workspace?",
2604
+ summary: `A workspace named “${body.name || workspaceDefaultName()}” already exists.`,
2605
+ affected: "The existing saved workspace will be replaced with the current tabs and groups.",
2606
+ confirmLabel: "Overwrite",
2607
+ });
2608
+ if (!overwrite) return;
2609
+ response = await api("/api/workspaces", { method: "POST", body: { ...body, overwrite: true }, scoped: false });
2610
+ }
2611
+ const data = response.data || {};
2612
+ setSavedWorkspaces(data.workspaces);
2613
+ const saved = data.workspace;
2614
+ const evicted = Array.isArray(data.evicted) ? data.evicted : [];
2615
+ const message = `Saved workspace ${saved?.name || "workspace"} (${saved?.tabCount || tabs.length} tabs).`;
2616
+ settleUndoToast(evicted.length ? `${message} Oldest saved workspace removed.` : message);
2617
+ addEvent(message, "success");
2618
+ if (evicted.length) addEvent(`Removed ${evicted.length} oldest saved workspace${evicted.length === 1 ? "" : "s"} to keep the saved-workspace limit.`, "warn");
2619
+ } catch (error) {
2620
+ const message = `Could not save workspace: ${error.message || String(error)}`;
2621
+ settleUndoToast(message, { error: true, timeoutMs: 7000 });
2622
+ addEvent(message, "error");
2623
+ } finally {
2624
+ for (const control of controls) control.disabled = control === elements.workspaceSaveButton ? tabs.length === 0 : false;
2625
+ }
2626
+ }
2627
+
2628
+ function renderWorkspaceLoadDialog() {
2629
+ const list = elements.workspaceLoadDialogList;
2630
+ const status = elements.workspaceLoadDialogStatus;
2631
+ if (!list || !status) return;
2632
+ list.replaceChildren();
2633
+ if (savedWorkspacesLoading) {
2634
+ status.textContent = "Loading saved workspaces…";
2635
+ return;
2636
+ }
2637
+ if (savedWorkspacesError) {
2638
+ status.textContent = `Could not load saved workspaces: ${savedWorkspacesError}`;
2639
+ const retry = make("button", "workspace-load-dialog-retry", "Retry");
2640
+ retry.type = "button";
2641
+ retry.addEventListener("click", () => refreshWorkspaceLoadDialog());
2642
+ list.append(retry);
2643
+ return;
2644
+ }
2645
+ if (!savedWorkspaces.length) {
2646
+ status.textContent = tabs.length
2647
+ ? "No saved workspaces yet. Use Save workspace to capture the current tabs."
2648
+ : "No saved workspaces yet. Open tabs, then use Save workspace.";
2649
+ return;
2650
+ }
2651
+ status.textContent = `${savedWorkspaces.length} saved workspace${savedWorkspaces.length === 1 ? "" : "s"} available.`;
2652
+ for (const workspace of savedWorkspaces) {
2653
+ const row = make("article", "workspace-load-dialog-item");
2654
+ const copy = make("div", "workspace-load-dialog-item-copy");
2655
+ const title = make("strong", "workspace-load-dialog-item-name", workspace.name);
2656
+ title.title = workspace.name;
2657
+ const detail = [
2658
+ formatDate(workspace.savedAt),
2659
+ `${workspace.tabCount || 0} tab${workspace.tabCount === 1 ? "" : "s"}`,
2660
+ workspace.groupCount ? `${workspace.groupCount} group${workspace.groupCount === 1 ? "" : "s"}` : "",
2661
+ Array.isArray(workspace.cwds) && workspace.cwds.length ? normalizeDisplayPath(workspace.cwds[0]) : "",
2662
+ ].filter(Boolean).join(" · ");
2663
+ copy.append(title, make("span", "workspace-load-dialog-item-detail", detail));
2664
+ const actions = make("div", "workspace-load-dialog-item-actions");
2665
+ const load = make("button", "workspace-load-dialog-item-load primary", "Load");
2666
+ load.type = "button";
2667
+ load.setAttribute("aria-label", `Load workspace ${workspace.name}`);
2668
+ load.addEventListener("click", async () => {
2669
+ const focusReturn = workspaceLoadPickerFocusReturn;
2670
+ closeWorkspaceLoadDialog({ restoreFocus: false });
2671
+ const result = await loadWebuiWorkspace(workspace.id, { triggerButton: load });
2672
+ if (result === "cancelled") await openWorkspaceLoadPicker({ triggerButton: focusReturn });
2673
+ else if (result === "error" && focusReturn instanceof HTMLElement && focusReturn.isConnected) focusReturn.focus({ preventScroll: true });
2674
+ });
2675
+ const remove = make("button", "workspace-load-dialog-item-delete danger", "Delete");
2676
+ remove.type = "button";
2677
+ remove.setAttribute("aria-label", `Delete workspace ${workspace.name}`);
2678
+ remove.addEventListener("click", async () => {
2679
+ if (!(await deleteWebuiWorkspace(workspace))) return;
2680
+ renderWorkspaceLoadDialog();
2681
+ queueMicrotask(() => elements.workspaceLoadDialogCloseButton?.focus({ preventScroll: true }));
2682
+ });
2683
+ actions.append(load, remove);
2684
+ row.append(copy, actions);
2685
+ list.append(row);
2686
+ }
2687
+ }
2688
+
2689
+ async function refreshWorkspaceLoadDialog() {
2690
+ const refresh = refreshSavedWorkspaces({ force: true });
2691
+ renderWorkspaceLoadDialog();
2692
+ try {
2693
+ await refresh;
2694
+ } catch {
2695
+ // The picker renders the saved error state from refreshSavedWorkspaces.
2696
+ }
2697
+ renderWorkspaceLoadDialog();
2698
+ }
2699
+
2700
+ function closeWorkspaceLoadDialog({ restoreFocus = true } = {}) {
2701
+ const dialog = elements.workspaceLoadDialog;
2702
+ if (!restoreFocus) workspaceLoadPickerFocusReturn = null;
2703
+ if (dialog?.open) dialog.close();
2704
+ const target = workspaceLoadPickerFocusReturn;
2705
+ workspaceLoadPickerFocusReturn = null;
2706
+ if (restoreFocus && target instanceof HTMLElement && target.isConnected) queueMicrotask(() => target.focus());
2707
+ }
2708
+
2709
+ async function openWorkspaceLoadPicker({ triggerButton = null } = {}) {
2710
+ const dialog = elements.workspaceLoadDialog;
2711
+ if (!dialog?.showModal) {
2712
+ setWorkspaceDashboardCollapsed(false, { persist: false });
2713
+ await refreshSavedWorkspaces({ force: true }).catch(() => {});
2714
+ return;
2715
+ }
2716
+ workspaceLoadPickerFocusReturn = triggerButton instanceof HTMLElement ? triggerButton : document.activeElement instanceof HTMLElement ? document.activeElement : null;
2717
+ renderWorkspaceLoadDialog();
2718
+ if (!dialog.open) dialog.showModal();
2719
+ queueMicrotask(() => elements.workspaceLoadDialogCloseButton?.focus());
2720
+ await refreshWorkspaceLoadDialog();
2721
+ }
2722
+
2723
+ function finishWorkspaceReplacement(choice = null) {
2724
+ const resolve = activeWorkspaceReplacementResolve;
2725
+ activeWorkspaceReplacementResolve = null;
2726
+ if (elements.workspaceReplaceDialog?.open) elements.workspaceReplaceDialog.close();
2727
+ resolve?.(choice);
2728
+ }
2729
+
2730
+ function workspaceReplacementTabRow(tab) {
2731
+ const indicator = tabIndicator(tab);
2732
+ const item = make("li", `workspace-replace-current-tab activity-${indicator.state}`);
2733
+ const title = make("strong", "workspace-replace-current-tab-title", tab.title || "Untitled tab");
2734
+ const detail = [
2735
+ tab.id === activeTabId ? "Active" : "",
2736
+ indicator.label,
2737
+ normalizeDisplayPath(tab.cwd || ""),
2738
+ ].filter(Boolean).join(" · ");
2739
+ item.append(title, make("span", "workspace-replace-current-tab-detail", detail));
2740
+ return item;
2741
+ }
2742
+
2743
+ function workspaceSaveCurrentDecision(name = elements.workspaceReplaceSaveName?.value) {
2744
+ return {
2745
+ replaceOpenTabs: true,
2746
+ saveCurrent: {
2747
+ name: String(name || "").trim() || workspaceDefaultName(),
2748
+ groups: workspaceGroupsForSave(),
2749
+ activeTabId,
2750
+ },
2751
+ };
2752
+ }
2753
+
2754
+ function chooseWorkspaceReplacement(workspace) {
2755
+ if (!tabs.length) return Promise.resolve({});
2756
+ const dialog = elements.workspaceReplaceDialog;
2757
+ if (!dialog?.showModal) {
2758
+ const discard = window.confirm(`Loading ${workspace?.name || "this workspace"} will terminate ${tabs.length} current Pi process${tabs.length === 1 ? "" : "es"}. Choose OK to load without saving, or Cancel to save first.`);
2759
+ if (discard) return Promise.resolve({ replaceOpenTabs: true, discardCurrent: true });
2760
+ const name = window.prompt("Save current workspace as:", workspaceDefaultName());
2761
+ if (name === null) return Promise.resolve(null);
2762
+ return Promise.resolve(workspaceSaveCurrentDecision(name));
2763
+ }
2764
+ if (activeWorkspaceReplacementResolve) finishWorkspaceReplacement(null);
2765
+ if (elements.workspaceReplaceTargetName) elements.workspaceReplaceTargetName.textContent = workspace?.name || "this workspace";
2766
+ if (elements.workspaceReplaceCurrentTabsCount) elements.workspaceReplaceCurrentTabsCount.textContent = `${tabs.length} tab${tabs.length === 1 ? "" : "s"}`;
2767
+ elements.workspaceReplaceCurrentTabsList?.replaceChildren(...tabs.map(workspaceReplacementTabRow));
2768
+ if (elements.workspaceReplaceSaveName) elements.workspaceReplaceSaveName.value = workspaceDefaultName();
2769
+ if (elements.workspaceReplaceDialogStatus) elements.workspaceReplaceDialogStatus.textContent = "Cancel leaves every current tab unchanged.";
2770
+ return new Promise((resolve) => {
2771
+ activeWorkspaceReplacementResolve = resolve;
2772
+ dialog.showModal();
2773
+ queueMicrotask(() => elements.workspaceReplaceCancelButton?.focus());
2774
+ });
2775
+ }
2776
+
2777
+ function retireClosedWorkspaceTabContexts(closedIds) {
2778
+ const closed = new Set(Array.isArray(closedIds) ? closedIds.filter((id) => typeof id === "string" && id) : []);
2779
+ if (!closed.size) return;
2780
+ tabs = tabs.filter((tab) => !closed.has(tab.id));
2781
+ syncTabMetadata(tabs);
2782
+ for (const id of closed) {
2783
+ tabDrafts.delete(id);
2784
+ clearAttachments(id);
2785
+ fileViewersByTab.delete(id);
2786
+ fileViewerSelectionsByTab.delete(id);
2787
+ btwWidgetDismissedIdsByTab.delete(id);
2788
+ removeSubagentTerminalViewsForParent(id);
2789
+ }
2790
+ syncTerminalCustomGroupsWithTabs(tabs);
2791
+ clearOpenTerminalTabGroup(null, { force: true });
2792
+ if (closed.has(activeTabId)) setActiveTabId(null, { remember: true });
2793
+ }
2794
+
2795
+ async function loadWebuiWorkspace(workspaceId, { triggerButton = null } = {}) {
2796
+ const decision = await chooseWorkspaceReplacement(savedWorkspaces.find((workspace) => workspace.id === workspaceId));
2797
+ if (decision === null) return "cancelled";
2798
+ const controls = new Set([triggerButton].filter(Boolean));
2799
+ for (const control of controls) control.disabled = true;
2800
+ try {
2801
+ let response;
2802
+ try {
2803
+ response = await api(`/api/workspaces/${encodeURIComponent(workspaceId)}/load`, {
2804
+ method: "POST",
2805
+ ...(Object.keys(decision).length ? { body: decision } : {}),
2806
+ scoped: false,
2807
+ });
2808
+ } catch (error) {
2809
+ const saveCurrent = decision.saveCurrent;
2810
+ if (!saveCurrent || error.statusCode !== 409 || !/workspace with that name already exists/i.test(error.message || "")) throw error;
2811
+ const overwrite = await appConfirm({
2812
+ title: "Overwrite saved workspace?",
2813
+ summary: `A workspace named “${saveCurrent.name || workspaceDefaultName()}” already exists.`,
2814
+ affected: "The existing saved workspace will be replaced before the current tabs are closed.",
2815
+ confirmLabel: "Overwrite & load",
2816
+ });
2817
+ if (!overwrite) return "cancelled";
2818
+ response = await api(`/api/workspaces/${encodeURIComponent(workspaceId)}/load`, {
2819
+ method: "POST",
2820
+ body: { ...decision, saveCurrent: { ...saveCurrent, overwrite: true } },
2821
+ scoped: false,
2822
+ });
2823
+ }
2824
+ const data = response.data || {};
2825
+ const closedIds = Array.isArray(data.closedIds) ? data.closedIds : [];
2826
+ retireClosedWorkspaceTabContexts(closedIds);
2827
+ if (Array.isArray(data.savedCurrent?.workspaces)) setSavedWorkspaces(data.savedCurrent.workspaces);
2828
+ const evicted = Array.isArray(data.savedCurrent?.evicted) ? data.savedCurrent.evicted : [];
2829
+ if (evicted.length) addEvent(`Removed ${evicted.length} oldest saved workspace${evicted.length === 1 ? "" : "s"} to keep the saved-workspace limit.`, "warn");
2830
+ await refreshTabs();
2831
+ installLoadedWorkspaceGroups(data.groups, data.idMap);
2832
+ await hydrateLoadedWorkspaceActiveTab(data.activeTabId);
2833
+ const warnings = Array.isArray(data.warnings) ? data.warnings : [];
2834
+ const restoredCount = Array.isArray(data.tabs) ? data.tabs.length : tabs.length;
2835
+ const replacement = closedIds.length ? `Replaced ${closedIds.length} current tab${closedIds.length === 1 ? "" : "s"}; ` : "";
2836
+ const message = `${replacement}${workspaceRestoreSummary(restoredCount, warnings)}`;
2837
+ settleUndoToast(message, { error: warnings.length > 0, timeoutMs: warnings.length ? 7000 : 3500 });
2838
+ addEvent(message, warnings.length ? "warn" : "success");
2839
+ for (const warning of warnings) addEvent(`Workspace restore: ${warning.message || "A saved tab could not be fully restored."}`, "warn");
2840
+ return "loaded";
2841
+ } catch (error) {
2842
+ const message = `Could not load workspace: ${error.message || String(error)}`;
2843
+ settleUndoToast(message, { error: true, timeoutMs: 7000 });
2844
+ addEvent(message, "error");
2845
+ return "error";
2846
+ } finally {
2847
+ for (const control of controls) control.disabled = false;
2848
+ }
2849
+ }
2850
+
2851
+ async function deleteWebuiWorkspace(workspace) {
2852
+ if (!workspace?.id) return false;
2853
+ const confirmed = await appConfirm({
2854
+ title: "Delete saved workspace?",
2855
+ summary: `Delete “${workspace.name}” from the saved workspace list?`,
2856
+ affected: "The saved tab constellation will be permanently removed; open tabs are unchanged.",
2857
+ confirmLabel: "Delete",
2858
+ });
2859
+ if (!confirmed) return false;
2860
+ try {
2861
+ const response = await api(`/api/workspaces/${encodeURIComponent(workspace.id)}`, { method: "DELETE", scoped: false });
2862
+ setSavedWorkspaces(response.data?.workspaces);
2863
+ const message = `Deleted saved workspace ${workspace.name}.`;
2864
+ settleUndoToast(message);
2865
+ addEvent(message, "success");
2866
+ return true;
2867
+ } catch (error) {
2868
+ const message = `Could not delete workspace: ${error.message || String(error)}`;
2869
+ settleUndoToast(message, { error: true, timeoutMs: 7000 });
2870
+ addEvent(message, "error");
2871
+ return false;
2872
+ }
2873
+ }
2874
+
2436
2875
  function terminalCustomGroupByTabId() {
2437
2876
  const map = new Map();
2438
2877
  for (const [groupId, group] of terminalCustomGroups) {
@@ -3096,6 +3535,7 @@ function renderBusyPromptBehaviorTag() {
3096
3535
  }
3097
3536
 
3098
3537
  function setBusyPromptBehaviorMenuOpen(open, { focusCurrent = false } = {}) {
3538
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
3099
3539
  busyPromptBehaviorMenuOpen = !!open;
3100
3540
  elements.busyPromptBehaviorTag?.setAttribute("aria-expanded", busyPromptBehaviorMenuOpen ? "true" : "false");
3101
3541
  elements.busyPromptBehaviorTag?.classList.toggle("menu-open", busyPromptBehaviorMenuOpen);
@@ -3164,6 +3604,7 @@ async function refreshNativeSettings(tabContext = activeTabContext()) {
3164
3604
 
3165
3605
  function setComposerActionsOpen(open) {
3166
3606
  const shouldOpen = open && isMobileView();
3607
+ if (shouldOpen && followUpQueueOpen) setFollowUpQueueOpen(false);
3167
3608
  document.body.classList.toggle("composer-actions-open", shouldOpen);
3168
3609
  elements.composerActionsButton.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
3169
3610
  if (!shouldOpen) {
@@ -4925,17 +5366,18 @@ function isFileDrag(event) {
4925
5366
  }
4926
5367
 
4927
5368
  function handleComposerDragOver(event) {
4928
- if (!isFileDrag(event)) return;
5369
+ if (event.target?.closest?.("#followUpQueueOverlay") || !isFileDrag(event)) return;
4929
5370
  event.preventDefault();
4930
5371
  elements.composer.classList.add("drag-over");
4931
5372
  }
4932
5373
 
4933
5374
  function handleComposerDragLeave(event) {
5375
+ if (event.target?.closest?.("#followUpQueueOverlay")) return;
4934
5376
  if (!elements.composer.contains(event.relatedTarget)) elements.composer.classList.remove("drag-over");
4935
5377
  }
4936
5378
 
4937
5379
  function handleComposerDrop(event) {
4938
- if (!isFileDrag(event)) return;
5380
+ if (event.target?.closest?.("#followUpQueueOverlay") || !isFileDrag(event)) return;
4939
5381
  event.preventDefault();
4940
5382
  elements.composer.classList.remove("drag-over");
4941
5383
  addAttachmentFiles(event.dataTransfer?.files, "drop");
@@ -5744,6 +6186,7 @@ let conversationVoicePending = null;
5744
6186
  // panel (hover/focus-within still work on desktop via CSS), so it also works
5745
6187
  // on touch devices where :hover never fires.
5746
6188
  function setConversationVoiceMenuOpen(open) {
6189
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
5747
6190
  conversationVoiceMenuOpen = !!open;
5748
6191
  elements.conversationVoiceButton?.setAttribute("aria-expanded", conversationVoiceMenuOpen ? "true" : "false");
5749
6192
  elements.conversationVoiceButton?.classList.toggle("menu-open", conversationVoiceMenuOpen);
@@ -7633,6 +8076,7 @@ function updateActiveFileViewerAfterMove(sourcePath = "", destinationPath = "")
7633
8076
  gitChanges: null,
7634
8077
  };
7635
8078
  if (fileViewerSelection) fileViewerSelection = { ...fileViewerSelection, path: nextPath, fileName: activeFileViewer.name };
8079
+ cacheActiveFileViewerForTab();
7636
8080
  updateFileViewerUi();
7637
8081
  }
7638
8082
 
@@ -8052,6 +8496,10 @@ function setFileViewerMode(mode = "source") {
8052
8496
  activeFileViewer.mode = resolveFileViewerMode({ ...activeFileViewer, mode });
8053
8497
  if (activeFileViewer.mode === "changes" && previousMode !== "changes") clearFileViewerSelection();
8054
8498
  updateFileViewerUi();
8499
+ if (elements.fileViewerSearchBar && !elements.fileViewerSearchBar.hidden) {
8500
+ fileViewerSearchIndex = -1;
8501
+ runFileViewerSearch({ navigate: true });
8502
+ }
8055
8503
  }
8056
8504
 
8057
8505
  function setFileViewerDirty(dirty) {
@@ -8067,7 +8515,10 @@ function updateFileViewerUi() {
8067
8515
  if (elements.fileViewerPane) elements.fileViewerPane.hidden = !open;
8068
8516
  requestAnimationFrame(syncResizablePanelWidthsForViewport);
8069
8517
  updateFileViewerResizeHandle();
8070
- if (!open) return;
8518
+ if (!open) {
8519
+ closeFileViewerSearch({ restoreFocus: false });
8520
+ return;
8521
+ }
8071
8522
  if (!isSidePanelOverlayView()) applyFileViewerWidth(currentFileViewerWidth());
8072
8523
  const viewer = activeFileViewer;
8073
8524
  const isMarkdown = viewer.language === "markdown";
@@ -8120,6 +8571,158 @@ function updateFileViewerUi() {
8120
8571
  elements.fileViewerOpenDefaultButton.disabled = viewer.readOnly === true || !viewerPath;
8121
8572
  }
8122
8573
  renderFileViewerSelectionBar();
8574
+ if (elements.fileViewerSearchBar && !elements.fileViewerSearchBar.hidden) {
8575
+ fileViewerSearchIndex = -1;
8576
+ runFileViewerSearch({ navigate: false });
8577
+ }
8578
+ }
8579
+
8580
+ const FILE_VIEWER_SEARCH_MATCH_LIMIT = 10_000;
8581
+
8582
+ function fileViewerSearchQueryText() {
8583
+ return String(elements.fileViewerSearchInput?.value || "");
8584
+ }
8585
+
8586
+ function fileViewerSearchSurface() {
8587
+ const mode = resolveFileViewerMode(activeFileViewer);
8588
+ if (mode === "preview") return elements.fileViewerPreview;
8589
+ if (mode === "changes") return elements.fileViewerChanges;
8590
+ return elements.fileViewerEditor;
8591
+ }
8592
+
8593
+ function fileViewerSearchText() {
8594
+ const surface = fileViewerSearchSurface();
8595
+ if (surface === elements.fileViewerEditor) return String(surface?.value ?? activeFileViewer?.content ?? "");
8596
+ return String(surface?.textContent || "");
8597
+ }
8598
+
8599
+ function collectFileViewerSearchMatches(query = fileViewerSearchQueryText()) {
8600
+ const haystack = fileViewerSearchText().toLowerCase();
8601
+ const needle = String(query || "").toLowerCase();
8602
+ if (!needle) return { matches: [], truncated: false };
8603
+ const matches = [];
8604
+ let offset = 0;
8605
+ while (matches.length < FILE_VIEWER_SEARCH_MATCH_LIMIT) {
8606
+ const index = haystack.indexOf(needle, offset);
8607
+ if (index < 0) return { matches, truncated: false };
8608
+ matches.push({ start: index, end: index + needle.length });
8609
+ offset = index + needle.length;
8610
+ }
8611
+ return { matches, truncated: haystack.indexOf(needle, offset) >= 0 };
8612
+ }
8613
+
8614
+ function updateFileViewerSearchCount() {
8615
+ if (!elements.fileViewerSearchCount) return;
8616
+ const query = fileViewerSearchQueryText();
8617
+ if (!query) elements.fileViewerSearchCount.textContent = "";
8618
+ else if (!fileViewerSearchMatches.length) elements.fileViewerSearchCount.textContent = "0/0";
8619
+ else elements.fileViewerSearchCount.textContent = `${fileViewerSearchIndex + 1}/${fileViewerSearchMatches.length}${fileViewerSearchTruncated ? "+" : ""}`;
8620
+ }
8621
+
8622
+ function textOffsetPosition(root, offset) {
8623
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
8624
+ let remaining = Math.max(0, offset);
8625
+ let node = walker.nextNode();
8626
+ while (node) {
8627
+ const length = node.nodeValue?.length || 0;
8628
+ if (remaining <= length) return { node, offset: remaining };
8629
+ remaining -= length;
8630
+ node = walker.nextNode();
8631
+ }
8632
+ return null;
8633
+ }
8634
+
8635
+ function clearFileViewerSearchHighlight() {
8636
+ globalThis.CSS?.highlights?.delete("file-viewer-search-current");
8637
+ fileViewerSearchHighlightElement?.classList.remove("file-viewer-search-current-fallback");
8638
+ fileViewerSearchHighlightElement = null;
8639
+ }
8640
+
8641
+ function focusFileViewerSearchMatch() {
8642
+ const match = fileViewerSearchMatches[fileViewerSearchIndex];
8643
+ const surface = fileViewerSearchSurface();
8644
+ clearFileViewerSearchHighlight();
8645
+ if (!match || !surface) return;
8646
+ if (surface === elements.fileViewerEditor) {
8647
+ surface.setSelectionRange(match.start, match.end);
8648
+ const lineIndex = surface.value.slice(0, match.start).split("\n").length - 1;
8649
+ const computedStyle = getComputedStyle(surface);
8650
+ const parsedLineHeight = Number.parseFloat(computedStyle.lineHeight);
8651
+ const fontSize = Number.parseFloat(computedStyle.fontSize) || 14;
8652
+ const lineHeight = !parsedLineHeight ? fontSize * 1.45 : parsedLineHeight < 8 ? parsedLineHeight * fontSize : parsedLineHeight;
8653
+ surface.scrollTop = Math.max(0, (lineIndex * lineHeight) - (surface.clientHeight / 2));
8654
+ } else {
8655
+ const start = textOffsetPosition(surface, match.start);
8656
+ const end = textOffsetPosition(surface, match.end);
8657
+ if (start && end) {
8658
+ const range = document.createRange();
8659
+ range.setStart(start.node, start.offset);
8660
+ range.setEnd(end.node, end.offset);
8661
+ const HighlightConstructor = globalThis.Highlight;
8662
+ if (globalThis.CSS?.highlights && typeof HighlightConstructor === "function") {
8663
+ globalThis.CSS.highlights.set("file-viewer-search-current", new HighlightConstructor(range));
8664
+ } else {
8665
+ fileViewerSearchHighlightElement = start.node.parentElement;
8666
+ fileViewerSearchHighlightElement?.classList.add("file-viewer-search-current-fallback");
8667
+ }
8668
+ start.node.parentElement?.scrollIntoView({ block: "center", behavior: "instant" });
8669
+ }
8670
+ }
8671
+ elements.fileViewerSearchInput?.focus({ preventScroll: true });
8672
+ updateFileViewerSearchCount();
8673
+ }
8674
+
8675
+ function runFileViewerSearch({ navigate = false } = {}) {
8676
+ const surface = fileViewerSearchSurface();
8677
+ if (surface?.id) elements.fileViewerSearchInput?.setAttribute("aria-controls", surface.id);
8678
+ const result = collectFileViewerSearchMatches();
8679
+ fileViewerSearchMatches = result.matches;
8680
+ fileViewerSearchTruncated = result.truncated;
8681
+ if (!fileViewerSearchMatches.length) fileViewerSearchIndex = -1;
8682
+ else if (fileViewerSearchIndex < 0 || fileViewerSearchIndex >= fileViewerSearchMatches.length) fileViewerSearchIndex = 0;
8683
+ updateFileViewerSearchCount();
8684
+ if (navigate) focusFileViewerSearchMatch();
8685
+ }
8686
+
8687
+ function stepFileViewerSearch(step) {
8688
+ if (!fileViewerSearchMatches.length) runFileViewerSearch();
8689
+ if (!fileViewerSearchMatches.length) return;
8690
+ fileViewerSearchIndex = (fileViewerSearchIndex + step + fileViewerSearchMatches.length) % fileViewerSearchMatches.length;
8691
+ focusFileViewerSearchMatch();
8692
+ }
8693
+
8694
+ function openFileViewerSearch() {
8695
+ if (!activeFileViewer || !elements.fileViewerSearchBar) return;
8696
+ closeChatSearch();
8697
+ const editor = fileViewerSearchSurface() === elements.fileViewerEditor ? elements.fileViewerEditor : null;
8698
+ const selectedText = editor && editor.selectionEnd > editor.selectionStart
8699
+ ? editor.value.slice(editor.selectionStart, editor.selectionEnd)
8700
+ : "";
8701
+ if (selectedText && !selectedText.includes("\n") && selectedText.length <= 200 && !fileViewerSearchQueryText()) {
8702
+ elements.fileViewerSearchInput.value = selectedText;
8703
+ }
8704
+ elements.fileViewerSearchBar.hidden = false;
8705
+ fileViewerSearchIndex = -1;
8706
+ runFileViewerSearch({ navigate: !!fileViewerSearchQueryText() });
8707
+ elements.fileViewerSearchInput?.focus({ preventScroll: true });
8708
+ elements.fileViewerSearchInput?.select();
8709
+ }
8710
+
8711
+ function closeFileViewerSearch({ restoreFocus = true } = {}) {
8712
+ if (!elements.fileViewerSearchBar || elements.fileViewerSearchBar.hidden) return;
8713
+ clearTimeout(fileViewerSearchTimer);
8714
+ fileViewerSearchTimer = null;
8715
+ clearFileViewerSearchHighlight();
8716
+ elements.fileViewerSearchBar.hidden = true;
8717
+ fileViewerSearchMatches = [];
8718
+ fileViewerSearchIndex = -1;
8719
+ fileViewerSearchTruncated = false;
8720
+ updateFileViewerSearchCount();
8721
+ if (!restoreFocus) return;
8722
+ const mode = resolveFileViewerMode(activeFileViewer);
8723
+ if (mode === "preview") elements.fileViewerPreview?.focus({ preventScroll: true });
8724
+ else if (mode === "changes") elements.fileViewerChanges?.focus({ preventScroll: true });
8725
+ else elements.fileViewerEditor?.focus({ preventScroll: true });
8123
8726
  }
8124
8727
 
8125
8728
  function fileViewerChangesNotice(text, level = "") {
@@ -8311,7 +8914,15 @@ async function sendFileSelectionToSession() {
8311
8914
  }
8312
8915
  }
8313
8916
 
8314
- function closeFileViewer() {
8917
+ function cacheActiveFileViewerForTab(tabId = activeTabId) {
8918
+ if (!tabId) return;
8919
+ if (activeFileViewer) fileViewersByTab.set(tabId, activeFileViewer);
8920
+ else fileViewersByTab.delete(tabId);
8921
+ if (fileViewerSelection) fileViewerSelectionsByTab.set(tabId, fileViewerSelection);
8922
+ else fileViewerSelectionsByTab.delete(tabId);
8923
+ }
8924
+
8925
+ function resetFileViewerUi() {
8315
8926
  fileViewerOpenRequestSerial += 1;
8316
8927
  activeFileViewer = null;
8317
8928
  clearFileViewerSelection();
@@ -8332,6 +8943,22 @@ function closeFileViewer() {
8332
8943
  setFileViewerStatus("");
8333
8944
  }
8334
8945
 
8946
+ function restoreFileViewerForActiveTab() {
8947
+ activeFileViewer = activeTabId ? fileViewersByTab.get(activeTabId) || null : null;
8948
+ fileViewerSelection = activeTabId ? fileViewerSelectionsByTab.get(activeTabId) || null : null;
8949
+ updateFileViewerUi();
8950
+ if (activeFileViewer?.dirty) setFileViewerStatus("Unsaved file edits.", "warn");
8951
+ else if (activeFileViewer) setFileViewerStatus("Restored for this terminal.", "success");
8952
+ }
8953
+
8954
+ function closeFileViewer() {
8955
+ if (activeTabId) {
8956
+ fileViewersByTab.delete(activeTabId);
8957
+ fileViewerSelectionsByTab.delete(activeTabId);
8958
+ }
8959
+ resetFileViewerUi();
8960
+ }
8961
+
8335
8962
  // Side-panel Git categories are UI labels; the read API uses its own allowlist.
8336
8963
  const GIT_FILE_DIFF_CATEGORY_BY_PANEL = Object.freeze({
8337
8964
  staged: "staged",
@@ -8376,10 +9003,10 @@ function gitFileChangesPlaceholder(category, repoRelPath, requestSerial) {
8376
9003
 
8377
9004
  async function applyGitFileChangesSnapshot(request, tabContext, viewerPath, requestSerial) {
8378
9005
  const snapshot = await request;
8379
- if (!isCurrentTabContext(tabContext)) return;
8380
- if (!activeFileViewer?.gitChanges?.loading || activeFileViewer.path !== viewerPath || activeFileViewer.gitChanges.requestSerial !== requestSerial) return;
8381
- activeFileViewer.gitChanges = snapshot;
8382
- updateFileViewerUi();
9006
+ const viewer = tabContext.tabId === activeTabId ? activeFileViewer : fileViewersByTab.get(tabContext.tabId);
9007
+ if (!viewer?.gitChanges?.loading || viewer.path !== viewerPath || viewer.gitChanges.requestSerial !== requestSerial) return;
9008
+ viewer.gitChanges = snapshot;
9009
+ if (viewer === activeFileViewer) updateFileViewerUi();
8383
9010
  }
8384
9011
 
8385
9012
  async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } = {}) {
@@ -8415,6 +9042,7 @@ async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } =
8415
9042
  };
8416
9043
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
8417
9044
  clearFileViewerSelection();
9045
+ cacheActiveFileViewerForTab();
8418
9046
  updateFileViewerUi();
8419
9047
  setFileViewerStatus("Opened in WebUI.", "success");
8420
9048
  if (changesRequest) void applyGitFileChangesSnapshot(changesRequest, tabContext, activeFileViewer.path, changesRequestSerial);
@@ -8440,6 +9068,7 @@ async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } =
8440
9068
  };
8441
9069
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = "";
8442
9070
  clearFileViewerSelection();
9071
+ cacheActiveFileViewerForTab();
8443
9072
  updateFileViewerUi();
8444
9073
  setFileViewerStatus("File content unavailable; showing Git changes (read-only).", "warn");
8445
9074
  return;
@@ -8474,6 +9103,7 @@ async function openAurReviewReportInViewer(path = "", repoRoot = "") {
8474
9103
  };
8475
9104
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
8476
9105
  clearFileViewerSelection();
9106
+ cacheActiveFileViewerForTab();
8477
9107
  updateFileViewerUi();
8478
9108
  setFileViewerStatus("Report opened in WebUI (read-only).", "success");
8479
9109
  } catch (error) {
@@ -8499,6 +9129,7 @@ async function saveActiveFileViewer() {
8499
9129
  if (!isCurrentTabContext(tabContext)) return;
8500
9130
  const data = response.data || {};
8501
9131
  activeFileViewer = { ...activeFileViewer, ...data, path: normalizeFileTreePath(data.path || activeFileViewer.path), content, dirty: false };
9132
+ cacheActiveFileViewerForTab();
8502
9133
  updateFileViewerUi();
8503
9134
  await loadFileTreeDirectory(fileParentPath(activeFileViewer.path), { force: true });
8504
9135
  setFileViewerStatus("Saved.", "success");
@@ -9017,8 +9648,9 @@ function resetActiveTabUi() {
9017
9648
  latestWorkspace = null;
9018
9649
  latestMessages = [];
9019
9650
  latestMessagesSessionKey = "";
9020
- closeFileViewer();
9651
+ resetFileViewerUi();
9021
9652
  resetFileTreeState();
9653
+ restoreFileViewerForActiveTab();
9022
9654
  clearRunIndicatorActivity({ render: false });
9023
9655
  statusEntries.clear();
9024
9656
  restoreWidgetsForActiveTab();
@@ -9915,8 +10547,6 @@ function terminalTabGroupTooltip(group, groupTitle = terminalDisplayGroupTitle(g
9915
10547
  return lines.join("\n");
9916
10548
  }
9917
10549
 
9918
- let terminalTabGroupSummarySerial = 0;
9919
-
9920
10550
  function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false, workflowModeActive = false, workflowCount = 0, subagent = false }) {
9921
10551
  const titleRow = make("span", "terminal-tab-title-row");
9922
10552
  const indicatorDot = make("span", "terminal-tab-activity-indicator");
@@ -10050,6 +10680,7 @@ function renderTerminalTabGroup(group, groupCount = 1) {
10050
10680
  button.setAttribute("aria-haspopup", "true");
10051
10681
  button.setAttribute("aria-expanded", group.key === openTerminalTabGroupKey ? "true" : "false");
10052
10682
  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}`);
10683
+ applyStyledTooltip(button, terminalTabGroupTooltip(group, groupTitle), { ariaLabel: false, description: true, placement: "right", variant: "workspace" });
10053
10684
  appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}${workflowModeActive ? " · workflow mode" : ""}${workflowCount ? ` · ${workflowCount} workflows` : ""}`, appRunnerRun, count: groupTabs.length, workflowModeActive, workflowCount });
10054
10685
  button.addEventListener("click", () => switchTab(activeGroupTab.id));
10055
10686
  wrapper.append(button);
@@ -10070,10 +10701,6 @@ function renderTerminalTabGroup(group, groupCount = 1) {
10070
10701
  const menu = make("div", "terminal-tab-group-menu");
10071
10702
  menu.setAttribute("role", "group");
10072
10703
  menu.setAttribute("aria-label", `${groupTitle} tabs`);
10073
- const summary = make("div", "terminal-tab-group-summary", terminalTabGroupTooltip(group, groupTitle));
10074
- summary.id = `terminalTabGroupSummary${++terminalTabGroupSummarySerial}`;
10075
- button.setAttribute("aria-describedby", summary.id);
10076
- menu.append(summary);
10077
10704
  for (const tab of groupTabs) menu.append(renderTerminalTabGroupItem(tab, group));
10078
10705
 
10079
10706
  const add = make("button", "terminal-tab-group-add", "+ Tab");
@@ -10112,6 +10739,7 @@ function clearOpenTerminalTabGroup(groupKey, { force = false } = {}) {
10112
10739
  }
10113
10740
 
10114
10741
  function setNewTabMenuOpen(open) {
10742
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
10115
10743
  newTabMenuOpen = !!open;
10116
10744
  elements.newTabButton?.setAttribute("aria-expanded", newTabMenuOpen ? "true" : "false");
10117
10745
  elements.newTabButton?.classList.toggle("menu-open", newTabMenuOpen);
@@ -10190,6 +10818,13 @@ function renderTabs() {
10190
10818
  }
10191
10819
  elements.tabBar.append(elements.newTabMenu);
10192
10820
  elements.closeAllTabsButton.disabled = tabs.length === 0;
10821
+ if (elements.workspaceSaveButton) {
10822
+ const canSave = tabs.length > 0;
10823
+ elements.workspaceSaveButton.disabled = !canSave;
10824
+ applyStyledTooltip(elements.workspaceSaveButton, canSave
10825
+ ? "Save workspace:\n• Captures all open tabs, sessions, order, custom groups, and the active tab."
10826
+ : "Save workspace is available after you open a tab.", { ariaLabel: canSave ? "Save workspace" : "Save workspace (no open tabs)", floating: false });
10827
+ }
10193
10828
  updateTerminalTabGroupOpenState();
10194
10829
  reconcileTerminalSplitState();
10195
10830
  setMobileTabsExpanded(mobileTabsExpanded);
@@ -10218,6 +10853,11 @@ async function refreshTabs({ selectStored = false } = {}) {
10218
10853
  setActiveTabId((requested && tabs.some((tab) => tab.id === requested) ? requested : stored && tabs.some((tab) => tab.id === stored) ? stored : tabs[0]?.id) || null, { remember: true });
10219
10854
  }
10220
10855
  rememberServerStartCwd(tabs.find((tab) => tab.id === activeTabId)?.cwd || tabs[0]?.cwd);
10856
+ if (!tabs.length && previousTabs.length) {
10857
+ savedWorkspacesLoaded = false;
10858
+ savedWorkspacesError = "";
10859
+ setWorkspaceDashboardCollapsed(false, { persist: false });
10860
+ }
10221
10861
  renderSessionSkillTags(activeTabId);
10222
10862
  renderTabs();
10223
10863
  return tabs;
@@ -10231,6 +10871,8 @@ async function switchTab(tabId) {
10231
10871
  }
10232
10872
  if (activeSubagentTerminalId) deactivateSubagentTerminalView({ render: false });
10233
10873
  clearOpenTerminalTabGroup(null, { force: true });
10874
+ setFollowUpQueueOpen(false);
10875
+ setFollowUpQueueStatus("");
10234
10876
  setMobileTabsExpanded(false);
10235
10877
  footerModelPickerOpen = false;
10236
10878
  footerThinkingPickerOpen = false;
@@ -10240,6 +10882,7 @@ async function switchTab(tabId) {
10240
10882
  saveActiveDraft();
10241
10883
  cacheMessagesForTab(activeTabId);
10242
10884
  cacheWidgetsForTab(activeTabId);
10885
+ cacheActiveFileViewerForTab(activeTabId);
10243
10886
  const tabContext = setActiveTabId(tabId, { remember: true });
10244
10887
  if (voiceConversation && voiceConversationTabId !== tabId) stopVoiceConversationLoop();
10245
10888
  resetActiveTabUi();
@@ -10443,7 +11086,7 @@ async function confirmCloseTerminalTabs(targetTabs, label) {
10443
11086
  });
10444
11087
  }
10445
11088
 
10446
- async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } = {}) {
11089
+ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", allowEmpty = false } = {}) {
10447
11090
  const targetIds = [...new Set(tabIds.filter(Boolean))];
10448
11091
  const targetTabs = targetIds.map((id) => tabs.find((item) => item.id === id)).filter(Boolean);
10449
11092
  if (!targetTabs.length) return;
@@ -10453,7 +11096,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
10453
11096
  const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
10454
11097
  try {
10455
11098
  if (closedActiveTab) eventSource?.close();
10456
- const response = await api("/api/tabs/close", { method: "POST", body: { ids: targetIds }, scoped: false });
11099
+ const response = await api("/api/tabs/close", { method: "POST", body: { ids: targetIds, allowEmpty }, scoped: false });
10457
11100
  const closedIds = response.data?.closedIds || targetIds;
10458
11101
  tabs = response.data?.tabs || tabs.filter((item) => !closedIds.includes(item.id));
10459
11102
  syncTabMetadata(tabs);
@@ -10465,11 +11108,14 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
10465
11108
  commandCatalogsByTab.delete(id);
10466
11109
  appRunnerDataByTab.delete(id);
10467
11110
  tabMessagesCache.delete(id);
11111
+ fileViewersByTab.delete(id);
11112
+ fileViewerSelectionsByTab.delete(id);
10468
11113
  btwWidgetDismissedIdsByTab.delete(id);
10469
11114
  removeSubagentTerminalViewsForParent(id);
10470
11115
  }
10471
11116
  syncTerminalCustomGroupsWithTabs(tabs);
10472
11117
  clearOpenTerminalTabGroup(null, { force: true });
11118
+ if (!tabs.length) setWorkspaceDashboardCollapsed(false, { persist: false });
10473
11119
 
10474
11120
  const activeTabNeedsFallback = closedIds.includes(activeTabId) || !tabs.some((item) => item.id === activeTabId);
10475
11121
  if (activeTabNeedsFallback) {
@@ -10506,7 +11152,7 @@ async function closeTerminalTabGroup(group) {
10506
11152
  }
10507
11153
 
10508
11154
  async function closeAllTerminalTabs() {
10509
- await closeTerminalTabs(tabs.map((tab) => tab.id), { label: "all terminal tabs" });
11155
+ await closeTerminalTabs(tabs.map((tab) => tab.id), { label: "all terminal tabs", allowEmpty: true });
10510
11156
  }
10511
11157
 
10512
11158
  async function initializeTabs() {
@@ -10515,7 +11161,12 @@ async function initializeTabs() {
10515
11161
  renderTabs();
10516
11162
  restoreActiveDraft();
10517
11163
  if (!loadedTabs.length) {
10518
- await createFirstTerminalTabFromChosenDirectory();
11164
+ setWorkspaceDashboardCollapsed(false, { persist: false });
11165
+ const saved = await refreshSavedWorkspaces().catch((error) => {
11166
+ addEvent(`Could not list saved workspaces: ${error.message || String(error)}`, "error");
11167
+ return [];
11168
+ });
11169
+ if (!saved.length) await createFirstTerminalTabFromChosenDirectory();
10519
11170
  return;
10520
11171
  }
10521
11172
  focusPromptInput({ defer: true });
@@ -11358,13 +12009,21 @@ function positionFooterTooltip(target) {
11358
12009
  const width = footerTooltipNode.offsetWidth;
11359
12010
  const height = footerTooltipNode.offsetHeight;
11360
12011
  const align = target.getAttribute("data-tooltip-align") || "center";
11361
- let left = rect.left + rect.width / 2 - width / 2;
11362
- if (align === "start") left = rect.left;
11363
- if (align === "end") left = rect.right - width;
12012
+ const placement = target.getAttribute("data-tooltip-placement") || "top";
12013
+ let left;
12014
+ let top;
12015
+ if (placement === "right") {
12016
+ left = rect.right + gap;
12017
+ if (left + width > window.innerWidth - margin) left = rect.left - gap - width;
12018
+ top = rect.top;
12019
+ } else {
12020
+ left = rect.left + rect.width / 2 - width / 2;
12021
+ if (align === "start") left = rect.left;
12022
+ if (align === "end") left = rect.right - width;
12023
+ top = rect.top - gap - height;
12024
+ if (top < margin) top = rect.bottom + gap;
12025
+ }
11364
12026
  left = Math.min(Math.max(margin, left), Math.max(margin, window.innerWidth - margin - width));
11365
-
11366
- let top = rect.top - gap - height;
11367
- if (top < margin) top = rect.bottom + gap;
11368
12027
  top = Math.min(Math.max(margin, top), window.innerHeight - margin - height);
11369
12028
 
11370
12029
  footerTooltipNode.style.left = `${Math.round(left)}px`;
@@ -11448,6 +12107,7 @@ function applyStyledTooltip(node, tooltip, options = {}) {
11448
12107
  node.setAttribute("aria-describedby", describedBy);
11449
12108
  }
11450
12109
  if (options.align) node.setAttribute("data-tooltip-align", options.align);
12110
+ if (options.placement) node.setAttribute("data-tooltip-placement", options.placement);
11451
12111
  if (options.variant) node.setAttribute("data-tooltip-variant", options.variant);
11452
12112
  if (options.floating !== false) bindStyledTooltipEvents(node);
11453
12113
  return node;
@@ -14510,6 +15170,9 @@ function renderWorkspaceDashboard() {
14510
15170
  activeTabId,
14511
15171
  tabs: tabs.slice(0, 8).map((item) => ({ id: item.id, title: item.title, indicator: tabIndicator(item), active: item.id === activeTabId, cwd: item.cwd ? normalizeDisplayPath(item.cwd) : "" })),
14512
15172
  overflow: tabs.length > 8 ? tabs.length - 8 : 0,
15173
+ savedWorkspaces: !tabs.length ? savedWorkspaces.map((workspace) => ({ id: workspace.id, name: workspace.name, savedAt: workspace.savedAt, tabCount: workspace.tabCount, groupCount: workspace.groupCount, cwds: workspace.cwds })) : [],
15174
+ savedWorkspacesLoading,
15175
+ savedWorkspacesError,
14513
15176
  });
14514
15177
  if (signature === workspaceDashboardSignature && root.childElementCount > 0) return;
14515
15178
  workspaceDashboardSignature = signature;
@@ -14548,11 +15211,16 @@ function renderWorkspaceDashboard() {
14548
15211
  actions.append(
14549
15212
  dashboardAction("Command palette", () => openCommandPalette(), "primary"),
14550
15213
  dashboardAction("New tab", () => createTerminalTab()),
14551
- dashboardAction("Branch worktree", () => openBranchWorktreePicker(), "worktree"),
14552
- dashboardAction("Resume", () => runNativeCommandMenu("/resume")),
14553
- dashboardAction("Model", () => runNativeCommandMenu("/model")),
14554
- dashboardAction("Settings", () => runNativeCommandMenu("/settings")),
14555
15214
  );
15215
+ if (tabs.length) {
15216
+ actions.append(
15217
+ dashboardAction("Load workspace", () => openWorkspaceLoadPicker(), "primary"),
15218
+ dashboardAction("Branch worktree", () => openBranchWorktreePicker(), "worktree"),
15219
+ dashboardAction("Resume", () => runNativeCommandMenu("/resume")),
15220
+ dashboardAction("Model", () => runNativeCommandMenu("/model")),
15221
+ dashboardAction("Settings", () => runNativeCommandMenu("/settings")),
15222
+ );
15223
+ }
14556
15224
  header.append(title, actions);
14557
15225
 
14558
15226
  const metrics = make("div", "workspace-dashboard-metrics");
@@ -14599,7 +15267,70 @@ function renderWorkspaceDashboard() {
14599
15267
  if (tabs.length > 8) tabList.append(make("span", "workspace-dashboard-tab-more", `+${tabs.length - 8} more`));
14600
15268
  tabsPanel.append(tabList);
14601
15269
 
15270
+ const savedWorkspacePanel = !tabs.length ? renderSavedWorkspacePicker() : null;
14602
15271
  root.append(header, metrics, tabsPanel);
15272
+ if (savedWorkspacePanel) root.append(savedWorkspacePanel);
15273
+ }
15274
+
15275
+ function renderSavedWorkspacePicker() {
15276
+ if (!savedWorkspacesLoaded && !savedWorkspacesLoading && !savedWorkspacesError) {
15277
+ queueMicrotask(() => refreshSavedWorkspaces().catch((error) => addEvent(`Could not list saved workspaces: ${error.message || String(error)}`, "error")));
15278
+ }
15279
+ const panel = make("section", "workspace-saved-workspaces");
15280
+ panel.setAttribute("aria-label", "Saved workspaces");
15281
+ const heading = make("div", "workspace-saved-workspaces-heading");
15282
+ heading.append(
15283
+ make("span", "workspace-dashboard-kicker", "Saved workspaces"),
15284
+ make("span", "workspace-saved-workspaces-hint", "Load a complete saved tab constellation"),
15285
+ );
15286
+ panel.append(heading);
15287
+ if (savedWorkspacesLoading) {
15288
+ const status = make("p", "workspace-saved-workspaces-empty muted", "Loading saved workspaces…");
15289
+ status.setAttribute("role", "status");
15290
+ panel.append(status);
15291
+ return panel;
15292
+ }
15293
+ if (savedWorkspacesError) {
15294
+ const status = make("p", "workspace-saved-workspaces-empty error", `Could not load saved workspaces: ${savedWorkspacesError}`);
15295
+ status.setAttribute("role", "status");
15296
+ const retry = make("button", "workspace-saved-workspaces-retry", "Retry");
15297
+ retry.type = "button";
15298
+ retry.addEventListener("click", () => refreshSavedWorkspaces({ force: true }).catch((error) => addEvent(`Could not list saved workspaces: ${error.message || String(error)}`, "error")));
15299
+ panel.append(status, retry);
15300
+ return panel;
15301
+ }
15302
+ if (!savedWorkspaces.length) {
15303
+ panel.append(make("p", "workspace-saved-workspaces-empty muted", "No saved workspaces yet. Open tabs, then use Save workspace."));
15304
+ return panel;
15305
+ }
15306
+ const list = make("div", "workspace-saved-workspaces-list");
15307
+ for (const workspace of savedWorkspaces) {
15308
+ const row = make("article", "workspace-saved-workspace");
15309
+ const copy = make("div", "workspace-saved-workspace-copy");
15310
+ const title = make("strong", "workspace-saved-workspace-name", workspace.name);
15311
+ title.title = workspace.name;
15312
+ const detail = [
15313
+ formatDate(workspace.savedAt),
15314
+ `${workspace.tabCount || 0} tab${workspace.tabCount === 1 ? "" : "s"}`,
15315
+ workspace.groupCount ? `${workspace.groupCount} group${workspace.groupCount === 1 ? "" : "s"}` : "",
15316
+ Array.isArray(workspace.cwds) && workspace.cwds.length ? normalizeDisplayPath(workspace.cwds[0]) : "",
15317
+ ].filter(Boolean).join(" · ");
15318
+ copy.append(title, make("span", "workspace-saved-workspace-detail", detail));
15319
+ const actions = make("div", "workspace-saved-workspace-actions");
15320
+ const load = make("button", "workspace-saved-workspace-load primary", "Load");
15321
+ load.type = "button";
15322
+ load.setAttribute("aria-label", `Load workspace ${workspace.name}`);
15323
+ load.addEventListener("click", () => loadWebuiWorkspace(workspace.id, { triggerButton: load }));
15324
+ const remove = make("button", "workspace-saved-workspace-delete", "Delete");
15325
+ remove.type = "button";
15326
+ remove.setAttribute("aria-label", `Delete workspace ${workspace.name}`);
15327
+ remove.addEventListener("click", () => deleteWebuiWorkspace(workspace));
15328
+ actions.append(load, remove);
15329
+ row.append(copy, actions);
15330
+ list.append(row);
15331
+ }
15332
+ panel.append(list);
15333
+ return panel;
14603
15334
  }
14604
15335
 
14605
15336
  function setFooterModelPickerOpen(open) {
@@ -16021,6 +16752,7 @@ async function changeActiveTabCwd() {
16021
16752
  return;
16022
16753
  }
16023
16754
 
16755
+ if (response.data?.changed !== false) closeFileViewer();
16024
16756
  const nextContext = setActiveTabId(response.data?.tab?.id || activeTabId);
16025
16757
  resetActiveTabUi();
16026
16758
  renderTabs();
@@ -16405,7 +17137,7 @@ function subagentTabsWithRunningAgents() {
16405
17137
  const gates = visibleSubagentGates(tab, dismissedSubagentGateKeys, now);
16406
17138
  return { ...tab, gates, gateCount: gates.length };
16407
17139
  })
16408
- .filter((tab) => Number(tab?.agentCount || 0) > 0 || Number(tab?.gateCount || 0) > 0)
17140
+ .filter((tab) => (Array.isArray(tab?.runs) && tab.runs.length > 0) || Number(tab?.gateCount || 0) > 0)
16409
17141
  .sort((a, b) => Number(a.tabIndex || 0) - Number(b.tabIndex || 0) || String(a.tabTitle || "").localeCompare(String(b.tabTitle || "")));
16410
17142
  }
16411
17143
 
@@ -16439,6 +17171,116 @@ function subagentExecutionFacts(agent = {}) {
16439
17171
  return [`model ${model || "unknown"}`, `reasoning ${thinking || "unknown"}`];
16440
17172
  }
16441
17173
 
17174
+ function subagentRunIsRunning(run = {}, agent = null) {
17175
+ if (run?.status && run.status !== "running") return false;
17176
+ const status = String(agent?.status || "").trim();
17177
+ return !status || ["running", "queued", "pending"].includes(status);
17178
+ }
17179
+
17180
+ function subagentRunCanCancel(run = {}, agent = null) {
17181
+ return run?.source !== "workflow" && subagentRunIsRunning(run, agent);
17182
+ }
17183
+
17184
+ function subagentRunStateLabel(run = {}) {
17185
+ if (run?.status === "cancelled") return "cancelled by you";
17186
+ if (run?.status === "failed") return "failed";
17187
+ if (run?.status === "done") return "done";
17188
+ return "running";
17189
+ }
17190
+
17191
+ function setSubagentCancelStatus(message = "", level = "muted") {
17192
+ if (!elements.subagentCancelStatus) return;
17193
+ elements.subagentCancelStatus.textContent = message;
17194
+ elements.subagentCancelStatus.className = `subagent-cancel-status ${message ? level : "muted"}`;
17195
+ elements.subagentCancelStatus.hidden = !message;
17196
+ }
17197
+
17198
+ function setSubagentCancelSubmitting(submitting) {
17199
+ subagentCancelSubmitting = !!submitting;
17200
+ if (elements.subagentCancelSubmitButton) {
17201
+ elements.subagentCancelSubmitButton.disabled = subagentCancelSubmitting;
17202
+ elements.subagentCancelSubmitButton.textContent = subagentCancelSubmitting ? "Cancelling…" : "Cancel subagent";
17203
+ }
17204
+ if (elements.subagentCancelKeepRunningButton) elements.subagentCancelKeepRunningButton.disabled = subagentCancelSubmitting;
17205
+ }
17206
+
17207
+ function subagentCancelTargetLabel(selection = subagentCancelSelection) {
17208
+ if (!selection) return "subagent run";
17209
+ return `run ${selection.runId}`;
17210
+ }
17211
+
17212
+ function openSubagentCancelDialog(tab, run, agent = null) {
17213
+ if (!tab?.tabId || !run?.id || !subagentRunCanCancel(run, agent) || !elements.subagentCancelDialog) return;
17214
+ const agentCount = Array.isArray(run.agents) ? run.agents.length : 0;
17215
+ subagentCancelSelection = {
17216
+ tabId: tab.tabId,
17217
+ runId: run.id,
17218
+ agentCount,
17219
+ };
17220
+ if (elements.subagentCancelDialogSubtitle) {
17221
+ const scope = agentCount > 1 ? ` and all ${agentCount} agents in it` : "";
17222
+ elements.subagentCancelDialogSubtitle.textContent = `Cancel ${subagentCancelTargetLabel()}${scope}? The entire run will be stopped and the parent agent will be notified.`;
17223
+ }
17224
+ if (elements.subagentCancelReason) elements.subagentCancelReason.value = "";
17225
+ if (elements.subagentCancelNote) elements.subagentCancelNote.value = "";
17226
+ setSubagentCancelStatus();
17227
+ setSubagentCancelSubmitting(false);
17228
+ if (!elements.subagentCancelDialog.open) elements.subagentCancelDialog.showModal();
17229
+ queueMicrotask(() => elements.subagentCancelReason?.focus());
17230
+ }
17231
+
17232
+ function closeSubagentCancelDialog() {
17233
+ if (subagentCancelSubmitting) return;
17234
+ if (elements.subagentCancelDialog?.open) elements.subagentCancelDialog.close();
17235
+ }
17236
+
17237
+ async function submitSubagentCancel() {
17238
+ const selection = subagentCancelSelection;
17239
+ if (!selection || subagentCancelSubmitting) return;
17240
+ const reason = String(elements.subagentCancelReason?.value || "").trim();
17241
+ const note = String(elements.subagentCancelNote?.value || "").trim();
17242
+ setSubagentCancelSubmitting(true);
17243
+ setSubagentCancelStatus("Cancelling subagent…");
17244
+ try {
17245
+ await api("/api/subagents/cancel", {
17246
+ method: "POST",
17247
+ scoped: false,
17248
+ body: {
17249
+ tab: selection.tabId,
17250
+ runId: selection.runId,
17251
+ ...(reason ? { reason } : {}),
17252
+ ...(note ? { note } : {}),
17253
+ },
17254
+ });
17255
+ if (elements.subagentCancelDialog?.open) elements.subagentCancelDialog.close();
17256
+ addEvent(`cancelled ${subagentCancelTargetLabel(selection)}; the parent agent was notified`, "info");
17257
+ await refreshSubagents();
17258
+ scheduleRefreshSubagents();
17259
+ } catch (error) {
17260
+ const message = `subagent cancel failed: ${error.message || String(error)}`;
17261
+ setSubagentCancelStatus(message, "error");
17262
+ addEvent(message, "error");
17263
+ } finally {
17264
+ setSubagentCancelSubmitting(false);
17265
+ }
17266
+ }
17267
+
17268
+ async function dismissSubagentRun(tab, run) {
17269
+ if (!tab?.tabId || !run?.id || subagentRunIsRunning(run)) return;
17270
+ try {
17271
+ await api("/api/subagents/dismiss", {
17272
+ method: "POST",
17273
+ scoped: false,
17274
+ body: { tab: tab.tabId, runId: run.id },
17275
+ });
17276
+ addEvent(`dismissed finished subagent run ${run.id}`, "info");
17277
+ await refreshSubagents();
17278
+ scheduleRefreshSubagents();
17279
+ } catch (error) {
17280
+ addEvent(`subagent dismiss failed: ${error.message || String(error)}`, "error");
17281
+ }
17282
+ }
17283
+
16442
17284
  function subagentOverlayTranscriptMessages(data = subagentOverlayData) {
16443
17285
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
16444
17286
  return (Array.isArray(agent.transcript) ? agent.transcript : [])
@@ -16567,10 +17409,11 @@ function appendSubagentOverlayTranscript(parent, messages) {
16567
17409
 
16568
17410
  function subagentOverlayStateFacts(data = subagentOverlayData) {
16569
17411
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
17412
+ const run = subagentOverlaySelection?.run || {};
16570
17413
  return [
16571
- agent.status || "running",
16572
- data?.mode || subagentOverlaySelection?.run?.mode,
16573
- subagentSourceLabel(data?.source || subagentOverlaySelection?.run?.source),
17414
+ subagentRunIsRunning(run, agent) ? agent.status || "running" : subagentRunStateLabel(run),
17415
+ data?.mode || run.mode,
17416
+ subagentSourceLabel(data?.source || run.source),
16574
17417
  agent.nested ? "nested" : "",
16575
17418
  ...subagentExecutionFacts(agent),
16576
17419
  agent.currentTool ? `tool ${agent.currentTool}` : "",
@@ -16626,7 +17469,7 @@ function renderSubagentOverlayWidget() {
16626
17469
  const data = subagentOverlayData;
16627
17470
  const agent = data?.agent || selection.agent || {};
16628
17471
  const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
16629
- const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
17472
+ const running = !selection.finished && subagentRunIsRunning(selection.run, agent);
16630
17473
  const transcriptMessages = subagentOverlayTranscriptMessages(data);
16631
17474
  const hasStructuredTranscript = transcriptMessages.length > 0;
16632
17475
  const outputText = subagentOverlayOutputText(data);
@@ -16671,6 +17514,9 @@ function renderSubagentOverlayWidget() {
16671
17514
  refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
16672
17515
  }, "subagent-overlay-refresh-action");
16673
17516
  refreshButton.disabled = subagentOverlayLoading || selection.finished;
17517
+ if (subagentRunCanCancel(selection.run, agent)) {
17518
+ actions.append(appRunnerActionButton("Cancel…", () => openSubagentCancelDialog(tab, selection.run, agent), "subagent-overlay-cancel-action danger"));
17519
+ }
16674
17520
  actions.append(copyButton, refreshButton, appRunnerActionButton("Close", closeSubagentOverlay, "subagent-overlay-close-action"));
16675
17521
  const details = [
16676
17522
  `${tab?.title || `Terminal ${selection.tabIndex || "?"}`} · run ${selection.runId}`,
@@ -16688,7 +17534,8 @@ function renderSubagentOverlayWidget() {
16688
17534
 
16689
17535
  function scheduleSubagentOverlayRefresh(delay = SUBAGENT_OVERLAY_REFRESH_MS) {
16690
17536
  clearTimeout(subagentOverlayRefreshTimer);
16691
- if (!subagentOverlaySelection || subagentOverlaySelection.finished) return;
17537
+ const agent = subagentOverlayData?.agent || subagentOverlaySelection?.agent || null;
17538
+ if (!subagentOverlaySelection || subagentOverlaySelection.finished || !subagentRunIsRunning(subagentOverlaySelection.run, agent)) return;
16692
17539
  subagentOverlayRefreshTimer = setTimeout(() => {
16693
17540
  refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
16694
17541
  }, delay);
@@ -16784,8 +17631,8 @@ function subagentTerminalViewTitle(view) {
16784
17631
  }
16785
17632
 
16786
17633
  function subagentTerminalViewIsRunning(view) {
16787
- const status = view?.data?.agent?.status || view?.agent?.status || "running";
16788
- return view?.finished !== true && ["running", "queued", "pending"].includes(status);
17634
+ const agent = view?.data?.agent || view?.agent || null;
17635
+ return view?.finished !== true && subagentRunIsRunning(view?.run, agent);
16789
17636
  }
16790
17637
 
16791
17638
  function subagentTerminalViewMeaningfulSignature(view) {
@@ -16796,7 +17643,7 @@ function subagentTerminalViewMeaningfulSignature(view) {
16796
17643
  function updateSubagentTerminalRefreshState(view, { running = subagentTerminalViewIsRunning(view) } = {}) {
16797
17644
  if (!view || view.id !== activeSubagentTerminalId) return;
16798
17645
  const status = [
16799
- view.loading ? "Refreshing…" : running ? "Live view · refreshes automatically" : "View retained after the child stopped being tracked",
17646
+ view.loading ? "Refreshing…" : running ? "Live view · refreshes automatically" : view.finished ? "View retained after the child stopped being tracked" : "View retained after the run finished",
16800
17647
  view.error,
16801
17648
  ].filter(Boolean).join(" · ");
16802
17649
  elements.subagentTerminalStatus.setAttribute("aria-live", view.error ? "polite" : "off");
@@ -16822,7 +17669,7 @@ function renderSubagentTerminalView() {
16822
17669
  const fallbackText = outputText || (running && agent.currentTool ? "" : running ? "Waiting for the first agent activity…" : "No recent output was captured.");
16823
17670
  const parent = tabs.find((tab) => tab.id === view.parentTabId);
16824
17671
  const facts = [
16825
- view.finished ? "finished" : running ? "running" : agent.status || "finished",
17672
+ view.finished ? "finished" : running ? "running" : subagentRunStateLabel(view.run),
16826
17673
  view.run?.mode,
16827
17674
  subagentSourceLabel(view.data?.source || view.run?.source),
16828
17675
  agent.nested ? "nested" : "",
@@ -16852,13 +17699,18 @@ function renderSubagentTerminalView() {
16852
17699
 
16853
17700
  updateSubagentTerminalRefreshState(view, { running });
16854
17701
  elements.subagentTerminalCopyButton.disabled = !outputText;
17702
+ if (elements.subagentTerminalCancelButton) {
17703
+ const cancellable = subagentRunCanCancel(view.run, agent);
17704
+ elements.subagentTerminalCancelButton.hidden = !cancellable;
17705
+ elements.subagentTerminalCancelButton.disabled = !cancellable;
17706
+ }
16855
17707
  if (shouldFollowOutput) requestAnimationFrame(() => { elements.subagentTerminalTranscript.scrollTop = elements.subagentTerminalTranscript.scrollHeight; });
16856
17708
  }
16857
17709
 
16858
17710
  function scheduleSubagentTerminalRefresh(delay = SUBAGENT_OVERLAY_REFRESH_MS) {
16859
17711
  clearTimeout(subagentTerminalRefreshTimer);
16860
17712
  const view = activeSubagentTerminalView();
16861
- if (!view || view.finished) return;
17713
+ if (!view || view.finished || !subagentTerminalViewIsRunning(view)) return;
16862
17714
  subagentTerminalRefreshTimer = setTimeout(() => {
16863
17715
  refreshSubagentTerminalView(view.id).finally(() => scheduleSubagentTerminalRefresh());
16864
17716
  }, delay);
@@ -16925,8 +17777,8 @@ async function activateSubagentTerminalView(viewId) {
16925
17777
  scheduleSubagentTerminalRefresh();
16926
17778
  }
16927
17779
 
16928
- async function openSubagentTerminal(tab, run, agent) {
16929
- if (!tab?.tabId || !run?.id || !agent?.id) return;
17780
+ function ensureSubagentTerminalView(tab, run, agent) {
17781
+ if (!tab?.tabId || !run?.id || !agent?.id) return null;
16930
17782
  const id = subagentTerminalViewId(tab, run, agent);
16931
17783
  const existing = subagentTerminalViews.get(id);
16932
17784
  if (existing) {
@@ -16934,27 +17786,34 @@ async function openSubagentTerminal(tab, run, agent) {
16934
17786
  existing.run = run;
16935
17787
  existing.agent = agent;
16936
17788
  existing.parentTitle = tab.tabTitle;
16937
- } else {
16938
- subagentTerminalViews.set(id, {
16939
- id,
16940
- parentTabId: tab.tabId,
16941
- parentTitle: tab.tabTitle,
16942
- tabIndex: tab.tabIndex,
16943
- tab,
16944
- run,
16945
- agent,
16946
- runId: run.id,
16947
- agentId: agent.id,
16948
- data: null,
16949
- error: "",
16950
- loading: false,
16951
- finished: false,
16952
- requestSerial: 0,
16953
- openedAt: Date.now(),
16954
- });
17789
+ return existing;
16955
17790
  }
17791
+ const view = {
17792
+ id,
17793
+ parentTabId: tab.tabId,
17794
+ parentTitle: tab.tabTitle,
17795
+ tabIndex: tab.tabIndex,
17796
+ tab,
17797
+ run,
17798
+ agent,
17799
+ runId: run.id,
17800
+ agentId: agent.id,
17801
+ data: null,
17802
+ error: "",
17803
+ loading: false,
17804
+ finished: false,
17805
+ requestSerial: 0,
17806
+ openedAt: Date.now(),
17807
+ };
17808
+ subagentTerminalViews.set(id, view);
17809
+ return view;
17810
+ }
17811
+
17812
+ async function openSubagentTerminal(tab, run, agent) {
17813
+ const view = ensureSubagentTerminalView(tab, run, agent);
17814
+ if (!view) return;
16956
17815
  try {
16957
- await activateSubagentTerminalView(id);
17816
+ await activateSubagentTerminalView(view.id);
16958
17817
  } catch (error) {
16959
17818
  addEvent(`could not open subagent terminal: ${error.message || String(error)}`, "error");
16960
17819
  }
@@ -16986,6 +17845,9 @@ async function copySubagentTerminalOutput() {
16986
17845
  }
16987
17846
 
16988
17847
  function removeSubagentTerminalViewsForParent(parentTabId) {
17848
+ for (const key of subagentTerminalRestoredParentTabs) {
17849
+ if (key.startsWith(`${parentTabId}\u0000`)) subagentTerminalRestoredParentTabs.delete(key);
17850
+ }
16989
17851
  for (const [viewId, view] of subagentTerminalViews) {
16990
17852
  if (view.parentTabId !== parentTabId) continue;
16991
17853
  view.requestSerial += 1;
@@ -16995,17 +17857,64 @@ function removeSubagentTerminalViewsForParent(parentTabId) {
16995
17857
  }
16996
17858
 
16997
17859
  function syncSubagentTerminalViewsFromOverview() {
17860
+ let changed = false;
17861
+ const overviewTabs = Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : [];
16998
17862
  for (const view of subagentTerminalViews.values()) {
16999
- const tab = (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : []).find((candidate) => candidate.tabId === view.parentTabId);
17863
+ const tab = overviewTabs.find((candidate) => candidate.tabId === view.parentTabId);
17000
17864
  const run = (Array.isArray(tab?.runs) ? tab.runs : []).find((candidate) => candidate.id === view.runId);
17001
17865
  const agent = (Array.isArray(run?.agents) ? run.agents : []).find((candidate) => candidate.id === view.agentId);
17002
17866
  if (tab) {
17003
17867
  view.tab = tab;
17004
17868
  view.parentTitle = tab.tabTitle;
17869
+ changed = true;
17870
+ }
17871
+ if (run) {
17872
+ view.run = run;
17873
+ changed = true;
17874
+ }
17875
+ if (agent) {
17876
+ view.agent = agent;
17877
+ if (view.data?.agent) view.data = { ...view.data, agent: { ...view.data.agent, ...agent } };
17878
+ changed = true;
17879
+ }
17880
+ }
17881
+ const selection = subagentOverlaySelection;
17882
+ if (selection) {
17883
+ const tab = overviewTabs.find((candidate) => candidate.tabId === selection.tabId);
17884
+ const run = (Array.isArray(tab?.runs) ? tab.runs : []).find((candidate) => candidate.id === selection.runId);
17885
+ const agent = (Array.isArray(run?.agents) ? run.agents : []).find((candidate) => candidate.id === selection.agentId);
17886
+ if (tab) selection.tab = tab;
17887
+ if (run) {
17888
+ selection.run = run;
17889
+ changed = true;
17890
+ }
17891
+ if (agent) {
17892
+ selection.agent = agent;
17893
+ if (subagentOverlayData?.agent) subagentOverlayData = { ...subagentOverlayData, agent: { ...subagentOverlayData.agent, ...agent } };
17894
+ changed = true;
17895
+ }
17896
+ }
17897
+ return changed;
17898
+ }
17899
+
17900
+ function materializeRetainedSubagentTerminalViews() {
17901
+ if (subagentOpenMode !== "tab") return false;
17902
+ let materialized = false;
17903
+ for (const tab of Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : []) {
17904
+ if (tab?.available !== true || !tab?.tabId) continue;
17905
+ const restoreKey = `${tab.tabId}\u0000${tab.sessionFile || ""}`;
17906
+ if (subagentTerminalRestoredParentTabs.has(restoreKey)) continue;
17907
+ subagentTerminalRestoredParentTabs.add(restoreKey);
17908
+ for (const run of Array.isArray(tab.runs) ? tab.runs : []) {
17909
+ if (run?.status === "running" || run?.source === "workflow") continue;
17910
+ for (const agent of Array.isArray(run.agents) ? run.agents : []) {
17911
+ const id = subagentTerminalViewId(tab, run, agent);
17912
+ if (subagentTerminalViews.has(id)) continue;
17913
+ if (ensureSubagentTerminalView(tab, run, agent)) materialized = true;
17914
+ }
17005
17915
  }
17006
- if (run) view.run = run;
17007
- if (agent) view.agent = agent;
17008
17916
  }
17917
+ return materialized;
17009
17918
  }
17010
17919
 
17011
17920
  function renderSubagentTerminalTab(view) {
@@ -17042,9 +17951,10 @@ function openSubagentOutput(tab, run, agent) {
17042
17951
  }
17043
17952
 
17044
17953
  function renderSubagentAgent(tab, run, agent) {
17045
- const row = make("button", `subagent-agent-row${agent?.nested ? " nested" : ""}`);
17954
+ const running = subagentRunIsRunning(run, agent);
17955
+ const row = make("button", `subagent-agent-row${agent?.nested ? " nested" : ""}${running ? " running" : " finished"}`);
17046
17956
  row.type = "button";
17047
- const dot = make("span", "subagent-running-dot");
17957
+ const dot = make("span", running ? "subagent-running-dot" : `subagent-state-dot ${agent?.status || "done"}`);
17048
17958
  dot.setAttribute("aria-hidden", "true");
17049
17959
  const content = make("div", "subagent-agent-content");
17050
17960
  content.append(make("strong", "subagent-agent-name", agent?.name || "subagent"));
@@ -17055,17 +17965,55 @@ function renderSubagentAgent(tab, run, agent) {
17055
17965
  subagentSourceLabel(run?.source),
17056
17966
  ...subagentExecutionFacts(agent),
17057
17967
  agent?.currentTool ? `tool: ${agent.currentTool}` : "",
17058
- elapsed ? `running ${elapsed}` : "",
17968
+ running && elapsed ? `running ${elapsed}` : agent?.status || subagentRunStateLabel(run),
17059
17969
  ].filter(Boolean);
17060
17970
  content.append(make("span", "subagent-agent-meta", facts.join(" · ")));
17061
17971
  row.append(dot, content);
17062
- const destination = subagentOpenMode === "tab" ? "subagent tab" : "live output overlay";
17972
+ const destination = subagentOpenMode === "tab" ? "subagent tab" : "output overlay";
17063
17973
  row.title = `${agent?.name || "subagent"} · ${facts.join(" · ")} · run ${run?.id || "unknown"} · open ${destination}`;
17064
17974
  row.setAttribute("aria-label", `Open ${destination} for ${agent?.name || "subagent"} in ${tab?.tabTitle || `Terminal ${tab?.tabIndex || "?"}`}`);
17065
17975
  row.addEventListener("click", () => openSubagentOutput(tab, run, agent));
17066
17976
  return row;
17067
17977
  }
17068
17978
 
17979
+ function renderSubagentRun(tab, run) {
17980
+ const running = subagentRunIsRunning(run);
17981
+ const card = make("section", `subagent-run ${running ? "running" : run?.status || "done"}`);
17982
+ const header = make("div", "subagent-run-header");
17983
+ const title = make("div", "subagent-run-title");
17984
+ const elapsed = subagentRunElapsed(run);
17985
+ title.append(
17986
+ make("strong", undefined, `Run ${run?.id || "unknown"}`),
17987
+ make("span", "subagent-run-meta", [subagentSourceLabel(run?.source), run?.mode, running && elapsed ? `running ${elapsed}` : ""].filter(Boolean).join(" · ")),
17988
+ );
17989
+ const actions = make("div", "subagent-run-actions");
17990
+ if (subagentRunCanCancel(run)) {
17991
+ const cancel = make("button", "subagent-run-cancel", "Cancel…");
17992
+ cancel.type = "button";
17993
+ cancel.addEventListener("click", () => openSubagentCancelDialog(tab, run));
17994
+ actions.append(cancel);
17995
+ } else if (!running) {
17996
+ actions.append(make("span", `subagent-run-state ${run?.status || "done"}`, subagentRunStateLabel(run)));
17997
+ if (run?.source !== "workflow") {
17998
+ const dismiss = make("button", "subagent-run-dismiss", "×");
17999
+ dismiss.type = "button";
18000
+ applyStyledTooltip(dismiss, "Dismiss finished run", { ariaLabel: "Dismiss finished run" });
18001
+ dismiss.addEventListener("click", () => dismissSubagentRun(tab, run));
18002
+ actions.append(dismiss);
18003
+ }
18004
+ }
18005
+ header.append(title, actions);
18006
+ card.append(header);
18007
+ const agents = (Array.isArray(run?.agents) ? run.agents : [])
18008
+ .slice()
18009
+ .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
18010
+ const list = make("div", "subagent-run-agents");
18011
+ for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
18012
+ if (!list.childElementCount) list.append(make("div", "subagents-empty", "No agent details were captured for this run."));
18013
+ card.append(list);
18014
+ return card;
18015
+ }
18016
+
17069
18017
  function subagentGateStatusLabel(status) {
17070
18018
  return status === "satisfied" ? "satisfied" : status === "running" ? "running" : status === "cancelled" ? "cancelled" : "failed";
17071
18019
  }
@@ -17137,21 +18085,22 @@ function renderSubagentTabGroup(tab) {
17137
18085
  make("strong", undefined, tab.tabTitle || `Terminal ${tab.tabIndex || "?"}`),
17138
18086
  make("span", "subagent-tab-session", `Terminal ${tab.tabIndex || "?"} · ${subagentTabMeta(tab)}`),
17139
18087
  );
17140
- const countLabel = Number(tab.gateCount || 0) > 0 ? `${tab.agentCount || 0} agents · ${tab.gateCount} gates` : String(tab.agentCount || 0);
18088
+ const runs = (Array.isArray(tab.runs) ? tab.runs : [])
18089
+ .slice()
18090
+ .sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0) || String(a.id || "").localeCompare(String(b.id || "")));
18091
+ const runningAgents = Number(tab.runningAgents || 0);
18092
+ const retainedRuns = runs.filter((run) => run?.status !== "running").length;
18093
+ const countLabel = [
18094
+ `${runningAgents} running`,
18095
+ retainedRuns ? `${retainedRuns} retained` : "",
18096
+ Number(tab.gateCount || 0) ? `${tab.gateCount} gates` : "",
18097
+ ].filter(Boolean).join(" · ");
17141
18098
  header.append(title, make("span", "subagent-tab-count", countLabel));
17142
18099
  header.addEventListener("click", () => switchTab(tab.tabId));
17143
18100
  group.append(header);
17144
18101
 
17145
18102
  const list = make("div", "subagent-agent-list");
17146
- const runs = (Array.isArray(tab.runs) ? tab.runs : [])
17147
- .slice()
17148
- .sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0) || String(a.id || "").localeCompare(String(b.id || "")));
17149
- for (const run of runs) {
17150
- const agents = (Array.isArray(run.agents) ? run.agents : [])
17151
- .filter((agent) => agent?.status === "running")
17152
- .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
17153
- for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
17154
- }
18103
+ for (const run of runs) list.append(renderSubagentRun(tab, run));
17155
18104
  for (const gate of (Array.isArray(tab.gates) ? tab.gates : []).slice().sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0))) {
17156
18105
  list.append(renderSubagentGate(tab, gate));
17157
18106
  }
@@ -17163,26 +18112,29 @@ function renderSubagents() {
17163
18112
  const box = elements.subagentsBox;
17164
18113
  if (!box) return;
17165
18114
  const activeTabs = subagentTabsWithRunningAgents();
17166
- const totalAgents = activeTabs.reduce((count, tab) => count + Number(tab.agentCount || 0), 0);
18115
+ const totalAgents = Number(latestSubagents?.runningAgents ?? activeTabs.reduce((count, tab) => count + Number(tab.runningAgents || 0), 0));
18116
+ const totalRuns = Number(latestSubagents?.totalRuns || 0);
18117
+ const runningRuns = Number(latestSubagents?.runningRuns || 0);
18118
+ const retainedRuns = Math.max(0, totalRuns - runningRuns);
17167
18119
  const totalGates = activeTabs.reduce((count, tab) => count + Number(tab.gateCount || 0), 0);
17168
- const totalItems = totalAgents + totalGates;
18120
+ const hasItems = activeTabs.length > 0;
17169
18121
  if (elements.subagentCountBadge) {
17170
- elements.subagentCountBadge.textContent = String(totalItems);
17171
- elements.subagentCountBadge.hidden = totalItems === 0;
18122
+ elements.subagentCountBadge.textContent = String(totalAgents);
18123
+ elements.subagentCountBadge.hidden = totalAgents === 0;
17172
18124
  }
17173
18125
  if (elements.subagentsStatus) {
17174
- elements.subagentsStatus.textContent = totalItems > 0
17175
- ? [`${totalAgents} running`, totalGates ? `${totalGates} retry ${totalGates === 1 ? "gate" : "gates"}` : "", `across ${activeTabs.length} ${activeTabs.length === 1 ? "terminal" : "terminals"}`].filter(Boolean).join(" · ")
18126
+ elements.subagentsStatus.textContent = hasItems
18127
+ ? [`${totalAgents} running`, retainedRuns ? `${retainedRuns} retained ${retainedRuns === 1 ? "run" : "runs"}` : "", totalGates ? `${totalGates} retry ${totalGates === 1 ? "gate" : "gates"}` : "", `across ${activeTabs.length} ${activeTabs.length === 1 ? "terminal" : "terminals"}`].filter(Boolean).join(" · ")
17176
18128
  : subagentsLoading && !latestSubagents
17177
18129
  ? "Checking subagents and retry gates…"
17178
- : "No running subagents or retained retry gates.";
18130
+ : "No running subagents, retained runs, or retry gates.";
17179
18131
  }
17180
18132
 
17181
18133
  box.replaceChildren();
17182
- box.classList.toggle("muted", totalItems === 0);
17183
- box.classList.toggle("has-items", totalItems > 0);
17184
- if (totalItems === 0) {
17185
- box.append(make("div", "subagents-empty", subagentsError ? `Subagent status unavailable: ${subagentsError.message || subagentsError}` : "Running subagents and retry-gate attempts will appear here, grouped by terminal and session."));
18134
+ box.classList.toggle("muted", !hasItems);
18135
+ box.classList.toggle("has-items", hasItems);
18136
+ if (!hasItems) {
18137
+ box.append(make("div", "subagents-empty", subagentsError ? `Subagent status unavailable: ${subagentsError.message || subagentsError}` : "Running and retained subagents will appear here, grouped by terminal and session."));
17186
18138
  return;
17187
18139
  }
17188
18140
  for (const tab of activeTabs) box.append(renderSubagentTabGroup(tab));
@@ -17191,25 +18143,34 @@ function renderSubagents() {
17191
18143
 
17192
18144
  async function refreshSubagents() {
17193
18145
  if (subagentsLoading) return;
18146
+ let subagentViewsChanged = false;
18147
+ let materializedTerminalViews = false;
17194
18148
  subagentsLoading = true;
17195
18149
  renderSubagents();
17196
18150
  try {
17197
18151
  const response = await api("/api/subagents", { scoped: false });
17198
18152
  latestSubagents = response.data || null;
17199
18153
  pruneDismissedSubagentGateKeys(latestSubagents?.tabs, dismissedSubagentGateKeys);
17200
- syncSubagentTerminalViewsFromOverview();
18154
+ subagentViewsChanged = syncSubagentTerminalViewsFromOverview();
18155
+ materializedTerminalViews = materializeRetainedSubagentTerminalViews();
17201
18156
  subagentsError = null;
17202
18157
  } catch (error) {
17203
18158
  subagentsError = error;
17204
18159
  } finally {
17205
18160
  subagentsLoading = false;
17206
18161
  renderSubagents();
18162
+ if (subagentOverlaySelection?.tabId === activeTabId) renderWidgets();
18163
+ if (activeSubagentTerminalId) {
18164
+ renderSubagentTerminalView();
18165
+ scheduleSubagentTerminalRefresh();
18166
+ }
18167
+ if (subagentViewsChanged || materializedTerminalViews) renderTabs();
17207
18168
  }
17208
18169
  }
17209
18170
 
17210
18171
  function scheduleRefreshSubagents(delay) {
17211
18172
  clearTimeout(refreshSubagentsTimer);
17212
- const totalAgents = Number(latestSubagents?.totalAgents || 0);
18173
+ const totalAgents = Number(latestSubagents?.runningAgents || 0);
17213
18174
  const hasRunningGate = (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : []).some((tab) => (Array.isArray(tab?.gates) ? tab.gates : []).some((gate) => gate?.status === "running"));
17214
18175
  const nextDelay = delay ?? (document.visibilityState === "hidden" ? SUBAGENTS_HIDDEN_REFRESH_MS : totalAgents > 0 || hasRunningGate ? SUBAGENTS_ACTIVE_REFRESH_MS : SUBAGENTS_IDLE_REFRESH_MS);
17215
18176
  refreshSubagentsTimer = setTimeout(() => {
@@ -23050,12 +24011,20 @@ function resumeGitWorkflowForActiveTab(tabContext = activeTabContext()) {
23050
24011
 
23051
24012
  function normalizeQueuedMessages(event) {
23052
24013
  const normalize = (items) => (Array.isArray(items) ? items.map((item) => String(item || "")).filter((item) => item.trim()) : []);
24014
+ const source = event?.source === "webui-compaction" ? "webui-compaction" : "pi-runtime";
23053
24015
  return {
24016
+ source,
24017
+ revision: source === "webui-compaction" && Number.isSafeInteger(event?.revision) && event.revision >= 0 ? event.revision : undefined,
24018
+ draining: source === "webui-compaction" && event?.draining === true,
23054
24019
  steering: normalize(event?.steering),
23055
24020
  followUp: normalize(event?.followUp),
23056
24021
  };
23057
24022
  }
23058
24023
 
24024
+ function queuedSnapshotForTab(tabId = activeTabId) {
24025
+ return tabId ? latestQueuedMessagesByTab.get(tabId) || normalizeQueuedMessages({}) : normalizeQueuedMessages({});
24026
+ }
24027
+
23059
24028
  function queueMessageCount(snapshot) {
23060
24029
  return (snapshot?.steering?.length || 0) + (snapshot?.followUp?.length || 0);
23061
24030
  }
@@ -23073,13 +24042,331 @@ function queueSummaryPill(label, count, tone) {
23073
24042
  return pill;
23074
24043
  }
23075
24044
 
24045
+ function followUpQueueMutationInFlight(tabId = activeTabId) {
24046
+ return !!tabId && followUpQueueMutationsInFlightByTab.has(tabId);
24047
+ }
24048
+
24049
+ function setFollowUpQueueStatus(text = "", level = "") {
24050
+ followUpQueueStatus = { text, level };
24051
+ if (!elements.followUpQueueStatus) return;
24052
+ elements.followUpQueueStatus.textContent = text;
24053
+ elements.followUpQueueStatus.className = `follow-up-queue-status${level ? ` ${level}` : ""}`;
24054
+ }
24055
+
24056
+ function syncFollowUpQueueMutationControls() {
24057
+ const tabId = activeTabId;
24058
+ const locked = followUpQueueMutationInFlight(tabId);
24059
+ const draining = queuedSnapshotForTab(tabId).draining;
24060
+ elements.followUpQueueOverlay?.classList.toggle("is-busy", locked);
24061
+ elements.followUpQueueOverlay?.classList.toggle("is-draining", draining);
24062
+ for (const textarea of elements.followUpQueueRows?.querySelectorAll("textarea") || []) textarea.disabled = locked || draining;
24063
+ for (const control of elements.followUpQueueRows?.querySelectorAll("[data-follow-up-queue-mutation-control]") || []) control.disabled = locked || draining || control.dataset.queueBoundary === "true";
24064
+ for (const row of elements.followUpQueueRows?.querySelectorAll(".follow-up-queue-row") || []) row.draggable = false;
24065
+ for (const handle of elements.followUpQueueRows?.querySelectorAll(".follow-up-queue-drag-handle") || []) handle.draggable = !locked && !draining;
24066
+ }
24067
+
24068
+ function setFollowUpQueueMutationInFlight(tabId, inFlight) {
24069
+ if (!tabId) return;
24070
+ if (inFlight) followUpQueueMutationsInFlightByTab.add(tabId);
24071
+ else followUpQueueMutationsInFlightByTab.delete(tabId);
24072
+ if (tabId === activeTabId) syncFollowUpQueueMutationControls();
24073
+ }
24074
+
24075
+ function preservedFocusedFollowUpQueueDraft(draft, followUps) {
24076
+ if (!draft || !Array.isArray(followUps) || !Number.isSafeInteger(draft.index) || draft.index < 0) return null;
24077
+ const authoritativeText = String(draft.authoritativeText ?? "");
24078
+ const value = String(draft.value ?? "");
24079
+ if (value === authoritativeText || followUps[draft.index] !== authoritativeText) return null;
24080
+ const selectionStart = Math.max(0, Math.min(value.length, Number.isSafeInteger(draft.selectionStart) ? draft.selectionStart : value.length));
24081
+ const selectionEnd = Math.max(selectionStart, Math.min(value.length, Number.isSafeInteger(draft.selectionEnd) ? draft.selectionEnd : selectionStart));
24082
+ return { index: draft.index, value, selectionStart, selectionEnd };
24083
+ }
24084
+
24085
+ function focusedFollowUpQueueDraft() {
24086
+ const textarea = document.activeElement;
24087
+ if (!textarea?.matches?.("textarea.follow-up-queue-textarea") || !elements.followUpQueueRows?.contains(textarea)) return null;
24088
+ const index = Number(textarea.closest(".follow-up-queue-row")?.dataset.followUpIndex);
24089
+ if (!Number.isSafeInteger(index) || index < 0) return null;
24090
+ const authoritativeText = String(textarea.dataset.followUpQueueAuthoritativeText ?? "");
24091
+ if (textarea.value === authoritativeText) return null;
24092
+ return {
24093
+ textarea,
24094
+ index,
24095
+ authoritativeText,
24096
+ value: textarea.value,
24097
+ selectionStart: textarea.selectionStart,
24098
+ selectionEnd: textarea.selectionEnd,
24099
+ };
24100
+ }
24101
+
24102
+ function queueTabContext(tabId = activeTabId) {
24103
+ const tab = tabs.find((item) => item.id === tabId);
24104
+ return {
24105
+ ...activeTabContext(tabId),
24106
+ sessionFile: typeof tab?.sessionFile === "string" && tab.sessionFile ? tab.sessionFile : null,
24107
+ startedAt: typeof tab?.startedAt === "string" && tab.startedAt ? tab.startedAt : null,
24108
+ };
24109
+ }
24110
+
24111
+ function queuedSnapshotTargetsCurrentTab(tabContext, currentTabId = activeTabId, currentTabs = tabs) {
24112
+ if (!tabContext?.tabId || tabContext.tabId !== currentTabId || !Array.isArray(currentTabs)) return false;
24113
+ const currentTab = currentTabs.find((tab) => tab?.id === tabContext.tabId);
24114
+ if (!currentTab) return false;
24115
+ const sessionFile = typeof tabContext.sessionFile === "string" && tabContext.sessionFile ? tabContext.sessionFile : null;
24116
+ const currentSessionFile = typeof currentTab.sessionFile === "string" && currentTab.sessionFile ? currentTab.sessionFile : null;
24117
+ if (sessionFile && currentSessionFile && sessionFile !== currentSessionFile) return false;
24118
+ const startedAt = typeof tabContext.startedAt === "string" && tabContext.startedAt ? tabContext.startedAt : null;
24119
+ const currentStartedAt = typeof currentTab.startedAt === "string" && currentTab.startedAt ? currentTab.startedAt : null;
24120
+ return !(startedAt && currentStartedAt && startedAt !== currentStartedAt);
24121
+ }
24122
+
24123
+ function setFollowUpQueueOpen(open, { restoreFocus = false } = {}) {
24124
+ const snapshot = queuedSnapshotForTab();
24125
+ const shouldOpen = !!open && snapshot.followUp.length > 0;
24126
+ if (shouldOpen && !followUpQueueOpen) {
24127
+ followUpQueueRestoreFocus = document.activeElement instanceof HTMLElement ? document.activeElement : elements.followUpQueueTrigger;
24128
+ setComposerActionsOpen(false);
24129
+ setPublishMenuOpen(false);
24130
+ setNativeCommandMenuOpen(false);
24131
+ setAppRunnerMenuOpen(false);
24132
+ setOptionsMenuOpen(false);
24133
+ setConversationVoiceMenuOpen(false);
24134
+ setBusyPromptBehaviorMenuOpen(false);
24135
+ setNewTabMenuOpen(false);
24136
+ }
24137
+ followUpQueueOpen = shouldOpen;
24138
+ elements.followUpQueueTrigger?.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
24139
+ if (elements.followUpQueueOverlay) elements.followUpQueueOverlay.hidden = !shouldOpen;
24140
+ if (!shouldOpen) {
24141
+ followUpQueueDrag = null;
24142
+ scheduleDeferredUiFlushAfterDropdownClose();
24143
+ if (restoreFocus) {
24144
+ const focusTarget = followUpQueueRestoreFocus?.isConnected ? followUpQueueRestoreFocus : elements.followUpQueueTrigger;
24145
+ requestAnimationFrame(() => focusTarget?.focus({ preventScroll: true }));
24146
+ }
24147
+ followUpQueueRestoreFocus = null;
24148
+ return;
24149
+ }
24150
+ renderFollowUpQueueOverlay();
24151
+ }
24152
+
24153
+ function queueMutationBody(snapshot, operation) {
24154
+ const body = {
24155
+ source: snapshot.source,
24156
+ kind: "followUp",
24157
+ expected: { steering: [...snapshot.steering], followUp: [...snapshot.followUp] },
24158
+ operation,
24159
+ };
24160
+ if (snapshot.source === "webui-compaction") body.revision = snapshot.revision;
24161
+ return body;
24162
+ }
24163
+
24164
+ function applyAuthoritativeQueuedSnapshot(tabContext, queue) {
24165
+ if (!tabContext?.tabId || !queue) return;
24166
+ const snapshot = normalizeQueuedMessages(queue);
24167
+ latestQueuedMessagesByTab.set(tabContext.tabId, snapshot);
24168
+ if (queuedSnapshotTargetsCurrentTab(tabContext)) renderQueue({ tabId: tabContext.tabId, ...snapshot });
24169
+ }
24170
+
24171
+ async function mutateQueuedFollowUp(operation, tabId = activeTabId) {
24172
+ if (!tabId || followUpQueueMutationInFlight(tabId)) return false;
24173
+ const tabContext = queueTabContext(tabId);
24174
+ const snapshot = queuedSnapshotForTab(tabId);
24175
+ if (!snapshot.followUp.length || snapshot.draining) {
24176
+ if (isCurrentTabContext(tabContext)) setFollowUpQueueStatus("Queue is draining; follow-ups can no longer be changed.", "warn");
24177
+ return false;
24178
+ }
24179
+ setFollowUpQueueMutationInFlight(tabId, true);
24180
+ if (isCurrentTabContext(tabContext)) setFollowUpQueueStatus(operation.type === "edit" ? "Saving queued follow-up…" : "Reordering queued follow-ups…");
24181
+ try {
24182
+ const response = await api("/api/queue/mutate", { method: "POST", body: queueMutationBody(snapshot, operation), tabId });
24183
+ const result = response?.data || {};
24184
+ if (result.queue) applyAuthoritativeQueuedSnapshot(tabContext, result.queue);
24185
+ if (!result.mutated) {
24186
+ if (isCurrentTabContext(tabContext)) setFollowUpQueueStatus("Queue changed before the update could be applied.", "warn");
24187
+ return false;
24188
+ }
24189
+ if (isCurrentTabContext(tabContext)) {
24190
+ const message = operation.type === "edit"
24191
+ ? `Saved queued follow-up ${operation.index + 1}.`
24192
+ : `Moved queued follow-up ${operation.from + 1} to position ${operation.to + 1}.`;
24193
+ setFollowUpQueueStatus(message, "success");
24194
+ }
24195
+ return true;
24196
+ } catch (error) {
24197
+ const result = error?.data?.data || {};
24198
+ if (result.queue) applyAuthoritativeQueuedSnapshot(tabContext, result.queue);
24199
+ if (isCurrentTabContext(tabContext)) {
24200
+ if (error?.statusCode === 409) setFollowUpQueueStatus(result.reason === "queue-draining" ? "Queue is draining; refreshed the authoritative queue." : "Queue changed elsewhere; refreshed the authoritative queue.", "warn");
24201
+ else setFollowUpQueueStatus(error.message || "Unable to update the queued follow-up.", "error");
24202
+ }
24203
+ return false;
24204
+ } finally {
24205
+ setFollowUpQueueMutationInFlight(tabId, false);
24206
+ if (isCurrentTabContext(tabContext)) renderFollowUpQueueOverlay();
24207
+ }
24208
+ }
24209
+
24210
+ function saveQueuedFollowUpText(index, expectedText, value) {
24211
+ const text = String(value ?? "");
24212
+ if (text === expectedText) return;
24213
+ if (!text.trim()) {
24214
+ setFollowUpQueueStatus("Queued follow-ups cannot be empty; restored the authoritative text.", "warn");
24215
+ renderFollowUpQueueOverlay();
24216
+ return;
24217
+ }
24218
+ void mutateQueuedFollowUp({ type: "edit", index, expectedText, text });
24219
+ }
24220
+
24221
+ function clearFollowUpQueueDragVisuals() {
24222
+ for (const row of elements.followUpQueueRows?.querySelectorAll(".follow-up-queue-row.is-dragging, .follow-up-queue-row.is-drop-target") || []) {
24223
+ row.classList.remove("is-dragging", "is-drop-target");
24224
+ }
24225
+ }
24226
+
24227
+ function renderFollowUpQueueOverlay() {
24228
+ if (deferUiRenderDuringPointerActivation("follow-up-queue", renderFollowUpQueueOverlay)) return;
24229
+ const snapshot = queuedSnapshotForTab();
24230
+ const followUps = snapshot.followUp;
24231
+ const count = followUps.length;
24232
+ const trigger = elements.followUpQueueTrigger;
24233
+ if (trigger) {
24234
+ trigger.hidden = count === 0;
24235
+ trigger.setAttribute("aria-expanded", followUpQueueOpen && count ? "true" : "false");
24236
+ trigger.setAttribute("aria-label", `${count} queued follow-up${count === 1 ? "" : "s"}`);
24237
+ }
24238
+ if (elements.followUpQueueTriggerCount) elements.followUpQueueTriggerCount.textContent = String(count);
24239
+ if (elements.followUpQueueOverlayCount) elements.followUpQueueOverlayCount.textContent = String(count);
24240
+ if (!count) {
24241
+ if (followUpQueueOpen) setFollowUpQueueOpen(false);
24242
+ if (elements.followUpQueueRows) elements.followUpQueueRows.replaceChildren();
24243
+ return;
24244
+ }
24245
+ if (!followUpQueueOpen || !elements.followUpQueueRows) return;
24246
+
24247
+ const locked = followUpQueueMutationInFlight();
24248
+ const unavailable = locked || snapshot.draining;
24249
+ const focusedDraft = focusedFollowUpQueueDraft();
24250
+ const preservedDraft = preservedFocusedFollowUpQueueDraft(focusedDraft, followUps);
24251
+ const rows = followUps.map((item, index) => {
24252
+ const row = make("article", "follow-up-queue-row");
24253
+ row.dataset.followUpIndex = String(index);
24254
+ row.draggable = false;
24255
+ const dragHandle = make("span", "follow-up-queue-drag-handle", "⠿");
24256
+ dragHandle.draggable = !unavailable;
24257
+ dragHandle.setAttribute("aria-hidden", "true");
24258
+ dragHandle.title = "Drag to reorder";
24259
+ const textarea = make("textarea", "follow-up-queue-textarea");
24260
+ const textareaDraft = preservedDraft?.index === index ? preservedDraft : null;
24261
+ textarea.value = textareaDraft ? textareaDraft.value : item;
24262
+ textarea.dataset.followUpQueueAuthoritativeText = item;
24263
+ textarea.rows = Math.max(2, Math.min(6, item.split("\n").length + 1));
24264
+ textarea.disabled = unavailable;
24265
+ textarea.setAttribute("aria-label", `Queued follow-up ${index + 1}`);
24266
+ textarea.dataset.followUpQueueMutationControl = "true";
24267
+ textarea.addEventListener("blur", () => {
24268
+ if (textarea === followUpQueueSuppressBlurFor) return;
24269
+ saveQueuedFollowUpText(index, item, textarea.value);
24270
+ });
24271
+ textarea.addEventListener("keydown", (event) => {
24272
+ if ((event.ctrlKey || event.metaKey) && !event.altKey && event.key === "Enter") {
24273
+ event.preventDefault();
24274
+ saveQueuedFollowUpText(index, item, textarea.value);
24275
+ return;
24276
+ }
24277
+ if (event.key !== "Escape") return;
24278
+ event.preventDefault();
24279
+ event.stopPropagation();
24280
+ if (textarea.value !== item) {
24281
+ textarea.value = item;
24282
+ setFollowUpQueueStatus(`Restored queued follow-up ${index + 1}.`, "warn");
24283
+ } else {
24284
+ setFollowUpQueueOpen(false, { restoreFocus: true });
24285
+ }
24286
+ });
24287
+ const controls = make("div", "follow-up-queue-row-controls");
24288
+ const moveUp = make("button", "follow-up-queue-move-button", "↑");
24289
+ moveUp.type = "button";
24290
+ moveUp.dataset.followUpQueueMutationControl = "true";
24291
+ moveUp.dataset.queueBoundary = index === 0 ? "true" : "false";
24292
+ moveUp.disabled = unavailable || index === 0;
24293
+ moveUp.title = `Move queued follow-up ${index + 1} up`;
24294
+ moveUp.setAttribute("aria-label", `Move queued follow-up ${index + 1} up`);
24295
+ moveUp.addEventListener("click", () => void mutateQueuedFollowUp({ type: "move", from: index, to: index - 1, expectedText: item }));
24296
+ const moveDown = make("button", "follow-up-queue-move-button", "↓");
24297
+ moveDown.type = "button";
24298
+ moveDown.dataset.followUpQueueMutationControl = "true";
24299
+ moveDown.dataset.queueBoundary = index === followUps.length - 1 ? "true" : "false";
24300
+ moveDown.disabled = unavailable || index === followUps.length - 1;
24301
+ moveDown.title = `Move queued follow-up ${index + 1} down`;
24302
+ moveDown.setAttribute("aria-label", `Move queued follow-up ${index + 1} down`);
24303
+ moveDown.addEventListener("click", () => void mutateQueuedFollowUp({ type: "move", from: index, to: index + 1, expectedText: item }));
24304
+ controls.append(moveUp, moveDown);
24305
+ row.append(dragHandle, textarea, controls);
24306
+ row.addEventListener("dragstart", (event) => {
24307
+ if (unavailable || event.target?.closest?.(".follow-up-queue-drag-handle") !== dragHandle) {
24308
+ event.preventDefault();
24309
+ return;
24310
+ }
24311
+ followUpQueueDrag = { tabId: activeTabId, index, expectedText: item };
24312
+ event.dataTransfer?.setData("application/x-pi-webui-follow-up", JSON.stringify(followUpQueueDrag));
24313
+ if (event.dataTransfer) event.dataTransfer.effectAllowed = "move";
24314
+ row.classList.add("is-dragging");
24315
+ });
24316
+ row.addEventListener("dragover", (event) => {
24317
+ if (!followUpQueueDrag || followUpQueueDrag.tabId !== activeTabId || unavailable || isFileDrag(event)) return;
24318
+ event.preventDefault();
24319
+ event.stopPropagation();
24320
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
24321
+ clearFollowUpQueueDragVisuals();
24322
+ row.classList.add("is-drop-target");
24323
+ });
24324
+ row.addEventListener("dragleave", (event) => {
24325
+ if (!row.contains(event.relatedTarget)) row.classList.remove("is-drop-target");
24326
+ });
24327
+ row.addEventListener("drop", (event) => {
24328
+ if (!followUpQueueDrag || followUpQueueDrag.tabId !== activeTabId || unavailable || isFileDrag(event)) return;
24329
+ event.preventDefault();
24330
+ event.stopPropagation();
24331
+ const drag = followUpQueueDrag;
24332
+ clearFollowUpQueueDragVisuals();
24333
+ followUpQueueDrag = null;
24334
+ if (drag.index !== index) void mutateQueuedFollowUp({ type: "move", from: drag.index, to: index, expectedText: drag.expectedText });
24335
+ });
24336
+ row.addEventListener("dragend", () => {
24337
+ followUpQueueDrag = null;
24338
+ clearFollowUpQueueDragVisuals();
24339
+ });
24340
+ return row;
24341
+ });
24342
+ followUpQueueSuppressBlurFor = focusedDraft?.textarea || null;
24343
+ try {
24344
+ elements.followUpQueueRows.replaceChildren(...rows);
24345
+ } finally {
24346
+ followUpQueueSuppressBlurFor = null;
24347
+ }
24348
+ if (preservedDraft && !unavailable) {
24349
+ requestAnimationFrame(() => {
24350
+ if (!followUpQueueOpen || activeTabId === null) return;
24351
+ const activeElement = document.activeElement;
24352
+ if (activeElement && activeElement !== document.body && activeElement !== document.documentElement) return;
24353
+ const textarea = elements.followUpQueueRows?.querySelector(`.follow-up-queue-row[data-follow-up-index="${preservedDraft.index}"] textarea`);
24354
+ if (!textarea) return;
24355
+ textarea.focus({ preventScroll: true });
24356
+ textarea.setSelectionRange(preservedDraft.selectionStart, preservedDraft.selectionEnd);
24357
+ });
24358
+ }
24359
+ setFollowUpQueueStatus(followUpQueueStatus.text, followUpQueueStatus.level);
24360
+ syncFollowUpQueueMutationControls();
24361
+ }
24362
+
23076
24363
  async function removeQueuedFollowUpPrompt(index, message, tabId = activeTabId) {
23077
- if (!tabId) return false;
23078
- const tabContext = activeTabContext(tabId);
24364
+ if (!tabId || queuedSnapshotForTab(tabId).source !== "pi-runtime") return false;
24365
+ const tabContext = queueTabContext(tabId);
23079
24366
  try {
23080
24367
  const response = await api("/api/queue/remove", { method: "POST", body: { kind: "followUp", index, message }, tabId });
23081
24368
  const data = response?.data || {};
23082
- if (data.queue && isCurrentTabContext(tabContext)) renderQueue({ tabId, ...data.queue });
24369
+ if (data.queue) applyAuthoritativeQueuedSnapshot(tabContext, data.queue);
23083
24370
  if (data.removed) {
23084
24371
  if (isCurrentTabContext(tabContext)) addEvent(`removed queued follow-up #${index + 1}`);
23085
24372
  scheduleRefreshState(120, tabContext);
@@ -23129,6 +24416,7 @@ function renderQueue(event) {
23129
24416
  const snapshot = normalizeQueuedMessages(event);
23130
24417
  const tabId = event?.tabId || activeTabId;
23131
24418
  if (tabId) latestQueuedMessagesByTab.set(tabId, snapshot);
24419
+ if (tabId && tabId !== activeTabId) return;
23132
24420
  const steering = snapshot.steering;
23133
24421
  const followUp = snapshot.followUp;
23134
24422
  const total = queueMessageCount(snapshot);
@@ -23138,6 +24426,7 @@ function renderQueue(event) {
23138
24426
  elements.queueBox.classList.toggle("has-items", total > 0);
23139
24427
  if (total === 0) {
23140
24428
  elements.queueBox.append(make("div", "queue-empty", "No queued messages."));
24429
+ if (tabId === activeTabId) renderFollowUpQueueOverlay();
23141
24430
  updateStickyUserPromptButton();
23142
24431
  return;
23143
24432
  }
@@ -23151,19 +24440,16 @@ function renderQueue(event) {
23151
24440
 
23152
24441
  elements.queueBox.append(summary);
23153
24442
  if (steering.length) elements.queueBox.append(renderQueueGroup("Steering", steering, "steering", { tabId }));
23154
- if (followUp.length) elements.queueBox.append(renderQueueGroup("Follow-up", followUp, "follow-up", { removable: true, tabId }));
23155
- elements.queueBox.append(make("div", "queue-hint", "Alt+Up restores this queue snapshot to the composer without clearing Pi's queue. Use Remove beside follow-ups to drop them from the queue."));
24443
+ if (followUp.length) elements.queueBox.append(renderQueueGroup("Follow-up", followUp, "follow-up", { removable: snapshot.source === "pi-runtime", tabId }));
24444
+ elements.queueBox.append(make("div", "queue-hint", snapshot.source === "pi-runtime"
24445
+ ? "Alt+Up restores this queue snapshot to the composer without clearing Pi's queue. Use Remove beside follow-ups to drop them from the queue."
24446
+ : "Alt+Up restores this queue snapshot to the composer without clearing Pi's queue. Edit and reorder compaction-held follow-ups with the composer Queue control."));
24447
+ if (tabId === activeTabId) renderFollowUpQueueOverlay();
23156
24448
  updateStickyUserPromptButton();
23157
24449
  }
23158
24450
 
23159
- function nextQueuedFollowUpPrompt(tabId = activeTabId) {
23160
- const snapshot = tabId ? latestQueuedMessagesByTab.get(tabId) : null;
23161
- const next = Array.isArray(snapshot?.followUp) ? snapshot.followUp.find((item) => String(item || "").trim()) : null;
23162
- return next ? stickyUserPromptPreviewText(next) : "";
23163
- }
23164
-
23165
24451
  function queuedMessagesForComposer(tabId = activeTabId) {
23166
- const snapshot = latestQueuedMessagesByTab.get(tabId) || { steering: [], followUp: [] };
24452
+ const snapshot = queuedSnapshotForTab(tabId);
23167
24453
  return [...(snapshot.steering || []), ...(snapshot.followUp || [])].map((item) => String(item || "").trim()).filter(Boolean);
23168
24454
  }
23169
24455
 
@@ -25019,6 +26305,12 @@ function renderEmptyStartState() {
25019
26305
  className: "primary",
25020
26306
  onClick: (button) => createTerminalTabFromChosenDirectory({ triggerButton: button }),
25021
26307
  }),
26308
+ emptyStartAction({
26309
+ title: "Load workspace",
26310
+ description: "Restore a saved tab constellation",
26311
+ symbol: "⇱",
26312
+ onClick: (button) => openWorkspaceLoadPicker({ triggerButton: button }),
26313
+ }),
25022
26314
  emptyStartAction({
25023
26315
  title: "Resume session",
25024
26316
  description: "Continue previous work and context",
@@ -25121,21 +26413,15 @@ function updateStickyUserPromptButton() {
25121
26413
  button.dataset.compacted = target.compacted ? "true" : "false";
25122
26414
  if (Number.isInteger(target.index) && target.index >= 0) button.dataset.messageIndex = String(target.index);
25123
26415
  else button.removeAttribute("data-message-index");
25124
- const nextFollowUp = nextQueuedFollowUpPrompt();
25125
26416
  const baseTitle = target.compacted ? `Prompt was compacted; jump to compaction summary: ${target.preview}` : `Jump to ${label.toLowerCase()}: ${target.preview}`;
25126
26417
  const baseAriaLabel = target.compacted ? `Prompt was compacted; jump to compaction summary: ${target.preview}` : `Jump to ${label.toLowerCase()} (${ordinal} of ${targets.length}): ${target.preview}`;
25127
- button.title = nextFollowUp ? `${baseTitle}\nNext follow-up prompt: ${nextFollowUp}` : baseTitle;
25128
- button.setAttribute("aria-label", nextFollowUp ? `${baseAriaLabel}. Next follow-up prompt: ${nextFollowUp}` : baseAriaLabel);
26418
+ button.title = baseTitle;
26419
+ button.setAttribute("aria-label", baseAriaLabel);
25129
26420
  const children = [
25130
26421
  make("span", "sticky-user-prompt-label", label),
25131
26422
  make("span", "sticky-user-prompt-text", target.preview),
25132
26423
  make("span", "sticky-user-prompt-meta", meta),
25133
26424
  ];
25134
- if (nextFollowUp) {
25135
- const followUp = make("span", "sticky-user-follow-up-prompt");
25136
- followUp.append(make("span", "sticky-user-follow-up-label", "Next follow-up"), make("span", "sticky-user-follow-up-text", nextFollowUp));
25137
- children.push(followUp);
25138
- }
25139
26425
  button.replaceChildren(...children);
25140
26426
  }
25141
26427
 
@@ -26924,6 +28210,7 @@ async function sendBtwPromptFromButton() {
26924
28210
  }
26925
28211
 
26926
28212
  function setPublishMenuOpen(open) {
28213
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26927
28214
  publishMenuOpen = !!open;
26928
28215
  elements.publishButton.setAttribute("aria-expanded", publishMenuOpen ? "true" : "false");
26929
28216
  elements.publishButton.classList.toggle("menu-open", publishMenuOpen);
@@ -26933,6 +28220,7 @@ function setPublishMenuOpen(open) {
26933
28220
  }
26934
28221
 
26935
28222
  function setNativeCommandMenuOpen(open) {
28223
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26936
28224
  nativeCommandMenuOpen = !!open;
26937
28225
  elements.nativeCommandMenuButton.setAttribute("aria-expanded", nativeCommandMenuOpen ? "true" : "false");
26938
28226
  elements.nativeCommandMenuButton.classList.toggle("menu-open", nativeCommandMenuOpen);
@@ -26942,6 +28230,7 @@ function setNativeCommandMenuOpen(open) {
26942
28230
  }
26943
28231
 
26944
28232
  function setAppRunnerMenuOpen(open) {
28233
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26945
28234
  appRunnerMenuOpen = !!open;
26946
28235
  elements.appRunnerMenuButton?.setAttribute("aria-expanded", appRunnerMenuOpen ? "true" : "false");
26947
28236
  elements.appRunnerMenuButton?.classList.toggle("menu-open", appRunnerMenuOpen);
@@ -26951,6 +28240,7 @@ function setAppRunnerMenuOpen(open) {
26951
28240
  }
26952
28241
 
26953
28242
  function setOptionsMenuOpen(open) {
28243
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26954
28244
  optionsMenuOpen = !!open;
26955
28245
  elements.optionsMenuButton.setAttribute("aria-expanded", optionsMenuOpen ? "true" : "false");
26956
28246
  elements.optionsMenuButton.classList.toggle("menu-open", optionsMenuOpen);
@@ -31413,6 +32703,10 @@ function commandPaletteCoreItems() {
31413
32703
  { kind: "Pi", label: "/tools", description: "Manage active tools", keywords: "capabilities", run: () => runNativeCommandMenu("/tools") },
31414
32704
  { kind: "Pi", label: "/skills", description: "Manage active skills", keywords: "system prompt", run: () => runNativeCommandMenu("/skills") },
31415
32705
  ];
32706
+ if (tabs.length) {
32707
+ items.push({ kind: "Workspace", label: "Workspace: Save", description: "Capture all open tabs, sessions, groups, and the active tab", keywords: "workspace snapshot save sessions groups", run: () => saveWebuiWorkspace({ triggerButton: elements.commandPaletteButton }) });
32708
+ }
32709
+ items.push({ kind: "Workspace", label: "Workspace: Load…", description: tabs.length ? "Choose a saved workspace and decide whether to save current tabs" : "Show saved workspaces to restore", keywords: "workspace restore saved sessions groups", run: () => openWorkspaceLoadPicker({ triggerButton: elements.commandPaletteButton }) });
31416
32710
  if (isOptionalFeatureEnabled("statsCommand")) items.push({ kind: "Pi", label: "/stats-webui", description: "Open usage dashboard", keywords: "tokens cost budget", run: () => openStatsOverlay({ refresh: true }) });
31417
32711
  return items;
31418
32712
  }
@@ -33103,6 +34397,10 @@ elements.composer.addEventListener("submit", (event) => {
33103
34397
  event.preventDefault();
33104
34398
  sendPrompt("prompt");
33105
34399
  });
34400
+ elements.followUpQueueTrigger?.addEventListener("click", () => {
34401
+ setFollowUpQueueOpen(!followUpQueueOpen);
34402
+ });
34403
+ elements.followUpQueueCloseButton?.addEventListener("click", () => setFollowUpQueueOpen(false, { restoreFocus: true }));
33106
34404
  elements.composerActionsButton.addEventListener("click", () => {
33107
34405
  setComposerActionsOpen(!document.body.classList.contains("composer-actions-open"));
33108
34406
  });
@@ -33205,6 +34503,7 @@ elements.newTabCurrentDirectoryButton?.addEventListener("click", () => createTer
33205
34503
  elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerminalTabFromChosenDirectory({ triggerButton: elements.newTabChooseDirectoryButton }));
33206
34504
  elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
33207
34505
  elements.splitTabButton?.addEventListener("click", () => splitActiveTerminalTab());
34506
+ elements.workspaceSaveButton?.addEventListener("click", () => saveWebuiWorkspace());
33208
34507
  elements.terminalSplitCloseButton?.addEventListener("click", () => closeTerminalSplitView());
33209
34508
  elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
33210
34509
  elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
@@ -33449,6 +34748,30 @@ elements.confirmationDialog?.addEventListener("cancel", (event) => {
33449
34748
  elements.confirmationDialog?.addEventListener("close", () => {
33450
34749
  if (activeConfirmationResolve) finishApplicationConfirmation(false);
33451
34750
  });
34751
+ elements.workspaceLoadDialogCloseButton?.addEventListener("click", () => closeWorkspaceLoadDialog());
34752
+ elements.workspaceLoadDialog?.addEventListener("cancel", (event) => {
34753
+ event.preventDefault();
34754
+ closeWorkspaceLoadDialog();
34755
+ });
34756
+ elements.workspaceLoadDialog?.addEventListener("close", () => {
34757
+ const target = workspaceLoadPickerFocusReturn;
34758
+ workspaceLoadPickerFocusReturn = null;
34759
+ if (target instanceof HTMLElement && target.isConnected) queueMicrotask(() => target.focus());
34760
+ });
34761
+ elements.workspaceReplaceCancelButton?.addEventListener("click", () => finishWorkspaceReplacement(null));
34762
+ elements.workspaceReplaceDiscardButton?.addEventListener("click", () => finishWorkspaceReplacement({ replaceOpenTabs: true, discardCurrent: true }));
34763
+ elements.workspaceReplaceSaveButton?.addEventListener("click", () => finishWorkspaceReplacement(workspaceSaveCurrentDecision()));
34764
+ elements.workspaceReplaceDialog?.querySelector("form")?.addEventListener("submit", (event) => {
34765
+ event.preventDefault();
34766
+ finishWorkspaceReplacement(workspaceSaveCurrentDecision());
34767
+ });
34768
+ elements.workspaceReplaceDialog?.addEventListener("cancel", (event) => {
34769
+ event.preventDefault();
34770
+ finishWorkspaceReplacement(null);
34771
+ });
34772
+ elements.workspaceReplaceDialog?.addEventListener("close", () => {
34773
+ if (activeWorkspaceReplacementResolve) finishWorkspaceReplacement(null);
34774
+ });
33452
34775
  elements.gitWorktreeBaseCancelButton?.addEventListener("click", () => finishGitWorktreeBaseChoice(null));
33453
34776
  elements.gitWorktreeBaseCreateButton?.addEventListener("click", () => finishGitWorktreeBaseChoice(elements.gitWorktreeBaseCurrentHead?.checked ? "HEAD" : "origin/main"));
33454
34777
  elements.gitWorktreeBaseDialog?.querySelector("form")?.addEventListener("submit", (event) => {
@@ -33915,6 +35238,23 @@ elements.subagentTerminalCopyButton?.addEventListener("click", () => copySubagen
33915
35238
  elements.subagentTerminalRefreshButton?.addEventListener("click", () => {
33916
35239
  refreshSubagentTerminalView(activeSubagentTerminalId, { showLoading: true }).finally(() => scheduleSubagentTerminalRefresh());
33917
35240
  });
35241
+ elements.subagentTerminalCancelButton?.addEventListener("click", () => {
35242
+ const view = activeSubagentTerminalView();
35243
+ if (view) openSubagentCancelDialog(view.tab || { tabId: view.parentTabId, tabTitle: view.parentTitle }, view.run, view.data?.agent || view.agent);
35244
+ });
35245
+ elements.subagentCancelKeepRunningButton?.addEventListener("click", closeSubagentCancelDialog);
35246
+ elements.subagentCancelDialog?.querySelector("form")?.addEventListener("submit", (event) => {
35247
+ event.preventDefault();
35248
+ void submitSubagentCancel();
35249
+ });
35250
+ elements.subagentCancelDialog?.addEventListener("cancel", (event) => {
35251
+ if (subagentCancelSubmitting) event.preventDefault();
35252
+ });
35253
+ elements.subagentCancelDialog?.addEventListener("close", () => {
35254
+ subagentCancelSelection = null;
35255
+ setSubagentCancelSubmitting(false);
35256
+ setSubagentCancelStatus();
35257
+ });
33918
35258
  elements.piVersionButton?.addEventListener("click", () => {
33919
35259
  openPiReleaseNotes().catch((error) => addEvent(error.message || String(error), "error"));
33920
35260
  });
@@ -33961,6 +35301,9 @@ document.addEventListener("pointerdown", (event) => {
33961
35301
  if (document.body.classList.contains("composer-actions-open") && !elements.composer.contains(event.target)) {
33962
35302
  setComposerActionsOpen(false);
33963
35303
  }
35304
+ if (followUpQueueOpen && !event.target?.closest?.("#followUpQueueOverlay, #followUpQueueTrigger")) {
35305
+ setFollowUpQueueOpen(false, { restoreFocus: true });
35306
+ }
33964
35307
  if (publishMenuOpen && !event.target?.closest?.(".composer-publish-menu")) {
33965
35308
  setPublishMenuOpen(false);
33966
35309
  }
@@ -34138,6 +35481,7 @@ function stepChatSearch(step) {
34138
35481
 
34139
35482
  function openChatSearch() {
34140
35483
  if (!elements.chatSearchBar) return;
35484
+ closeFileViewerSearch({ restoreFocus: false });
34141
35485
  elements.chatSearchBar.hidden = false;
34142
35486
  elements.chatSearchInput?.focus();
34143
35487
  elements.chatSearchInput?.select();
@@ -34176,7 +35520,8 @@ elements.chatSearchCloseButton?.addEventListener("click", closeChatSearch);
34176
35520
  window.addEventListener("keydown", (event) => {
34177
35521
  if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") {
34178
35522
  event.preventDefault();
34179
- openChatSearch();
35523
+ if (activeFileViewer && elements.fileViewerPane?.contains(event.target)) openFileViewerSearch();
35524
+ else openChatSearch();
34180
35525
  }
34181
35526
  });
34182
35527
 
@@ -34202,6 +35547,11 @@ window.addEventListener("keydown", (event) => {
34202
35547
  if (event.key !== "Escape") return;
34203
35548
  if (event.defaultPrevented) return;
34204
35549
  if (elements.dialog?.open || elements.pathPickerDialog?.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open) return;
35550
+ if (followUpQueueOpen) {
35551
+ event.preventDefault();
35552
+ setFollowUpQueueOpen(false, { restoreFocus: true });
35553
+ return;
35554
+ }
34205
35555
  if (publishMenuOpen) {
34206
35556
  setPublishMenuOpen(false);
34207
35557
  return;
@@ -34412,12 +35762,33 @@ elements.fileViewerCloseButton?.addEventListener("click", closeFileViewer);
34412
35762
  elements.fileViewerChangesModeButton?.addEventListener("click", () => setFileViewerMode("changes"));
34413
35763
  elements.fileViewerSourceModeButton?.addEventListener("click", () => setFileViewerMode("source"));
34414
35764
  elements.fileViewerPreviewModeButton?.addEventListener("click", () => setFileViewerMode("preview"));
35765
+ elements.fileViewerSearchInput?.addEventListener("input", () => {
35766
+ clearTimeout(fileViewerSearchTimer);
35767
+ fileViewerSearchTimer = setTimeout(() => {
35768
+ fileViewerSearchIndex = -1;
35769
+ runFileViewerSearch({ navigate: true });
35770
+ }, 150);
35771
+ });
35772
+ elements.fileViewerSearchInput?.addEventListener("keydown", (event) => {
35773
+ if (event.key === "Enter") {
35774
+ event.preventDefault();
35775
+ stepFileViewerSearch(event.shiftKey ? -1 : 1);
35776
+ } else if (event.key === "Escape") {
35777
+ event.preventDefault();
35778
+ event.stopPropagation();
35779
+ closeFileViewerSearch();
35780
+ }
35781
+ });
35782
+ elements.fileViewerSearchPrevButton?.addEventListener("click", () => stepFileViewerSearch(-1));
35783
+ elements.fileViewerSearchNextButton?.addEventListener("click", () => stepFileViewerSearch(1));
35784
+ elements.fileViewerSearchCloseButton?.addEventListener("click", () => closeFileViewerSearch());
34415
35785
  elements.fileViewerEditor?.addEventListener("input", () => {
34416
35786
  if (!activeFileViewer) return;
34417
35787
  activeFileViewer.content = elements.fileViewerEditor.value || "";
34418
35788
  activeFileViewer.size = new Blob([activeFileViewer.content]).size;
34419
35789
  setFileViewerDirty(true);
34420
35790
  updateFileViewerSelectionFromEditor();
35791
+ if (elements.fileViewerSearchBar && !elements.fileViewerSearchBar.hidden) runFileViewerSearch();
34421
35792
  });
34422
35793
  for (const eventName of ["select", "keyup", "mouseup"]) {
34423
35794
  elements.fileViewerEditor?.addEventListener(eventName, updateFileViewerSelectionFromEditor);