@firstpick/pi-package-webui 0.7.7 → 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.
Files changed (50) hide show
  1. package/README.md +23 -0
  2. package/bin/pi-webui-rpc-supervisor.mjs +115 -21
  3. package/bin/pi-webui.mjs +447 -88
  4. package/lib/queue-mutation.mjs +109 -0
  5. package/lib/rpc-supervisor-client.mjs +18 -2
  6. package/lib/rpc-supervisor-protocol.mjs +11 -2
  7. package/lib/scoped-models.mjs +19 -0
  8. package/lib/webui-workspaces.mjs +265 -0
  9. package/package.json +4 -4
  10. package/public/app.js +2227 -195
  11. package/public/index.html +143 -2
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +3 -1
  15. package/public/styles.css +787 -56
  16. package/public/voice-conversation.mjs +1 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  18. package/tests/compaction-mutation-contract.test.mjs +166 -0
  19. package/tests/compaction-resume-harness.test.mjs +113 -2
  20. package/tests/compaction-static.test.mjs +5 -0
  21. package/tests/completion-signal-contract.test.mjs +156 -0
  22. package/tests/cwd-footer-reliability-static.test.mjs +112 -0
  23. package/tests/durable-rpc-supervisor-harness.test.mjs +25 -2
  24. package/tests/fast-mode-client-static.test.mjs +1 -1
  25. package/tests/file-selection-overlay-static.test.mjs +21 -0
  26. package/tests/file-viewer-search-static.test.mjs +65 -0
  27. package/tests/fixtures/compacting-pi.mjs +0 -0
  28. package/tests/fixtures/fake-pi.mjs +186 -49
  29. package/tests/footer-context-contrast-static.test.mjs +10 -0
  30. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  31. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  32. package/tests/http-endpoints-harness.test.mjs +160 -1
  33. package/tests/issue-bot-client.test.mjs +135 -0
  34. package/tests/issue-wizard-state.test.mjs +126 -0
  35. package/tests/mobile-static.test.mjs +61 -42
  36. package/tests/native-parity.test.mjs +3 -3
  37. package/tests/open-issue-wizard-static.test.mjs +75 -0
  38. package/tests/prompt-routing-tab-status.test.mjs +5 -0
  39. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  40. package/tests/queue-mutation-contract.test.mjs +143 -0
  41. package/tests/rpc-supervisor-host.test.mjs +135 -2
  42. package/tests/rpc-supervisor-protocol.test.mjs +26 -0
  43. package/tests/scoped-models.test.mjs +42 -0
  44. package/tests/streaming-ui-coupling.test.mjs +3 -2
  45. package/tests/subagents-helper.test.mjs +216 -3
  46. package/tests/terminal-tab-workspace-static.test.mjs +101 -0
  47. package/tests/webui-workspaces-harness.test.mjs +223 -0
  48. package/tests/webui-workspaces.test.mjs +106 -0
  49. package/tests/workspace-save-load-static.test.mjs +69 -0
  50. package/webui-rpc-helper.mjs +300 -41
package/public/app.js CHANGED
@@ -5,6 +5,8 @@ import { createFastOutputLiveState, createSustainedFlushScheduler, fastOutputLiv
5
5
  import { addLaunchSlot, cloneLaunchSlotRoles, launchSlotRolesEqual, removeLaunchSlot, updateLaunchSlot } from "./subagent-launch-slot-state.mjs";
6
6
  import { pruneDismissedSubagentGateKeys, subagentGateIsTerminal, subagentGateKey, visibleSubagentGates } from "./subagent-gate-visibility.mjs";
7
7
  import { groupConsecutiveWorkflowStatusItems, isCompletedWorkflowStatusExecution, workflowStatusSnapshot } from "./workflow-status-stack.mjs";
8
+ import { buildIssuePayload, createIssueWizardCatalog, createIssueWizardState, getCompatibleTemplates, isIssueWizardStepValid, issueClipboardText, reduceIssueWizardState } from "./issue-wizard-state.mjs";
9
+ import { createIssueBotClient, readIssueBotRuntimeConfig } from "./issue-bot-client.mjs";
8
10
 
9
11
  const $ = (selector) => document.querySelector(selector);
10
12
 
@@ -15,6 +17,7 @@ const elements = {
15
17
  tabBar: $("#tabBar"),
16
18
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
17
19
  splitTabButton: $("#splitTabButton"),
20
+ workspaceSaveButton: $("#workspaceSaveButton"),
18
21
  newTabMenu: $("#newTabMenu"),
19
22
  newTabButton: $("#newTabButton"),
20
23
  newTabMenuPanel: $("#newTabMenuPanel"),
@@ -55,7 +58,15 @@ const elements = {
55
58
  subagentTerminalStatus: $("#subagentTerminalStatus"),
56
59
  subagentTerminalCopyButton: $("#subagentTerminalCopyButton"),
57
60
  subagentTerminalRefreshButton: $("#subagentTerminalRefreshButton"),
61
+ subagentTerminalCancelButton: $("#subagentTerminalCancelButton"),
58
62
  subagentTerminalInput: $("#subagentTerminalInput"),
63
+ subagentCancelDialog: $("#subagentCancelDialog"),
64
+ subagentCancelDialogSubtitle: $("#subagentCancelDialogSubtitle"),
65
+ subagentCancelReason: $("#subagentCancelReason"),
66
+ subagentCancelNote: $("#subagentCancelNote"),
67
+ subagentCancelStatus: $("#subagentCancelStatus"),
68
+ subagentCancelKeepRunningButton: $("#subagentCancelKeepRunningButton"),
69
+ subagentCancelSubmitButton: $("#subagentCancelSubmitButton"),
59
70
  stickyUserPromptButton: $("#stickyUserPromptButton"),
60
71
  chat: $("#chat"),
61
72
  chatSearchBar: $("#chatSearchBar"),
@@ -73,6 +84,13 @@ const elements = {
73
84
  composerActionsButton: $("#composerActionsButton"),
74
85
  composerActionsPanel: $("#composerActionsPanel"),
75
86
  promptInput: $("#promptInput"),
87
+ followUpQueueTrigger: $("#followUpQueueTrigger"),
88
+ followUpQueueTriggerCount: $("#followUpQueueTriggerCount"),
89
+ followUpQueueOverlay: $("#followUpQueueOverlay"),
90
+ followUpQueueOverlayCount: $("#followUpQueueOverlayCount"),
91
+ followUpQueueRows: $("#followUpQueueRows"),
92
+ followUpQueueStatus: $("#followUpQueueStatus"),
93
+ followUpQueueCloseButton: $("#followUpQueueCloseButton"),
76
94
  busyPromptBehaviorTag: $("#busyPromptBehaviorTag"),
77
95
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
78
96
  sessionSkillTags: $("#sessionSkillTags"),
@@ -233,6 +251,12 @@ const elements = {
233
251
  fileViewerPreview: $("#fileViewerPreview"),
234
252
  fileViewerChanges: $("#fileViewerChanges"),
235
253
  fileViewerStatus: $("#fileViewerStatus"),
254
+ fileViewerSearchBar: $("#fileViewerSearchBar"),
255
+ fileViewerSearchInput: $("#fileViewerSearchInput"),
256
+ fileViewerSearchCount: $("#fileViewerSearchCount"),
257
+ fileViewerSearchPrevButton: $("#fileViewerSearchPrevButton"),
258
+ fileViewerSearchNextButton: $("#fileViewerSearchNextButton"),
259
+ fileViewerSearchCloseButton: $("#fileViewerSearchCloseButton"),
236
260
  fileSelectionBar: $("#fileSelectionBar"),
237
261
  fileSelectionSummary: $("#fileSelectionSummary"),
238
262
  fileSelectionCommentInput: $("#fileSelectionCommentInput"),
@@ -244,6 +268,24 @@ const elements = {
244
268
  sidePanelExpandButton: $("#sidePanelExpandButton"),
245
269
  sidePanelBackdrop: $("#sidePanelBackdrop"),
246
270
  sidePanel: $("#sidePanel"),
271
+ openIssueButton: $("#openIssueButton"),
272
+ issueWizardDialog: $("#issueWizardDialog"),
273
+ issueWizardPages: $("#issueWizardPages"),
274
+ issueWizardProgress: $("#issueWizardProgress"),
275
+ issueWizardStatus: $("#issueWizardStatus"),
276
+ issueWizardSubmissionStatus: $("#issueWizardSubmissionStatus"),
277
+ issueWizardSubmissionMessage: $("#issueWizardSubmissionMessage"),
278
+ issueWizardSubmissionLink: $("#issueWizardSubmissionLink"),
279
+ issueWizardRefreshButton: $("#issueWizardRefreshButton"),
280
+ issueWizardSecurityGuidance: $("#issueWizardSecurityGuidance"),
281
+ issueWizardSecurityLink: $("#issueWizardSecurityLink"),
282
+ issueWizardTurnstile: $("#issueWizardTurnstile"),
283
+ issueWizardCloseButton: $("#issueWizardCloseButton"),
284
+ issueWizardBackButton: $("#issueWizardBackButton"),
285
+ issueWizardContinueButton: $("#issueWizardContinueButton"),
286
+ issueWizardCopyButton: $("#issueWizardCopyButton"),
287
+ issueWizardBotButton: $("#issueWizardBotButton"),
288
+ issueWizardBotHint: $("#issueWizardBotHint"),
247
289
  stateDetails: $("#stateDetails"),
248
290
  subagentsStatus: $("#subagentsStatus"),
249
291
  subagentsBox: $("#subagentsBox"),
@@ -306,6 +348,19 @@ const elements = {
306
348
  confirmationUndo: $("#confirmationUndo"),
307
349
  confirmationCancelButton: $("#confirmationCancelButton"),
308
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"),
309
364
  gitWorktreeBaseDialog: $("#gitWorktreeBaseDialog"),
310
365
  gitWorktreeBaseBranch: $("#gitWorktreeBaseBranch"),
311
366
  gitWorktreeBaseOriginMain: $("#gitWorktreeBaseOriginMain"),
@@ -391,9 +446,16 @@ let activeTextAttachmentEditor = null;
391
446
  let activeSkillEditor = null;
392
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() };
393
448
  let activeFileViewer = null;
449
+ let fileViewersByTab = new Map();
394
450
  let fileViewerOpenRequestSerial = 0;
395
451
  let fileViewerGitChangesRequestSerial = 0;
396
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;
397
459
  let fileContextMenuState = null;
398
460
  let sidePanelContextMenuState = null;
399
461
  let fileTreeDragState = null;
@@ -462,6 +524,8 @@ const supervisorContinuityRefreshes = new Map();
462
524
  const supervisorEnvelopeWarnings = new Set();
463
525
  let activeDialog = null;
464
526
  let activeConfirmationResolve = null;
527
+ let activeWorkspaceReplacementResolve = null;
528
+ let workspaceLoadPickerFocusReturn = null;
465
529
  let activeGitWorktreeBaseResolve = null;
466
530
  let activeUndoAction = null;
467
531
  let undoToastTimer = null;
@@ -495,6 +559,11 @@ let mobileTabsExpanded = false;
495
559
  let openTerminalTabGroupKey = null;
496
560
  let terminalCustomGroups = new Map();
497
561
  let terminalCustomGroupSerial = 1;
562
+ let savedWorkspaces = [];
563
+ let savedWorkspacesLoaded = false;
564
+ let savedWorkspacesLoading = false;
565
+ let savedWorkspacesError = "";
566
+ let savedWorkspacesRefreshPromise = null;
498
567
  let terminalTabDragId = null;
499
568
  let splitTabId = null;
500
569
  let newTabMenuOpen = false;
@@ -567,7 +636,10 @@ let subagentOverlayLoading = false;
567
636
  let subagentOverlayRefreshTimer = null;
568
637
  let subagentOverlayRequestSerial = 0;
569
638
  let subagentOpenMode = "overlay";
639
+ let subagentCancelSelection = null;
640
+ let subagentCancelSubmitting = false;
570
641
  const subagentTerminalViews = new Map();
642
+ const subagentTerminalRestoredParentTabs = new Set();
571
643
  let activeSubagentTerminalId = null;
572
644
  let subagentTerminalRefreshTimer = null;
573
645
  let subagentLaunchSlotConfig = null;
@@ -659,6 +731,12 @@ let abortRequestInFlight = false;
659
731
  let userBashByTab = new Map();
660
732
  let userBashQueuesByTab = new Map();
661
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;
662
740
  let loadedPromptList = null;
663
741
  let promptListRunning = false;
664
742
  let workspaceDashboardCollapsed = false;
@@ -713,6 +791,8 @@ const GIT_FOOTER_WEBUI_STATUS_KEY = "git-footer-webui";
713
791
  const GIT_FOOTER_WEBUI_PAYLOAD_TYPE = "firstpick.git-footer-status.footer";
714
792
  const GIT_FOOTER_WEBUI_PAYLOAD_VERSION = 1;
715
793
  const GIT_FOOTER_WEBUI_PAYLOAD_CACHE_KEY = "pi-webui-git-footer-webui-payload-cache";
794
+ const GIT_FOOTER_PAYLOAD_REQUEST_TIMEOUT_MS = 10_000;
795
+ const GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS = 2_000;
716
796
  const GIT_FOOTER_STATUS_SETUP_STORAGE_KEY = "pi-webui-git-footer-status-setup";
717
797
  const GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS = Object.freeze({
718
798
  tokens: true,
@@ -1067,6 +1147,389 @@ const OPTIONAL_FEATURES = [
1067
1147
  },
1068
1148
  ];
1069
1149
  const OPTIONAL_FEATURE_BY_ID = new Map(OPTIONAL_FEATURES.map((feature) => [feature.id, feature]));
1150
+
1151
+ let issueWizardCatalog = null;
1152
+ let issueWizardState = createIssueWizardState();
1153
+ const issueBotRuntimeConfig = readIssueBotRuntimeConfig();
1154
+ let issueBotClient = null;
1155
+ let issueBotAbortController = null;
1156
+ let issueBotSubmissionHandle = null;
1157
+ let issueBotSubmissionResult = null;
1158
+ let issueBotRequestActive = false;
1159
+
1160
+ function setIssueWizardStatus(message) {
1161
+ if (elements.issueWizardStatus) elements.issueWizardStatus.textContent = message;
1162
+ }
1163
+
1164
+ function issueWizardPage(step) {
1165
+ return elements.issueWizardPages?.querySelector(`[data-issue-wizard-page="${step}"]`) || null;
1166
+ }
1167
+
1168
+ function issueWizardChoiceButton({ label, description = "", preview = "", selected, action, value, group }) {
1169
+ const button = make("button", "issue-wizard-choice");
1170
+ button.type = "button";
1171
+ button.dataset.issueWizardAction = action;
1172
+ button.dataset.issueWizardValue = value;
1173
+ button.dataset.issueWizardGroup = group;
1174
+ button.setAttribute("aria-pressed", selected ? "true" : "false");
1175
+ button.classList.toggle("selected", selected);
1176
+ button.append(make("strong", undefined, label));
1177
+ if (description) button.append(make("span", "issue-wizard-choice-description", description));
1178
+ if (preview) button.append(make("span", "issue-wizard-choice-preview", preview));
1179
+ return button;
1180
+ }
1181
+
1182
+ function focusIssueWizardChoice(action, value) {
1183
+ queueMicrotask(() => {
1184
+ const buttons = issueWizardPage(issueWizardState.step)?.querySelectorAll(`[data-issue-wizard-action="${action}"]`) || [];
1185
+ const target = Array.from(buttons).find((button) => button.dataset.issueWizardValue === value);
1186
+ target?.focus({ preventScroll: true });
1187
+ });
1188
+ }
1189
+
1190
+ function focusIssueWizardPage() {
1191
+ queueMicrotask(() => {
1192
+ const page = issueWizardPage(issueWizardState.step);
1193
+ const target = page?.querySelector('[aria-pressed="true"], button, select, textarea');
1194
+ target?.focus({ preventScroll: true });
1195
+ });
1196
+ }
1197
+
1198
+ function renderIssueWizardChoices(page, items, { selectedId, action, group, emptyMessage }) {
1199
+ const choices = make("div", "issue-wizard-choice-grid");
1200
+ choices.setAttribute("role", "group");
1201
+ choices.setAttribute("aria-label", group);
1202
+ if (!items.length) {
1203
+ choices.append(make("p", "issue-wizard-empty muted", emptyMessage));
1204
+ } else {
1205
+ for (const item of items) {
1206
+ const preview = action === "select-template" && item.fields?.length
1207
+ ? `Includes: ${item.fields.map((field) => field.label).join(" · ")}`
1208
+ : "";
1209
+ const button = issueWizardChoiceButton({ label: item.label, description: item.description, preview, selected: item.id === selectedId, action, value: item.id, group });
1210
+ button.addEventListener("click", () => {
1211
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: action, [`${action.split("-")[1]}Id`]: item.id }, issueWizardCatalog);
1212
+ renderIssueWizard();
1213
+ focusIssueWizardChoice(action, item.id);
1214
+ });
1215
+ choices.append(button);
1216
+ }
1217
+ }
1218
+ page.append(choices);
1219
+ }
1220
+
1221
+ function renderIssueWizardDetails(page) {
1222
+ const template = issueWizardCatalog.templates.find((item) => item.id === issueWizardState.templateId);
1223
+ if (!template) {
1224
+ page.append(make("p", "issue-wizard-empty muted", "Choose a compatible template before adding details."));
1225
+ return;
1226
+ }
1227
+ const summary = make("textarea", "issue-wizard-textarea");
1228
+ summary.id = "issueWizardSummary";
1229
+ summary.rows = 2;
1230
+ summary.maxLength = 160;
1231
+ summary.value = issueWizardState.summary;
1232
+ summary.placeholder = "Short summary";
1233
+ summary.setAttribute("aria-describedby", "issueWizardSummaryHint");
1234
+ summary.addEventListener("input", () => {
1235
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-summary", summary: summary.value }, issueWizardCatalog);
1236
+ renderIssueWizardNavigation();
1237
+ });
1238
+ const summaryLabel = make("label", "issue-wizard-field");
1239
+ summaryLabel.htmlFor = summary.id;
1240
+ summaryLabel.append(make("span", "issue-wizard-field-label", "Short summary"), summary, make("small", "muted", "Required. This completes the GitHub issue title."));
1241
+ summaryLabel.lastElementChild.id = "issueWizardSummaryHint";
1242
+ page.append(summaryLabel);
1243
+
1244
+ for (const field of template.fields) {
1245
+ const fieldWrap = make("div", "issue-wizard-field");
1246
+ const label = make("span", "issue-wizard-field-label", field.label);
1247
+ label.id = `issueWizardFieldLabel-${field.id}`;
1248
+ fieldWrap.append(label);
1249
+ if (field.kind === "textarea") {
1250
+ const input = make("textarea", "issue-wizard-textarea");
1251
+ input.rows = 4;
1252
+ input.value = issueWizardState.fields[field.id] || "";
1253
+ input.setAttribute("aria-labelledby", label.id);
1254
+ input.addEventListener("input", () => {
1255
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-field", fieldId: field.id, value: input.value }, issueWizardCatalog);
1256
+ renderIssueWizardNavigation();
1257
+ });
1258
+ fieldWrap.append(input);
1259
+ } else if (field.kind === "select") {
1260
+ const select = make("select", "issue-wizard-select");
1261
+ select.setAttribute("aria-labelledby", label.id);
1262
+ const placeholder = make("option", undefined, "Choose one…");
1263
+ placeholder.value = "";
1264
+ select.append(placeholder);
1265
+ for (const option of field.options || []) {
1266
+ const item = make("option", undefined, option.label);
1267
+ item.value = option.id;
1268
+ item.selected = issueWizardState.fields[field.id] === option.id;
1269
+ select.append(item);
1270
+ }
1271
+ select.addEventListener("change", () => {
1272
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-field", fieldId: field.id, value: select.value }, issueWizardCatalog);
1273
+ renderIssueWizardNavigation();
1274
+ });
1275
+ fieldWrap.append(select);
1276
+ } else {
1277
+ const choices = make("div", "issue-wizard-inline-choices");
1278
+ choices.setAttribute("role", "group");
1279
+ choices.setAttribute("aria-labelledby", label.id);
1280
+ for (const option of field.options || []) {
1281
+ const button = issueWizardChoiceButton({ label: option.label, selected: issueWizardState.fields[field.id] === option.id, action: "set-field", value: option.id, group: field.label });
1282
+ button.addEventListener("click", () => {
1283
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-field", fieldId: field.id, value: option.id }, issueWizardCatalog);
1284
+ renderIssueWizard();
1285
+ focusIssueWizardChoice("set-field", option.id);
1286
+ });
1287
+ choices.append(button);
1288
+ }
1289
+ fieldWrap.append(choices);
1290
+ }
1291
+ page.append(fieldWrap);
1292
+ }
1293
+ }
1294
+
1295
+ function renderIssueWizardReview(page) {
1296
+ let payload;
1297
+ try {
1298
+ payload = buildIssuePayload(issueWizardState, issueWizardCatalog);
1299
+ } catch {
1300
+ page.append(make("p", "issue-wizard-empty muted", "Complete the required details to preview the issue."));
1301
+ return;
1302
+ }
1303
+ const title = make("textarea", "issue-wizard-preview-title");
1304
+ title.readOnly = true;
1305
+ title.rows = 2;
1306
+ title.value = payload.title;
1307
+ title.setAttribute("aria-label", "GitHub issue title preview");
1308
+ const body = make("textarea", "issue-wizard-preview-body");
1309
+ body.readOnly = true;
1310
+ body.rows = 12;
1311
+ body.value = payload.body;
1312
+ body.setAttribute("aria-label", "GitHub issue Markdown body preview");
1313
+ const titleWrap = make("label", "issue-wizard-preview");
1314
+ titleWrap.append(make("span", "issue-wizard-field-label", "GitHub issue title"), title);
1315
+ const bodyWrap = make("label", "issue-wizard-preview");
1316
+ bodyWrap.append(make("span", "issue-wizard-field-label", "GitHub issue Markdown body"), body);
1317
+ page.append(titleWrap, bodyWrap);
1318
+ }
1319
+
1320
+ function issueBotMessage(result) {
1321
+ if (result?.phase === "admitting") return "Verifying bot protection and submitting the structured report…";
1322
+ switch (result?.status) {
1323
+ case "queued": return result.timedOut ? "The report is still queued. Refresh status when you are ready." : "The report is queued for automated checks…";
1324
+ case "checking": return result.timedOut ? "The report is still being checked. Refresh status when you are ready." : "The report is being checked…";
1325
+ case "created": return `GitHub issue #${result.issueNumber} was created.`;
1326
+ case "rejected": return "This report was not accepted for automated public issue creation. You can still copy it and create an issue manually.";
1327
+ case "review": return "This report needs manual review and was not published automatically. You can still copy it and create an issue manually.";
1328
+ case "unknown": return "The creation result is unknown; no further automatic issue creation will be attempted. You can copy the issue instead.";
1329
+ default: return "Automated submission is unavailable. You can still copy the complete issue.";
1330
+ }
1331
+ }
1332
+
1333
+ function renderIssueWizardSubmissionStatus() {
1334
+ const result = issueBotSubmissionResult;
1335
+ if (elements.issueWizardSubmissionStatus) elements.issueWizardSubmissionStatus.hidden = !result;
1336
+ if (elements.issueWizardSubmissionMessage) elements.issueWizardSubmissionMessage.textContent = result ? issueBotMessage(result) : "";
1337
+ const created = result?.status === "created" && typeof result.issueUrl === "string";
1338
+ if (elements.issueWizardSubmissionLink) {
1339
+ elements.issueWizardSubmissionLink.hidden = !created;
1340
+ elements.issueWizardSubmissionLink.href = created ? result.issueUrl : "";
1341
+ elements.issueWizardSubmissionLink.textContent = created ? "View confirmed GitHub issue" : "";
1342
+ }
1343
+ const showRefresh = !!result?.timedOut && !!issueBotSubmissionHandle;
1344
+ if (elements.issueWizardRefreshButton) {
1345
+ elements.issueWizardRefreshButton.hidden = !showRefresh;
1346
+ elements.issueWizardRefreshButton.disabled = issueBotRequestActive;
1347
+ }
1348
+ const sensitive = result?.reasonCode === "sensitive_content";
1349
+ const hasPrivateReportUrl = !!issueBotRuntimeConfig.privateSecurityReportUrl;
1350
+ if (elements.issueWizardSecurityGuidance) elements.issueWizardSecurityGuidance.hidden = !sensitive || !hasPrivateReportUrl;
1351
+ if (elements.issueWizardSecurityLink) {
1352
+ elements.issueWizardSecurityLink.hidden = !sensitive || !hasPrivateReportUrl;
1353
+ elements.issueWizardSecurityLink.href = sensitive && hasPrivateReportUrl ? issueBotRuntimeConfig.privateSecurityReportUrl : "";
1354
+ }
1355
+ }
1356
+
1357
+ function renderIssueWizardNavigation() {
1358
+ const step = issueWizardState.step;
1359
+ const botAvailable = !!issueBotClient?.available;
1360
+ if (elements.issueWizardProgress) elements.issueWizardProgress.textContent = `Step ${step} of 5`;
1361
+ if (elements.issueWizardBackButton) elements.issueWizardBackButton.disabled = step === 1 || issueBotRequestActive;
1362
+ if (elements.issueWizardContinueButton) {
1363
+ elements.issueWizardContinueButton.hidden = step === 5;
1364
+ elements.issueWizardContinueButton.disabled = issueBotRequestActive || !isIssueWizardStepValid(issueWizardState, issueWizardCatalog, step);
1365
+ elements.issueWizardContinueButton.textContent = step === 4 ? "Review issue" : "Continue";
1366
+ }
1367
+ if (elements.issueWizardCopyButton) elements.issueWizardCopyButton.hidden = step !== 5;
1368
+ if (elements.issueWizardBotButton) {
1369
+ elements.issueWizardBotButton.hidden = step !== 5;
1370
+ elements.issueWizardBotButton.disabled = !botAvailable || issueBotRequestActive;
1371
+ elements.issueWizardBotButton.textContent = issueBotRequestActive ? "Checking issue status…" : "Send";
1372
+ }
1373
+ if (elements.issueWizardBotHint) {
1374
+ elements.issueWizardBotHint.hidden = step !== 5;
1375
+ elements.issueWizardBotHint.textContent = botAvailable
1376
+ ? "The bot submits only the structured wizard state. Keep private security details out of public reports."
1377
+ : "Automated submission is not enabled. Copy the issue and create it manually instead.";
1378
+ }
1379
+ renderIssueWizardSubmissionStatus();
1380
+ setIssueWizardStatus(`Step ${step} of 5.`);
1381
+ }
1382
+
1383
+ function renderIssueWizard() {
1384
+ if (!issueWizardCatalog || !elements.issueWizardPages) return;
1385
+ for (let step = 1; step <= 5; step += 1) {
1386
+ const page = issueWizardPage(step);
1387
+ if (!page) continue;
1388
+ page.hidden = step !== issueWizardState.step;
1389
+ page.replaceChildren();
1390
+ }
1391
+ const page = issueWizardPage(issueWizardState.step);
1392
+ if (!page) return;
1393
+ if (issueWizardState.step === 1) {
1394
+ page.append(make("p", "issue-wizard-intro", "What kind of issue would you like to report?"));
1395
+ renderIssueWizardChoices(page, issueWizardCatalog.categories, { selectedId: issueWizardState.categoryId, action: "select-category", group: "Issue category", emptyMessage: "No categories are available." });
1396
+ } else if (issueWizardState.step === 2) {
1397
+ page.append(make("p", "issue-wizard-intro", "Which part of Pi Web UI is affected?"));
1398
+ renderIssueWizardChoices(page, issueWizardCatalog.components, { selectedId: issueWizardState.componentId, action: "select-component", group: "Affected component", emptyMessage: "No components are available." });
1399
+ } else if (issueWizardState.step === 3) {
1400
+ page.append(make("p", "issue-wizard-intro", "Choose the structured template that best matches this issue."));
1401
+ renderIssueWizardChoices(page, getCompatibleTemplates(issueWizardCatalog, issueWizardState.categoryId, issueWizardState.componentId), { selectedId: issueWizardState.templateId, action: "select-template", group: "Issue template", emptyMessage: "Choose a category and component first." });
1402
+ } else if (issueWizardState.step === 4) {
1403
+ page.append(make("p", "issue-wizard-intro", "Add the details needed for a clear, actionable issue."));
1404
+ renderIssueWizardDetails(page);
1405
+ } else {
1406
+ page.append(make("p", "issue-wizard-intro", "Review the exact GitHub title and Markdown body before copying or submitting."));
1407
+ renderIssueWizardReview(page);
1408
+ }
1409
+ renderIssueWizardNavigation();
1410
+ }
1411
+
1412
+ async function copyIssueWizardPayload() {
1413
+ try {
1414
+ const payload = buildIssuePayload(issueWizardState, issueWizardCatalog);
1415
+ await copyText(issueClipboardText(payload));
1416
+ setIssueWizardStatus("Complete issue copied. Paste it into a new GitHub issue.");
1417
+ } catch {
1418
+ setIssueWizardStatus("Could not copy the issue. Select the preview text and copy it manually.");
1419
+ }
1420
+ }
1421
+
1422
+ function structuredIssueWizardState() {
1423
+ return {
1424
+ categoryId: issueWizardState.categoryId,
1425
+ componentId: issueWizardState.componentId,
1426
+ templateId: issueWizardState.templateId,
1427
+ summary: issueWizardState.summary,
1428
+ fields: { ...issueWizardState.fields },
1429
+ };
1430
+ }
1431
+
1432
+ function reportIssueBotStatus(result) {
1433
+ issueBotSubmissionResult = result;
1434
+ renderIssueWizardSubmissionStatus();
1435
+ }
1436
+
1437
+ function clearIssueBotSubmission({ abort = false } = {}) {
1438
+ if (abort) issueBotAbortController?.abort();
1439
+ issueBotAbortController = null;
1440
+ issueBotSubmissionHandle = null;
1441
+ issueBotSubmissionResult = null;
1442
+ issueBotRequestActive = false;
1443
+ elements.issueWizardTurnstile?.replaceChildren();
1444
+ renderIssueWizardSubmissionStatus();
1445
+ }
1446
+
1447
+ async function sendIssueToGithubBot() {
1448
+ if (!issueBotClient?.available || issueBotRequestActive) return;
1449
+ try {
1450
+ // Preserve the existing canonical builder as the review/copy authority, but never send title/body to the gateway.
1451
+ buildIssuePayload(issueWizardState, issueWizardCatalog);
1452
+ } catch {
1453
+ setIssueWizardStatus("Complete the required wizard details before submitting.");
1454
+ return;
1455
+ }
1456
+ const controller = new AbortController();
1457
+ issueBotAbortController = controller;
1458
+ issueBotRequestActive = true;
1459
+ issueBotSubmissionHandle = null;
1460
+ reportIssueBotStatus(Object.freeze({ status: "checking", phase: "admitting" }));
1461
+ renderIssueWizardNavigation();
1462
+ try {
1463
+ const submission = await issueBotClient.submit({
1464
+ issue: structuredIssueWizardState(),
1465
+ signal: controller.signal,
1466
+ onStatus: reportIssueBotStatus,
1467
+ });
1468
+ if (controller.signal.aborted || issueBotAbortController !== controller) return;
1469
+ issueBotSubmissionHandle = submission.handle;
1470
+ reportIssueBotStatus(submission.result);
1471
+ } catch (error) {
1472
+ if (error?.name !== "AbortError" && issueBotAbortController === controller) {
1473
+ reportIssueBotStatus(Object.freeze({ ok: false, status: "unavailable", reasonCode: "unavailable" }));
1474
+ }
1475
+ } finally {
1476
+ if (issueBotAbortController !== controller) return;
1477
+ issueBotAbortController = null;
1478
+ issueBotRequestActive = false;
1479
+ renderIssueWizardNavigation();
1480
+ }
1481
+ }
1482
+
1483
+ async function refreshIssueBotStatus() {
1484
+ if (!issueBotSubmissionHandle || issueBotRequestActive) return;
1485
+ const controller = new AbortController();
1486
+ issueBotAbortController = controller;
1487
+ issueBotRequestActive = true;
1488
+ renderIssueWizardNavigation();
1489
+ try {
1490
+ const result = await issueBotSubmissionHandle.refresh({ signal: controller.signal, onStatus: reportIssueBotStatus });
1491
+ if (!controller.signal.aborted && issueBotAbortController === controller) reportIssueBotStatus(result);
1492
+ } catch (error) {
1493
+ if (error?.name !== "AbortError" && issueBotAbortController === controller) {
1494
+ reportIssueBotStatus(Object.freeze({ ok: false, status: "unavailable", reasonCode: "unavailable" }));
1495
+ }
1496
+ } finally {
1497
+ if (issueBotAbortController !== controller) return;
1498
+ issueBotAbortController = null;
1499
+ issueBotRequestActive = false;
1500
+ renderIssueWizardNavigation();
1501
+ }
1502
+ }
1503
+
1504
+ function initializeIssueWizard() {
1505
+ if (!elements.openIssueButton || !elements.issueWizardDialog) return;
1506
+ issueWizardCatalog = createIssueWizardCatalog(OPTIONAL_FEATURES.map((feature) => feature.label));
1507
+ issueBotClient = createIssueBotClient({ config: issueBotRuntimeConfig, turnstileContainer: elements.issueWizardTurnstile });
1508
+ elements.openIssueButton.addEventListener("click", () => {
1509
+ clearIssueBotSubmission({ abort: true });
1510
+ issueWizardState = createIssueWizardState();
1511
+ renderIssueWizard();
1512
+ if (!elements.issueWizardDialog.open) elements.issueWizardDialog.showModal();
1513
+ queueMicrotask(() => issueWizardPage(1)?.querySelector("button")?.focus({ preventScroll: true }));
1514
+ });
1515
+ elements.issueWizardCloseButton?.addEventListener("click", () => elements.issueWizardDialog.close());
1516
+ elements.issueWizardDialog.addEventListener("close", () => clearIssueBotSubmission({ abort: true }));
1517
+ elements.issueWizardBackButton?.addEventListener("click", () => {
1518
+ if (issueBotRequestActive) return;
1519
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "back" }, issueWizardCatalog);
1520
+ renderIssueWizard();
1521
+ focusIssueWizardPage();
1522
+ });
1523
+ elements.issueWizardContinueButton?.addEventListener("click", () => {
1524
+ if (issueBotRequestActive) return;
1525
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "next" }, issueWizardCatalog);
1526
+ renderIssueWizard();
1527
+ focusIssueWizardPage();
1528
+ });
1529
+ elements.issueWizardCopyButton?.addEventListener("click", () => copyIssueWizardPayload());
1530
+ elements.issueWizardBotButton?.addEventListener("click", () => sendIssueToGithubBot());
1531
+ elements.issueWizardRefreshButton?.addEventListener("click", () => refreshIssueBotStatus());
1532
+ }
1070
1533
  const OPTIONAL_FEATURE_SECTIONS = [
1071
1534
  {
1072
1535
  id: "composer-commands",
@@ -1162,6 +1625,9 @@ const optionalFeatureInstallStates = new Map();
1162
1625
  const optionalFeatureInstallProgressTimers = new Map();
1163
1626
  let optionalFeaturePackageStatusError = "";
1164
1627
  const gitFooterPayloadRefreshInFlightByTab = new Set();
1628
+ const gitFooterPayloadStateByTab = new Map();
1629
+ const gitFooterPayloadSettlementTimersByTab = new Map();
1630
+ const gitFooterPayloadRequestSerialByTab = new Map();
1165
1631
  const gitFooterSyncPushInFlightByTab = new Set();
1166
1632
  const gitFooterPiCalibrationInFlightByTab = new Set();
1167
1633
  let gitFooterVisibilityApplyInFlight = false;
@@ -1461,6 +1927,7 @@ function isInteractiveDropdownOpen() {
1461
1927
  || optionsMenuOpen
1462
1928
  || conversationVoiceMenuOpen
1463
1929
  || busyPromptBehaviorMenuOpen
1930
+ || followUpQueueOpen
1464
1931
  || newTabMenuOpen
1465
1932
  || isFooterPickerOpen()
1466
1933
  || elements.commandSuggest?.hidden === false
@@ -1954,7 +2421,9 @@ function setSubagentOpenMode(mode, { persist = true, announce = false } = {}) {
1954
2421
  subagentOpenMode = normalizeSubagentOpenMode(mode);
1955
2422
  if (persist) persistSubagentOpenMode(subagentOpenMode);
1956
2423
  renderSubagentOpenModeControl();
2424
+ const materializedTerminalViews = subagentOpenMode === "tab" && materializeRetainedSubagentTerminalViews();
1957
2425
  renderSubagents();
2426
+ if (materializedTerminalViews) renderTabs();
1958
2427
  if (announce) addEvent(`subagents now open in ${SUBAGENT_OPEN_MODE_LABELS[subagentOpenMode].toLowerCase()}`);
1959
2428
  }
1960
2429
 
@@ -2025,6 +2494,384 @@ function persistTerminalCustomGroups() {
2025
2494
  }
2026
2495
  }
2027
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
+
2028
2875
  function terminalCustomGroupByTabId() {
2029
2876
  const map = new Map();
2030
2877
  for (const [groupId, group] of terminalCustomGroups) {
@@ -2688,6 +3535,7 @@ function renderBusyPromptBehaviorTag() {
2688
3535
  }
2689
3536
 
2690
3537
  function setBusyPromptBehaviorMenuOpen(open, { focusCurrent = false } = {}) {
3538
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
2691
3539
  busyPromptBehaviorMenuOpen = !!open;
2692
3540
  elements.busyPromptBehaviorTag?.setAttribute("aria-expanded", busyPromptBehaviorMenuOpen ? "true" : "false");
2693
3541
  elements.busyPromptBehaviorTag?.classList.toggle("menu-open", busyPromptBehaviorMenuOpen);
@@ -2756,6 +3604,7 @@ async function refreshNativeSettings(tabContext = activeTabContext()) {
2756
3604
 
2757
3605
  function setComposerActionsOpen(open) {
2758
3606
  const shouldOpen = open && isMobileView();
3607
+ if (shouldOpen && followUpQueueOpen) setFollowUpQueueOpen(false);
2759
3608
  document.body.classList.toggle("composer-actions-open", shouldOpen);
2760
3609
  elements.composerActionsButton.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
2761
3610
  if (!shouldOpen) {
@@ -3642,9 +4491,12 @@ function triggerNativeDownload(download) {
3642
4491
  anchor.rel = "noopener";
3643
4492
  anchor.hidden = true;
3644
4493
  document.body.append(anchor);
3645
- anchor.click();
3646
- anchor.remove();
3647
- return true;
4494
+ try {
4495
+ anchor.click();
4496
+ return true;
4497
+ } finally {
4498
+ anchor.remove();
4499
+ }
3648
4500
  }
3649
4501
 
3650
4502
  function isStandalonePwaWindow() {
@@ -3692,9 +4544,12 @@ function openNativeDownloadInBrowser(download) {
3692
4544
  anchor.rel = "noopener";
3693
4545
  anchor.hidden = true;
3694
4546
  document.body.append(anchor);
3695
- anchor.click();
3696
- anchor.remove();
3697
- return true;
4547
+ try {
4548
+ anchor.click();
4549
+ return true;
4550
+ } finally {
4551
+ anchor.remove();
4552
+ }
3698
4553
  }
3699
4554
 
3700
4555
  function openNativeExportDownloadPrompt(download, serverPath = "") {
@@ -4511,17 +5366,18 @@ function isFileDrag(event) {
4511
5366
  }
4512
5367
 
4513
5368
  function handleComposerDragOver(event) {
4514
- if (!isFileDrag(event)) return;
5369
+ if (event.target?.closest?.("#followUpQueueOverlay") || !isFileDrag(event)) return;
4515
5370
  event.preventDefault();
4516
5371
  elements.composer.classList.add("drag-over");
4517
5372
  }
4518
5373
 
4519
5374
  function handleComposerDragLeave(event) {
5375
+ if (event.target?.closest?.("#followUpQueueOverlay")) return;
4520
5376
  if (!elements.composer.contains(event.relatedTarget)) elements.composer.classList.remove("drag-over");
4521
5377
  }
4522
5378
 
4523
5379
  function handleComposerDrop(event) {
4524
- if (!isFileDrag(event)) return;
5380
+ if (event.target?.closest?.("#followUpQueueOverlay") || !isFileDrag(event)) return;
4525
5381
  event.preventDefault();
4526
5382
  elements.composer.classList.remove("drag-over");
4527
5383
  addAttachmentFiles(event.dataTransfer?.files, "drop");
@@ -5330,6 +6186,7 @@ let conversationVoicePending = null;
5330
6186
  // panel (hover/focus-within still work on desktop via CSS), so it also works
5331
6187
  // on touch devices where :hover never fires.
5332
6188
  function setConversationVoiceMenuOpen(open) {
6189
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
5333
6190
  conversationVoiceMenuOpen = !!open;
5334
6191
  elements.conversationVoiceButton?.setAttribute("aria-expanded", conversationVoiceMenuOpen ? "true" : "false");
5335
6192
  elements.conversationVoiceButton?.classList.toggle("menu-open", conversationVoiceMenuOpen);
@@ -5932,6 +6789,7 @@ function setOptionalFeatureDisabled(featureId, disabled) {
5932
6789
  if (featureId === "gitFooterStatus") {
5933
6790
  statusEntries.delete(GIT_FOOTER_WEBUI_STATUS_KEY);
5934
6791
  clearGitFooterWebuiPayloadCache();
6792
+ for (const tabId of new Set([...gitFooterPayloadStateByTab.keys(), ...gitFooterPayloadSettlementTimersByTab.keys(), ...gitFooterPayloadRefreshInFlightByTab])) clearGitFooterPayloadState(tabId);
5935
6793
  }
5936
6794
  if (featureId === "btwCommand") {
5937
6795
  statusEntries.delete(BTW_WEBUI_STATUS_KEY);
@@ -7218,6 +8076,7 @@ function updateActiveFileViewerAfterMove(sourcePath = "", destinationPath = "")
7218
8076
  gitChanges: null,
7219
8077
  };
7220
8078
  if (fileViewerSelection) fileViewerSelection = { ...fileViewerSelection, path: nextPath, fileName: activeFileViewer.name };
8079
+ cacheActiveFileViewerForTab();
7221
8080
  updateFileViewerUi();
7222
8081
  }
7223
8082
 
@@ -7637,6 +8496,10 @@ function setFileViewerMode(mode = "source") {
7637
8496
  activeFileViewer.mode = resolveFileViewerMode({ ...activeFileViewer, mode });
7638
8497
  if (activeFileViewer.mode === "changes" && previousMode !== "changes") clearFileViewerSelection();
7639
8498
  updateFileViewerUi();
8499
+ if (elements.fileViewerSearchBar && !elements.fileViewerSearchBar.hidden) {
8500
+ fileViewerSearchIndex = -1;
8501
+ runFileViewerSearch({ navigate: true });
8502
+ }
7640
8503
  }
7641
8504
 
7642
8505
  function setFileViewerDirty(dirty) {
@@ -7652,7 +8515,10 @@ function updateFileViewerUi() {
7652
8515
  if (elements.fileViewerPane) elements.fileViewerPane.hidden = !open;
7653
8516
  requestAnimationFrame(syncResizablePanelWidthsForViewport);
7654
8517
  updateFileViewerResizeHandle();
7655
- if (!open) return;
8518
+ if (!open) {
8519
+ closeFileViewerSearch({ restoreFocus: false });
8520
+ return;
8521
+ }
7656
8522
  if (!isSidePanelOverlayView()) applyFileViewerWidth(currentFileViewerWidth());
7657
8523
  const viewer = activeFileViewer;
7658
8524
  const isMarkdown = viewer.language === "markdown";
@@ -7705,6 +8571,158 @@ function updateFileViewerUi() {
7705
8571
  elements.fileViewerOpenDefaultButton.disabled = viewer.readOnly === true || !viewerPath;
7706
8572
  }
7707
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 });
7708
8726
  }
7709
8727
 
7710
8728
  function fileViewerChangesNotice(text, level = "") {
@@ -7896,7 +8914,15 @@ async function sendFileSelectionToSession() {
7896
8914
  }
7897
8915
  }
7898
8916
 
7899
- 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() {
7900
8926
  fileViewerOpenRequestSerial += 1;
7901
8927
  activeFileViewer = null;
7902
8928
  clearFileViewerSelection();
@@ -7917,6 +8943,22 @@ function closeFileViewer() {
7917
8943
  setFileViewerStatus("");
7918
8944
  }
7919
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
+
7920
8962
  // Side-panel Git categories are UI labels; the read API uses its own allowlist.
7921
8963
  const GIT_FILE_DIFF_CATEGORY_BY_PANEL = Object.freeze({
7922
8964
  staged: "staged",
@@ -7961,10 +9003,10 @@ function gitFileChangesPlaceholder(category, repoRelPath, requestSerial) {
7961
9003
 
7962
9004
  async function applyGitFileChangesSnapshot(request, tabContext, viewerPath, requestSerial) {
7963
9005
  const snapshot = await request;
7964
- if (!isCurrentTabContext(tabContext)) return;
7965
- if (!activeFileViewer?.gitChanges?.loading || activeFileViewer.path !== viewerPath || activeFileViewer.gitChanges.requestSerial !== requestSerial) return;
7966
- activeFileViewer.gitChanges = snapshot;
7967
- 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();
7968
9010
  }
7969
9011
 
7970
9012
  async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } = {}) {
@@ -8000,6 +9042,7 @@ async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } =
8000
9042
  };
8001
9043
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
8002
9044
  clearFileViewerSelection();
9045
+ cacheActiveFileViewerForTab();
8003
9046
  updateFileViewerUi();
8004
9047
  setFileViewerStatus("Opened in WebUI.", "success");
8005
9048
  if (changesRequest) void applyGitFileChangesSnapshot(changesRequest, tabContext, activeFileViewer.path, changesRequestSerial);
@@ -8025,6 +9068,7 @@ async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } =
8025
9068
  };
8026
9069
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = "";
8027
9070
  clearFileViewerSelection();
9071
+ cacheActiveFileViewerForTab();
8028
9072
  updateFileViewerUi();
8029
9073
  setFileViewerStatus("File content unavailable; showing Git changes (read-only).", "warn");
8030
9074
  return;
@@ -8059,6 +9103,7 @@ async function openAurReviewReportInViewer(path = "", repoRoot = "") {
8059
9103
  };
8060
9104
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
8061
9105
  clearFileViewerSelection();
9106
+ cacheActiveFileViewerForTab();
8062
9107
  updateFileViewerUi();
8063
9108
  setFileViewerStatus("Report opened in WebUI (read-only).", "success");
8064
9109
  } catch (error) {
@@ -8084,6 +9129,7 @@ async function saveActiveFileViewer() {
8084
9129
  if (!isCurrentTabContext(tabContext)) return;
8085
9130
  const data = response.data || {};
8086
9131
  activeFileViewer = { ...activeFileViewer, ...data, path: normalizeFileTreePath(data.path || activeFileViewer.path), content, dirty: false };
9132
+ cacheActiveFileViewerForTab();
8087
9133
  updateFileViewerUi();
8088
9134
  await loadFileTreeDirectory(fileParentPath(activeFileViewer.path), { force: true });
8089
9135
  setFileViewerStatus("Saved.", "success");
@@ -8104,6 +9150,7 @@ function normalizeTabActivity(activity = {}) {
8104
9150
  ...activity,
8105
9151
  status,
8106
9152
  isWorking: status === "working",
9153
+ runStarted: activity.runStarted === true,
8107
9154
  completionSerial: Number.isFinite(completionSerial) ? completionSerial : 0,
8108
9155
  };
8109
9156
  }
@@ -8135,7 +9182,7 @@ function decrementTabPendingBlockerCount(tabId) {
8135
9182
  }
8136
9183
 
8137
9184
  function tabActivityStateChanged(previous, next) {
8138
- return !previous || previous.status !== next.status || previous.isWorking !== next.isWorking || previous.completionSerial !== next.completionSerial;
9185
+ return !previous || previous.status !== next.status || previous.isWorking !== next.isWorking || previous.runStarted !== next.runStarted || previous.completionSerial !== next.completionSerial;
8139
9186
  }
8140
9187
 
8141
9188
  function setTabActivity(tabId, activity = {}) {
@@ -8184,6 +9231,8 @@ function syncTabMetadata(nextTabs = []) {
8184
9231
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
8185
9232
  clearGitWorkflowForTab(tabId);
8186
9233
  commandCatalogsByTab.delete(tabId);
9234
+ clearGitFooterPayloadState(tabId);
9235
+ gitFooterPayloadRequestSerialByTab.delete(tabId);
8187
9236
  }
8188
9237
  }
8189
9238
  for (const tabId of tabMessagesCache.keys()) {
@@ -8277,12 +9326,20 @@ function syncTabPolling() {
8277
9326
  }
8278
9327
  }
8279
9328
 
8280
- function markTabWorkingLocally(tabId = activeTabId) {
9329
+ function markTabWorkingLocally(tabId = activeTabId, { runStarted = false } = {}) {
8281
9330
  const tab = tabs.find((item) => item.id === tabId);
8282
9331
  if (!tab) return false;
9332
+ suppressPendingAgentDoneNotificationsForTab(tabId);
8283
9333
  const previous = activityForTab(tab);
8284
9334
  const timestamp = new Date().toISOString();
8285
- const next = normalizeTabActivity({ ...previous, status: "working", isWorking: true, lastStartedAt: timestamp, lastChangedAt: timestamp });
9335
+ const next = normalizeTabActivity({
9336
+ ...previous,
9337
+ status: "working",
9338
+ isWorking: true,
9339
+ runStarted: previous.runStarted === true || runStarted === true,
9340
+ lastStartedAt: timestamp,
9341
+ lastChangedAt: timestamp,
9342
+ });
8286
9343
  tabActivities.set(tabId, next);
8287
9344
  if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
8288
9345
  return true;
@@ -8292,7 +9349,7 @@ function markTabIdleLocally(tabId = activeTabId) {
8292
9349
  const tab = tabs.find((item) => item.id === tabId);
8293
9350
  if (!tab) return false;
8294
9351
  const previous = activityForTab(tab);
8295
- const next = normalizeTabActivity({ ...previous, status: "idle", isWorking: false });
9352
+ const next = normalizeTabActivity({ ...previous, status: "idle", isWorking: false, runStarted: false });
8296
9353
  tabActivities.set(tabId, next);
8297
9354
  if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
8298
9355
  return true;
@@ -8303,10 +9360,12 @@ function markTabDoneLocally(tabId = activeTabId) {
8303
9360
  const tab = tabs.find((item) => item.id === tabId);
8304
9361
  if (!tab) return false;
8305
9362
  const previous = activityForTab(tab);
9363
+ if (!previous.runStarted) return markTabIdleLocally(tabId);
8306
9364
  const next = normalizeTabActivity({
8307
9365
  ...previous,
8308
9366
  status: "done",
8309
9367
  isWorking: false,
9368
+ runStarted: false,
8310
9369
  completionSerial: (Number(previous.completionSerial) || 0) + 1,
8311
9370
  lastCompletedAt: new Date().toISOString(),
8312
9371
  });
@@ -8333,7 +9392,9 @@ function syncActiveTabActivityFromState(state = currentState) {
8333
9392
  return false;
8334
9393
  }
8335
9394
  if (stateHasVisibleWork(state)) {
8336
- if (!activity.isWorking) return markTabWorkingLocally(tab.id);
9395
+ if (!activity.isWorking || (state.isStreaming && !activity.runStarted)) {
9396
+ return markTabWorkingLocally(tab.id, { runStarted: state.isStreaming === true });
9397
+ }
8337
9398
  return false;
8338
9399
  }
8339
9400
  if (activity.isWorking && !tabActivityRecentlyStarted(activity)) return markTabDoneLocally(tab.id);
@@ -8443,7 +9504,7 @@ function restoreActiveDraft() {
8443
9504
 
8444
9505
  function focusPromptInput({ defer = false } = {}) {
8445
9506
  const focus = () => {
8446
- if (activeSubagentTerminalId || !elements.promptInput || elements.dialog.open || elements.pathPickerDialog.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open || elements.nativeCommandDialog.open || elements.remoteQrDialog?.open || elements.appRunnerInfoDialog?.open || elements.gitFooterVisibilityDialog?.open || elements.statsOverlayDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
9507
+ if (activeSubagentTerminalId || !elements.promptInput || elements.dialog.open || elements.issueWizardDialog?.open || elements.pathPickerDialog.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open || elements.nativeCommandDialog.open || elements.remoteQrDialog?.open || elements.appRunnerInfoDialog?.open || elements.gitFooterVisibilityDialog?.open || elements.statsOverlayDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
8447
9508
  try {
8448
9509
  elements.promptInput.focus({ preventScroll: true });
8449
9510
  } catch {
@@ -8587,8 +9648,9 @@ function resetActiveTabUi() {
8587
9648
  latestWorkspace = null;
8588
9649
  latestMessages = [];
8589
9650
  latestMessagesSessionKey = "";
8590
- closeFileViewer();
9651
+ resetFileViewerUi();
8591
9652
  resetFileTreeState();
9653
+ restoreFileViewerForActiveTab();
8592
9654
  clearRunIndicatorActivity({ render: false });
8593
9655
  statusEntries.clear();
8594
9656
  restoreWidgetsForActiveTab();
@@ -9162,6 +10224,26 @@ function gitPanelHistoryDate(value) {
9162
10224
  return Number.isNaN(date.getTime()) ? String(value || "") : date.toLocaleString();
9163
10225
  }
9164
10226
 
10227
+ function gitPanelDataRenderSignature(data) {
10228
+ if (!data) return null;
10229
+ return {
10230
+ branch: data.branch || "",
10231
+ changes: Array.isArray(data.changes) ? data.changes : [],
10232
+ history: Array.isArray(data.history) ? data.history : [],
10233
+ };
10234
+ }
10235
+
10236
+ function updateGitPanelRepositoryMeta(cards = gitPanelRepositoryCards()) {
10237
+ const sections = [...elements.gitPanelGroups?.querySelectorAll(".git-side-panel-repository[data-git-root]") || []];
10238
+ for (const card of cards) {
10239
+ const snapshot = gitPanelSnapshot(card.root);
10240
+ if (!snapshot?.data) continue;
10241
+ const section = sections.find((candidate) => candidate.dataset.gitRoot === card.root);
10242
+ const status = section?.querySelector(".git-side-panel-repository-updated");
10243
+ if (status) status.textContent = snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(snapshot.data.generatedAt)}`;
10244
+ }
10245
+ }
10246
+
9165
10247
  function renderGitPanelHistory(card, data) {
9166
10248
  const wrapper = make("div", "git-side-panel-history");
9167
10249
  const history = Array.isArray(data?.history) ? data.history : [];
@@ -9233,7 +10315,7 @@ function renderGitPanelRepositoryContent(card, snapshot) {
9233
10315
  const meta = make("div", "git-side-panel-repository-meta");
9234
10316
  meta.append(
9235
10317
  make("strong", undefined, data.branch || "detached"),
9236
- make("span", undefined, snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(data.generatedAt)}`),
10318
+ make("span", "git-side-panel-repository-updated", snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(data.generatedAt)}`),
9237
10319
  );
9238
10320
  const changesPanel = renderGitPanelChanges(card, data);
9239
10321
  changesPanel.id = "git-side-panel-changes-panel";
@@ -9263,6 +10345,7 @@ function renderGitPanelRepositoryCard(card) {
9263
10345
  const snapshot = gitPanelSnapshot(card.root);
9264
10346
  const expanded = gitPanelState.expandedCardKey === card.key;
9265
10347
  const section = make("section", `git-side-panel-repository${expanded ? " expanded" : ""}`);
10348
+ section.dataset.gitRoot = card.root;
9266
10349
  const button = make("button", "git-side-panel-repository-toggle");
9267
10350
  button.type = "button";
9268
10351
  button.setAttribute("aria-expanded", expanded ? "true" : "false");
@@ -9309,12 +10392,13 @@ function renderGitPanel() {
9309
10392
  cards: cards.map((card) => {
9310
10393
  const snapshot = gitPanelSnapshot(card.root);
9311
10394
  const data = snapshot?.data;
9312
- return [card.key, card.root, card.cwd, card.tabId, snapshot?.loadedAt || 0, !!snapshot?.loading, snapshot?.error || "", gitPanelChangeCount(data), data?.history?.length || 0, data?.branch || "", data?.generatedAt || "", gitPanelState.activeViews.get(card.root) || "changes"];
10395
+ return [card.key, card.root, card.cwd, card.tabId, snapshot?.error || "", !data && !!snapshot?.loading, gitPanelDataRenderSignature(data), gitPanelState.activeViews.get(card.root) || "changes"];
9313
10396
  }),
9314
10397
  repositoryCount,
9315
10398
  discovering,
9316
10399
  });
9317
10400
  if (signature === gitPanelRenderSignature && elements.gitPanelGroups.childElementCount === cards.length) {
10401
+ updateGitPanelRepositoryMeta(cards);
9318
10402
  ensureGitPanelRepositoriesDiscovered();
9319
10403
  ensureGitPanelVisibleRepositoriesFresh(cards);
9320
10404
  return;
@@ -9358,10 +10442,6 @@ function terminalAppRunnerLabel(run) {
9358
10442
  return command && command !== "app runner" ? `app runner: ${command}` : "app runner running";
9359
10443
  }
9360
10444
 
9361
- function terminalAppRunnerTooltip(run) {
9362
- return appRunnerIsRunning(run) ? ` · ${terminalAppRunnerLabel(run)}` : "";
9363
- }
9364
-
9365
10445
  function tabConversationMode(tab) {
9366
10446
  if (!tab?.id) return normalizeConversationModeState(tab?.conversationMode || {});
9367
10447
  return normalizeConversationModeState(conversationModeByTab.get(tab.id) || tab.conversationMode || {});
@@ -9371,22 +10451,16 @@ function tabConversationModeActive(tab) {
9371
10451
  return tabConversationMode(tab).enabled === true;
9372
10452
  }
9373
10453
 
9374
- function terminalConversationModeTooltip(tab) {
9375
- const mode = tabConversationMode(tab);
9376
- return mode.enabled ? ` · natural conversation: ${mode.uiState || "listening"}` : "";
9377
- }
9378
-
9379
10454
  function tabWorkflowModeActive(tab) {
9380
10455
  return normalizeWorkflowModeState(workflowModeByTab.get(tab?.id) || {}).enabled === true;
9381
10456
  }
9382
10457
 
9383
- function terminalWorkflowTooltip(tab) {
9384
- const count = workflowRunningCountForTab(tab?.id);
9385
- return `${tabWorkflowModeActive(tab) ? " · workflow mode active" : ""}${count ? ` · ${count} workflow run${count === 1 ? "" : "s"} active` : ""}`;
10458
+ function terminalTabWorkspaceName(tab) {
10459
+ return tabGroupTitle(tab?.cwd, "workspace");
9386
10460
  }
9387
10461
 
9388
10462
  function terminalTabMeta(tab, indicator) {
9389
- const parts = [tab.running ? `${indicator.meta} · pid ${tab.pid || "…"}` : "stopped"];
10463
+ const parts = [tab.running ? `${indicator.meta} · ${terminalTabWorkspaceName(tab)}` : "stopped"];
9390
10464
  if (tabAppRunnerRunningRun(tab)) parts.push("app runner");
9391
10465
  if (tabConversationModeActive(tab)) parts.push("voice");
9392
10466
  if (tabWorkflowModeActive(tab)) parts.push("workflow mode");
@@ -9395,6 +10469,84 @@ function terminalTabMeta(tab, indicator) {
9395
10469
  return parts.join(" · ");
9396
10470
  }
9397
10471
 
10472
+ function terminalTabGitTooltip(tab) {
10473
+ const workspace = normalizeGitWorkspaceInfo(tab?.gitWorkspace);
10474
+ if (!workspace) return "";
10475
+ const checkout = workspace.worktreePath ? (workspace.isMainWorktree ? "main worktree" : "worktree") : "";
10476
+ return [workspace.branch || "detached", checkout].filter(Boolean).join(" · ");
10477
+ }
10478
+
10479
+ function terminalTabActiveTooltip(tab) {
10480
+ const active = [];
10481
+ const appRunnerRun = tabAppRunnerRunningRun(tab);
10482
+ if (appRunnerRun) active.push(terminalAppRunnerLabel(appRunnerRun));
10483
+ const conversationMode = tabConversationMode(tab);
10484
+ if (conversationMode.enabled) active.push(`voice: ${conversationMode.uiState || "listening"}`);
10485
+ const workflowCount = workflowRunningCountForTab(tab?.id);
10486
+ if (tabWorkflowModeActive(tab)) active.push(workflowCount ? `workflow: ${workflowCount} run${workflowCount === 1 ? "" : "s"}` : "workflow mode");
10487
+ else if (workflowCount) active.push(`workflow: ${workflowCount} run${workflowCount === 1 ? "" : "s"}`);
10488
+ return active.join(" · ");
10489
+ }
10490
+
10491
+ function terminalTabTooltip(tab) {
10492
+ const lines = [
10493
+ `${tab?.title || "Terminal tab"} · ${tabIndicator(tab).label}`,
10494
+ `Working folder: ${normalizeDisplayPath(tab?.cwd || "") || "Not set"}`,
10495
+ ];
10496
+ const git = terminalTabGitTooltip(tab);
10497
+ if (git) lines.push(`Git: ${git}`);
10498
+ const active = terminalTabActiveTooltip(tab);
10499
+ if (active) lines.push(`Active: ${active}`);
10500
+ lines.push("Click to switch · Drag to group");
10501
+ return lines.join("\n");
10502
+ }
10503
+
10504
+ function terminalTabGroupStatusTooltip(groupTabs = []) {
10505
+ const counts = { blocked: 0, working: 0, done: 0, idle: 0, stopped: 0 };
10506
+ for (const tab of groupTabs) {
10507
+ const state = tab?.running ? tabIndicator(tab).state : "stopped";
10508
+ counts[state] = (counts[state] || 0) + 1;
10509
+ }
10510
+ return ["blocked", "working", "done", "idle", "stopped"]
10511
+ .filter((state) => counts[state])
10512
+ .map((state) => `${counts[state]} ${state}`)
10513
+ .join(" · ");
10514
+ }
10515
+
10516
+ function terminalTabGroupWorkspaceTooltip(group) {
10517
+ const paths = [...new Set((group?.tabs || []).map((tab) => normalizeDisplayPath(tab?.cwd || "")).filter(Boolean))];
10518
+ if (!group?.custom || paths.length <= 1) return `Working folder: ${paths[0] || normalizeDisplayPath(group?.cwd || "") || "Not set"}`;
10519
+ const names = paths.map((path) => path.split("/").filter(Boolean).slice(-2).join("/") || path);
10520
+ const remainder = names.length - 2;
10521
+ return `Workspaces: ${names.slice(0, 2).join(", ")}${remainder > 0 ? ` +${remainder} more` : ""}`;
10522
+ }
10523
+
10524
+ function terminalTabGroupActiveTooltip(groupTabs = []) {
10525
+ const appRunners = groupTabs.filter(tabAppRunnerRunningRun).length;
10526
+ const voices = groupTabs.filter(tabConversationModeActive).length;
10527
+ const workflowTabs = groupTabs.filter(tabWorkflowModeActive).length;
10528
+ const workflowRuns = groupTabs.reduce((total, tab) => total + workflowRunningCountForTab(tab?.id), 0);
10529
+ return [
10530
+ appRunners ? `${appRunners} app runner${appRunners === 1 ? "" : "s"}` : "",
10531
+ voices ? `${voices} voice` : "",
10532
+ workflowTabs ? `${workflowTabs} workflow tab${workflowTabs === 1 ? "" : "s"}` : "",
10533
+ workflowRuns ? `${workflowRuns} workflow run${workflowRuns === 1 ? "" : "s"}` : "",
10534
+ ].filter(Boolean).join(" · ");
10535
+ }
10536
+
10537
+ function terminalTabGroupTooltip(group, groupTitle = terminalDisplayGroupTitle(group)) {
10538
+ const groupTabs = group?.tabs || [];
10539
+ const lines = [
10540
+ `${groupTitle} · ${groupTabs.length} tab${groupTabs.length === 1 ? "" : "s"}`,
10541
+ terminalTabGroupWorkspaceTooltip(group),
10542
+ `Status: ${terminalTabGroupStatusTooltip(groupTabs) || "No tabs"}`,
10543
+ ];
10544
+ const active = terminalTabGroupActiveTooltip(groupTabs);
10545
+ if (active) lines.push(`Active: ${active}`);
10546
+ lines.push("Click to switch · Drop tabs here to add");
10547
+ return lines.join("\n");
10548
+ }
10549
+
9398
10550
  function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false, workflowModeActive = false, workflowCount = 0, subagent = false }) {
9399
10551
  const titleRow = make("span", "terminal-tab-title-row");
9400
10552
  const indicatorDot = make("span", "terminal-tab-activity-indicator");
@@ -9426,8 +10578,7 @@ function renderTerminalTab(tab) {
9426
10578
  button.setAttribute("role", "tab");
9427
10579
  button.setAttribute("aria-selected", isActive ? "true" : "false");
9428
10580
  button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
9429
- const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)}${terminalConversationModeTooltip(tab)}${terminalWorkflowTooltip(tab)} · drag onto another tab or group to group`;
9430
- applyStyledTooltip(button, tooltip, { ariaLabel: false });
10581
+ applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace" });
9431
10582
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
9432
10583
  button.addEventListener("click", () => switchTab(tab.id));
9433
10584
  wrapper.append(button);
@@ -9466,8 +10617,7 @@ function renderTerminalTabGroupItem(tab, group) {
9466
10617
  button.setAttribute("role", "tab");
9467
10618
  button.setAttribute("aria-selected", isActive ? "true" : "false");
9468
10619
  button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
9469
- const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)}${terminalConversationModeTooltip(tab)}${terminalWorkflowTooltip(tab)} · drag onto another tab or group to group`;
9470
- applyStyledTooltip(button, tooltip, { ariaLabel: false });
10620
+ applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace" });
9471
10621
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
9472
10622
  button.addEventListener("click", (event) => {
9473
10623
  event.stopPropagation();
@@ -9510,7 +10660,6 @@ function renderTerminalTabGroup(group, groupCount = 1) {
9510
10660
  const workflowModeActive = groupTabs.some(tabWorkflowModeActive);
9511
10661
  const groupTitle = terminalDisplayGroupTitle(group, activeGroupTab?.title || "group");
9512
10662
  const activeTitle = activeGroupTab?.title || groupTitle;
9513
- const groupDetail = terminalDisplayGroupDetail(group, groupTitle);
9514
10663
  const wrapper = make("div", `terminal-tab terminal-tab-group${group.custom ? " terminal-tab-custom-group" : ""} activity-${indicator.state}${isActive ? " active" : ""}${isStopped ? " stopped" : ""}${appRunnerRun ? " app-runner-running" : ""}${workflowModeActive ? " workflow-mode-running" : ""}${workflowCount ? " workflow-run-running" : ""}`);
9515
10664
  wrapper.dataset.groupKey = group.key;
9516
10665
  if (group.customGroupId) wrapper.dataset.customGroupId = group.customGroupId;
@@ -9531,8 +10680,7 @@ function renderTerminalTabGroup(group, groupCount = 1) {
9531
10680
  button.setAttribute("aria-haspopup", "true");
9532
10681
  button.setAttribute("aria-expanded", group.key === openTerminalTabGroupKey ? "true" : "false");
9533
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}`);
9534
- const tooltip = `${activeTitle} · ${groupTitle} · ${groupDetail} · ${groupTabs.length} tabs · ${indicator.label}${appRunnerSummary ? ` · ${appRunnerSummary}` : ""}${workflowModeActive ? " · workflow mode active" : ""}${workflowCount ? ` · ${workflowCount} workflow runs active` : ""} · drop tabs here to add to group`;
9535
- applyStyledTooltip(button, tooltip, { ariaLabel: false });
10683
+ applyStyledTooltip(button, terminalTabGroupTooltip(group, groupTitle), { ariaLabel: false, description: true, placement: "right", variant: "workspace" });
9536
10684
  appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}${workflowModeActive ? " · workflow mode" : ""}${workflowCount ? ` · ${workflowCount} workflows` : ""}`, appRunnerRun, count: groupTabs.length, workflowModeActive, workflowCount });
9537
10685
  button.addEventListener("click", () => switchTab(activeGroupTab.id));
9538
10686
  wrapper.append(button);
@@ -9591,6 +10739,7 @@ function clearOpenTerminalTabGroup(groupKey, { force = false } = {}) {
9591
10739
  }
9592
10740
 
9593
10741
  function setNewTabMenuOpen(open) {
10742
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
9594
10743
  newTabMenuOpen = !!open;
9595
10744
  elements.newTabButton?.setAttribute("aria-expanded", newTabMenuOpen ? "true" : "false");
9596
10745
  elements.newTabButton?.classList.toggle("menu-open", newTabMenuOpen);
@@ -9669,6 +10818,13 @@ function renderTabs() {
9669
10818
  }
9670
10819
  elements.tabBar.append(elements.newTabMenu);
9671
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
+ }
9672
10828
  updateTerminalTabGroupOpenState();
9673
10829
  reconcileTerminalSplitState();
9674
10830
  setMobileTabsExpanded(mobileTabsExpanded);
@@ -9697,6 +10853,11 @@ async function refreshTabs({ selectStored = false } = {}) {
9697
10853
  setActiveTabId((requested && tabs.some((tab) => tab.id === requested) ? requested : stored && tabs.some((tab) => tab.id === stored) ? stored : tabs[0]?.id) || null, { remember: true });
9698
10854
  }
9699
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
+ }
9700
10861
  renderSessionSkillTags(activeTabId);
9701
10862
  renderTabs();
9702
10863
  return tabs;
@@ -9710,6 +10871,8 @@ async function switchTab(tabId) {
9710
10871
  }
9711
10872
  if (activeSubagentTerminalId) deactivateSubagentTerminalView({ render: false });
9712
10873
  clearOpenTerminalTabGroup(null, { force: true });
10874
+ setFollowUpQueueOpen(false);
10875
+ setFollowUpQueueStatus("");
9713
10876
  setMobileTabsExpanded(false);
9714
10877
  footerModelPickerOpen = false;
9715
10878
  footerThinkingPickerOpen = false;
@@ -9719,6 +10882,7 @@ async function switchTab(tabId) {
9719
10882
  saveActiveDraft();
9720
10883
  cacheMessagesForTab(activeTabId);
9721
10884
  cacheWidgetsForTab(activeTabId);
10885
+ cacheActiveFileViewerForTab(activeTabId);
9722
10886
  const tabContext = setActiveTabId(tabId, { remember: true });
9723
10887
  if (voiceConversation && voiceConversationTabId !== tabId) stopVoiceConversationLoop();
9724
10888
  resetActiveTabUi();
@@ -9922,7 +11086,7 @@ async function confirmCloseTerminalTabs(targetTabs, label) {
9922
11086
  });
9923
11087
  }
9924
11088
 
9925
- async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } = {}) {
11089
+ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", allowEmpty = false } = {}) {
9926
11090
  const targetIds = [...new Set(tabIds.filter(Boolean))];
9927
11091
  const targetTabs = targetIds.map((id) => tabs.find((item) => item.id === id)).filter(Boolean);
9928
11092
  if (!targetTabs.length) return;
@@ -9932,7 +11096,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
9932
11096
  const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
9933
11097
  try {
9934
11098
  if (closedActiveTab) eventSource?.close();
9935
- 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 });
9936
11100
  const closedIds = response.data?.closedIds || targetIds;
9937
11101
  tabs = response.data?.tabs || tabs.filter((item) => !closedIds.includes(item.id));
9938
11102
  syncTabMetadata(tabs);
@@ -9944,11 +11108,14 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
9944
11108
  commandCatalogsByTab.delete(id);
9945
11109
  appRunnerDataByTab.delete(id);
9946
11110
  tabMessagesCache.delete(id);
11111
+ fileViewersByTab.delete(id);
11112
+ fileViewerSelectionsByTab.delete(id);
9947
11113
  btwWidgetDismissedIdsByTab.delete(id);
9948
11114
  removeSubagentTerminalViewsForParent(id);
9949
11115
  }
9950
11116
  syncTerminalCustomGroupsWithTabs(tabs);
9951
11117
  clearOpenTerminalTabGroup(null, { force: true });
11118
+ if (!tabs.length) setWorkspaceDashboardCollapsed(false, { persist: false });
9952
11119
 
9953
11120
  const activeTabNeedsFallback = closedIds.includes(activeTabId) || !tabs.some((item) => item.id === activeTabId);
9954
11121
  if (activeTabNeedsFallback) {
@@ -9985,7 +11152,7 @@ async function closeTerminalTabGroup(group) {
9985
11152
  }
9986
11153
 
9987
11154
  async function closeAllTerminalTabs() {
9988
- 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 });
9989
11156
  }
9990
11157
 
9991
11158
  async function initializeTabs() {
@@ -9994,7 +11161,12 @@ async function initializeTabs() {
9994
11161
  renderTabs();
9995
11162
  restoreActiveDraft();
9996
11163
  if (!loadedTabs.length) {
9997
- 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();
9998
11170
  return;
9999
11171
  }
10000
11172
  focusPromptInput({ defer: true });
@@ -10297,7 +11469,8 @@ function queueAgentDoneBrowserNotification({ key, tabId, title, body }) {
10297
11469
  clearPendingAgentDoneNotification(key);
10298
11470
  const timer = setTimeout(() => {
10299
11471
  pendingAgentDoneNotificationTimers.delete(key);
10300
- if (isAutoRetryingTab(tabId)) return;
11472
+ const tab = tabs.find((item) => item.id === tabId);
11473
+ if (isAutoRetryingTab(tabId) || promptRoutingTabs.has(tabId) || activityForTab(tab).isWorking) return;
10301
11474
  showAgentDoneBrowserNotification({ tabId, title, body });
10302
11475
  }, AGENT_DONE_NOTIFICATION_RETRY_GRACE_MS);
10303
11476
  pendingAgentDoneNotificationTimers.set(key, { tabId, timer });
@@ -10808,6 +11981,8 @@ let footerTooltipPendingTarget = null;
10808
11981
  function ensureFooterTooltipNode() {
10809
11982
  if (!footerTooltipNode) {
10810
11983
  footerTooltipNode = make("div", "footer-floating-tooltip");
11984
+ footerTooltipNode.id = "footerFloatingTooltip";
11985
+ footerTooltipNode.setAttribute("role", "tooltip");
10811
11986
  footerTooltipNode.hidden = true;
10812
11987
  document.body.append(footerTooltipNode);
10813
11988
  }
@@ -10816,6 +11991,9 @@ function ensureFooterTooltipNode() {
10816
11991
  const update = () => positionFooterTooltip(footerTooltipTarget);
10817
11992
  window.addEventListener("resize", update, { passive: true });
10818
11993
  window.addEventListener("scroll", update, { passive: true, capture: true });
11994
+ document.addEventListener("keydown", (event) => {
11995
+ if (event.key === "Escape" && footerTooltipTarget) hideFooterTooltip(footerTooltipTarget);
11996
+ }, true);
10819
11997
  }
10820
11998
  return footerTooltipNode;
10821
11999
  }
@@ -10831,13 +12009,21 @@ function positionFooterTooltip(target) {
10831
12009
  const width = footerTooltipNode.offsetWidth;
10832
12010
  const height = footerTooltipNode.offsetHeight;
10833
12011
  const align = target.getAttribute("data-tooltip-align") || "center";
10834
- let left = rect.left + rect.width / 2 - width / 2;
10835
- if (align === "start") left = rect.left;
10836
- 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
+ }
10837
12026
  left = Math.min(Math.max(margin, left), Math.max(margin, window.innerWidth - margin - width));
10838
-
10839
- let top = rect.top - gap - height;
10840
- if (top < margin) top = rect.bottom + gap;
10841
12027
  top = Math.min(Math.max(margin, top), window.innerHeight - margin - height);
10842
12028
 
10843
12029
  footerTooltipNode.style.left = `${Math.round(left)}px`;
@@ -10857,6 +12043,9 @@ function showFooterTooltip(target) {
10857
12043
  if (!text) return;
10858
12044
  footerTooltipTarget = target;
10859
12045
  const tooltip = ensureFooterTooltipNode();
12046
+ const variant = target.getAttribute("data-tooltip-variant");
12047
+ if (variant) tooltip.dataset.variant = variant;
12048
+ else delete tooltip.dataset.variant;
10860
12049
  tooltip.textContent = text;
10861
12050
  tooltip.hidden = false;
10862
12051
  tooltip.classList.add("visible");
@@ -10883,6 +12072,7 @@ function hideFooterTooltip(target) {
10883
12072
  if (!footerTooltipNode) return;
10884
12073
  footerTooltipNode.hidden = true;
10885
12074
  footerTooltipNode.classList.remove("visible");
12075
+ delete footerTooltipNode.dataset.variant;
10886
12076
  }
10887
12077
 
10888
12078
  function bindStyledTooltipEvents(node) {
@@ -10890,10 +12080,15 @@ function bindStyledTooltipEvents(node) {
10890
12080
  node._styledTooltipBound = true;
10891
12081
  node.addEventListener("mouseenter", () => scheduleFooterTooltip(node));
10892
12082
  node.addEventListener("mouseleave", () => hideFooterTooltip(node));
10893
- node.addEventListener("focus", () => showFooterTooltip(node));
12083
+ node.addEventListener("focus", () => {
12084
+ if (node.getAttribute("data-tooltip-variant") === "workspace" && !node.matches(":focus-visible")) return;
12085
+ showFooterTooltip(node);
12086
+ });
10894
12087
  node.addEventListener("blur", () => hideFooterTooltip(node));
10895
12088
  }
10896
12089
 
12090
+ let styledTooltipDescriptionSerial = 0;
12091
+
10897
12092
  function applyStyledTooltip(node, tooltip, options = {}) {
10898
12093
  if (!node) return node;
10899
12094
  const text = cleanTooltipText(tooltip);
@@ -10904,7 +12099,16 @@ function applyStyledTooltip(node, tooltip, options = {}) {
10904
12099
  const ariaLabel = typeof options.ariaLabel === "string" ? options.ariaLabel : text.replace(/\s+/g, " ");
10905
12100
  node.setAttribute("aria-label", ariaLabel);
10906
12101
  }
12102
+ if (options.description === true) {
12103
+ const description = make("span", "sr-only styled-tooltip-description", text);
12104
+ description.id = `styledTooltipDescription${++styledTooltipDescriptionSerial}`;
12105
+ node.append(description);
12106
+ const describedBy = [node.getAttribute("aria-describedby"), description.id].filter(Boolean).join(" ");
12107
+ node.setAttribute("aria-describedby", describedBy);
12108
+ }
10907
12109
  if (options.align) node.setAttribute("data-tooltip-align", options.align);
12110
+ if (options.placement) node.setAttribute("data-tooltip-placement", options.placement);
12111
+ if (options.variant) node.setAttribute("data-tooltip-variant", options.variant);
10908
12112
  if (options.floating !== false) bindStyledTooltipEvents(node);
10909
12113
  return node;
10910
12114
  }
@@ -13682,10 +14886,13 @@ function gitFooterFallbackMessage() {
13682
14886
  const tabContext = activeTabContext();
13683
14887
  const commandsStillLoading = availableCommands.length === 0 && rawAvailableCommands.length === 0;
13684
14888
  const footerRefreshPending = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
14889
+ const payloadState = tabContext.tabId ? gitFooterPayloadStateByTab.get(tabContext.tabId) : null;
13685
14890
  const extensionDetected = hasAvailableCommand("git-footer-refresh") || optionalFeatureAvailability.gitFooterStatus;
13686
- return commandsStillLoading || footerRefreshPending || extensionDetected
13687
- ? "Loading git footer status…"
13688
- : "Git footer status extension unavailable";
14891
+ if (commandsStillLoading || footerRefreshPending || payloadState?.phase === "waiting") return "Loading git footer status…";
14892
+ if (payloadState?.phase === "failed") return payloadState.error || "Git footer status was not received — refresh to retry";
14893
+ if (payloadState?.phase === "idle") return "Git footer status unavailable — refresh to retry";
14894
+ if (extensionDetected) return "Loading git footer status…";
14895
+ return "Git footer status extension unavailable";
13689
14896
  }
13690
14897
 
13691
14898
  function renderMinimalFooter() {
@@ -13963,6 +15170,9 @@ function renderWorkspaceDashboard() {
13963
15170
  activeTabId,
13964
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) : "" })),
13965
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,
13966
15176
  });
13967
15177
  if (signature === workspaceDashboardSignature && root.childElementCount > 0) return;
13968
15178
  workspaceDashboardSignature = signature;
@@ -14001,11 +15211,16 @@ function renderWorkspaceDashboard() {
14001
15211
  actions.append(
14002
15212
  dashboardAction("Command palette", () => openCommandPalette(), "primary"),
14003
15213
  dashboardAction("New tab", () => createTerminalTab()),
14004
- dashboardAction("Branch worktree", () => openBranchWorktreePicker(), "worktree"),
14005
- dashboardAction("Resume", () => runNativeCommandMenu("/resume")),
14006
- dashboardAction("Model", () => runNativeCommandMenu("/model")),
14007
- dashboardAction("Settings", () => runNativeCommandMenu("/settings")),
14008
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
+ }
14009
15224
  header.append(title, actions);
14010
15225
 
14011
15226
  const metrics = make("div", "workspace-dashboard-metrics");
@@ -14052,7 +15267,70 @@ function renderWorkspaceDashboard() {
14052
15267
  if (tabs.length > 8) tabList.append(make("span", "workspace-dashboard-tab-more", `+${tabs.length - 8} more`));
14053
15268
  tabsPanel.append(tabList);
14054
15269
 
15270
+ const savedWorkspacePanel = !tabs.length ? renderSavedWorkspacePicker() : null;
14055
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;
14056
15334
  }
14057
15335
 
14058
15336
  function setFooterModelPickerOpen(open) {
@@ -15398,7 +16676,12 @@ function closePathPicker(cwd) {
15398
16676
  }
15399
16677
 
15400
16678
  function pickCwd(tab, initialCwd, { title } = {}) {
15401
- if (pathPickerState) return Promise.resolve(null);
16679
+ if (pathPickerState) {
16680
+ addEvent("working-directory picker is already open", "warn");
16681
+ elements.pathPickerDialog.focus();
16682
+ elements.pathPickerSearchInput.focus({ preventScroll: true });
16683
+ return Promise.resolve(null);
16684
+ }
15402
16685
 
15403
16686
  return new Promise((resolve) => {
15404
16687
  const pickerTab = tab || { id: "path-picker", title: "tab" };
@@ -15439,27 +16722,47 @@ async function changeActiveTabCwd() {
15439
16722
  if (!(await appConfirmText(`Restart ${tab.title} in:\n${cwd}\n\nCurrent in-flight work in this tab will be stopped. The conversation continues in the new directory.`, { affected: tab.title, confirmLabel: "Change working folder" }))) return;
15440
16723
 
15441
16724
  saveActiveDraft();
16725
+ if (isCurrentTabContext(tabContext)) {
16726
+ addTransientMessage({
16727
+ role: "native",
16728
+ title: "Changing working folder…",
16729
+ content: `Restarting ${tab.title} in ${cwd}. This can take a few seconds.`,
16730
+ level: "info",
16731
+ });
16732
+ }
16733
+ let response;
15442
16734
  try {
15443
- const response = await api(`/api/tabs/${encodeURIComponent(tab.id)}`, { method: "PATCH", body: { cwd }, scoped: false });
15444
- tabs = response.data?.tabs || tabs;
15445
- syncTabMetadata(tabs);
15446
- if (!isCurrentTabContext(tabContext)) {
15447
- renderTabs();
15448
- return;
15449
- }
15450
- const nextContext = setActiveTabId(response.data?.tab?.id || activeTabId);
15451
- resetGitWorkflowForTab(nextContext.tabId);
15452
- resetActiveTabUi();
16735
+ response = await api(`/api/tabs/${encodeURIComponent(tab.id)}`, { method: "PATCH", body: { cwd }, scoped: false });
16736
+ } catch (error) {
16737
+ const message = `Could not change ${tab.title} to ${cwd}. The existing working folder was kept.\n\n${error.message || String(error)}`;
16738
+ if (isCurrentTabContext(tabContext)) surfaceRuntimeDiagnostic("Working folder change failed", message);
16739
+ else addEvent(`working folder change failed for ${tab.title}: ${error.message || String(error)}`, "error");
16740
+ return;
16741
+ }
16742
+
16743
+ tabs = response.data?.tabs || tabs;
16744
+ syncTabMetadata(tabs);
16745
+ const changedTabId = response.data?.tab?.id || tab.id;
16746
+ const changedCwd = response.data?.tab?.cwd || cwd;
16747
+ resetGitWorkflowForTab(changedTabId);
16748
+ clearGitFooterPayloadState(changedTabId);
16749
+ if (!isCurrentTabContext(tabContext)) {
15453
16750
  renderTabs();
15454
- restoreActiveDraft();
15455
- connectEvents(nextContext);
15456
- await refreshAll(nextContext);
15457
- if (!isCurrentTabContext(nextContext)) return;
15458
- const changedCwd = response.data?.tab?.cwd || cwd;
15459
16751
  addEvent(response.data?.changed === false ? `cwd unchanged: ${changedCwd}` : `changed ${tab.title} cwd to ${changedCwd}`, "info");
15460
- } catch (error) {
15461
- if (isCurrentTabContext(tabContext)) addEvent(error.message, "error");
16752
+ return;
15462
16753
  }
16754
+
16755
+ if (response.data?.changed !== false) closeFileViewer();
16756
+ const nextContext = setActiveTabId(response.data?.tab?.id || activeTabId);
16757
+ resetActiveTabUi();
16758
+ renderTabs();
16759
+ restoreActiveDraft();
16760
+ connectEvents(nextContext);
16761
+ await refreshAll(nextContext);
16762
+ if (!isCurrentTabContext(nextContext)) return;
16763
+ const successMessage = response.data?.changed === false ? `cwd unchanged: ${changedCwd}` : `changed ${tab.title} cwd to ${changedCwd}`;
16764
+ addEvent(successMessage, "info");
16765
+ if (response.data?.changed !== false) addTransientMessage({ role: "native", title: "Working folder changed", content: `${tab.title} restarted in ${changedCwd}.`, level: "info" });
15463
16766
  }
15464
16767
 
15465
16768
  function renderFooter() {
@@ -15834,7 +17137,7 @@ function subagentTabsWithRunningAgents() {
15834
17137
  const gates = visibleSubagentGates(tab, dismissedSubagentGateKeys, now);
15835
17138
  return { ...tab, gates, gateCount: gates.length };
15836
17139
  })
15837
- .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)
15838
17141
  .sort((a, b) => Number(a.tabIndex || 0) - Number(b.tabIndex || 0) || String(a.tabTitle || "").localeCompare(String(b.tabTitle || "")));
15839
17142
  }
15840
17143
 
@@ -15868,6 +17171,116 @@ function subagentExecutionFacts(agent = {}) {
15868
17171
  return [`model ${model || "unknown"}`, `reasoning ${thinking || "unknown"}`];
15869
17172
  }
15870
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
+
15871
17284
  function subagentOverlayTranscriptMessages(data = subagentOverlayData) {
15872
17285
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
15873
17286
  return (Array.isArray(agent.transcript) ? agent.transcript : [])
@@ -15996,10 +17409,11 @@ function appendSubagentOverlayTranscript(parent, messages) {
15996
17409
 
15997
17410
  function subagentOverlayStateFacts(data = subagentOverlayData) {
15998
17411
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
17412
+ const run = subagentOverlaySelection?.run || {};
15999
17413
  return [
16000
- agent.status || "running",
16001
- data?.mode || subagentOverlaySelection?.run?.mode,
16002
- 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),
16003
17417
  agent.nested ? "nested" : "",
16004
17418
  ...subagentExecutionFacts(agent),
16005
17419
  agent.currentTool ? `tool ${agent.currentTool}` : "",
@@ -16055,7 +17469,7 @@ function renderSubagentOverlayWidget() {
16055
17469
  const data = subagentOverlayData;
16056
17470
  const agent = data?.agent || selection.agent || {};
16057
17471
  const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
16058
- const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
17472
+ const running = !selection.finished && subagentRunIsRunning(selection.run, agent);
16059
17473
  const transcriptMessages = subagentOverlayTranscriptMessages(data);
16060
17474
  const hasStructuredTranscript = transcriptMessages.length > 0;
16061
17475
  const outputText = subagentOverlayOutputText(data);
@@ -16100,6 +17514,9 @@ function renderSubagentOverlayWidget() {
16100
17514
  refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
16101
17515
  }, "subagent-overlay-refresh-action");
16102
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
+ }
16103
17520
  actions.append(copyButton, refreshButton, appRunnerActionButton("Close", closeSubagentOverlay, "subagent-overlay-close-action"));
16104
17521
  const details = [
16105
17522
  `${tab?.title || `Terminal ${selection.tabIndex || "?"}`} · run ${selection.runId}`,
@@ -16117,7 +17534,8 @@ function renderSubagentOverlayWidget() {
16117
17534
 
16118
17535
  function scheduleSubagentOverlayRefresh(delay = SUBAGENT_OVERLAY_REFRESH_MS) {
16119
17536
  clearTimeout(subagentOverlayRefreshTimer);
16120
- if (!subagentOverlaySelection || subagentOverlaySelection.finished) return;
17537
+ const agent = subagentOverlayData?.agent || subagentOverlaySelection?.agent || null;
17538
+ if (!subagentOverlaySelection || subagentOverlaySelection.finished || !subagentRunIsRunning(subagentOverlaySelection.run, agent)) return;
16121
17539
  subagentOverlayRefreshTimer = setTimeout(() => {
16122
17540
  refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
16123
17541
  }, delay);
@@ -16213,8 +17631,8 @@ function subagentTerminalViewTitle(view) {
16213
17631
  }
16214
17632
 
16215
17633
  function subagentTerminalViewIsRunning(view) {
16216
- const status = view?.data?.agent?.status || view?.agent?.status || "running";
16217
- 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);
16218
17636
  }
16219
17637
 
16220
17638
  function subagentTerminalViewMeaningfulSignature(view) {
@@ -16225,7 +17643,7 @@ function subagentTerminalViewMeaningfulSignature(view) {
16225
17643
  function updateSubagentTerminalRefreshState(view, { running = subagentTerminalViewIsRunning(view) } = {}) {
16226
17644
  if (!view || view.id !== activeSubagentTerminalId) return;
16227
17645
  const status = [
16228
- 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",
16229
17647
  view.error,
16230
17648
  ].filter(Boolean).join(" · ");
16231
17649
  elements.subagentTerminalStatus.setAttribute("aria-live", view.error ? "polite" : "off");
@@ -16251,7 +17669,7 @@ function renderSubagentTerminalView() {
16251
17669
  const fallbackText = outputText || (running && agent.currentTool ? "" : running ? "Waiting for the first agent activity…" : "No recent output was captured.");
16252
17670
  const parent = tabs.find((tab) => tab.id === view.parentTabId);
16253
17671
  const facts = [
16254
- view.finished ? "finished" : running ? "running" : agent.status || "finished",
17672
+ view.finished ? "finished" : running ? "running" : subagentRunStateLabel(view.run),
16255
17673
  view.run?.mode,
16256
17674
  subagentSourceLabel(view.data?.source || view.run?.source),
16257
17675
  agent.nested ? "nested" : "",
@@ -16281,13 +17699,18 @@ function renderSubagentTerminalView() {
16281
17699
 
16282
17700
  updateSubagentTerminalRefreshState(view, { running });
16283
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
+ }
16284
17707
  if (shouldFollowOutput) requestAnimationFrame(() => { elements.subagentTerminalTranscript.scrollTop = elements.subagentTerminalTranscript.scrollHeight; });
16285
17708
  }
16286
17709
 
16287
17710
  function scheduleSubagentTerminalRefresh(delay = SUBAGENT_OVERLAY_REFRESH_MS) {
16288
17711
  clearTimeout(subagentTerminalRefreshTimer);
16289
17712
  const view = activeSubagentTerminalView();
16290
- if (!view || view.finished) return;
17713
+ if (!view || view.finished || !subagentTerminalViewIsRunning(view)) return;
16291
17714
  subagentTerminalRefreshTimer = setTimeout(() => {
16292
17715
  refreshSubagentTerminalView(view.id).finally(() => scheduleSubagentTerminalRefresh());
16293
17716
  }, delay);
@@ -16354,8 +17777,8 @@ async function activateSubagentTerminalView(viewId) {
16354
17777
  scheduleSubagentTerminalRefresh();
16355
17778
  }
16356
17779
 
16357
- async function openSubagentTerminal(tab, run, agent) {
16358
- if (!tab?.tabId || !run?.id || !agent?.id) return;
17780
+ function ensureSubagentTerminalView(tab, run, agent) {
17781
+ if (!tab?.tabId || !run?.id || !agent?.id) return null;
16359
17782
  const id = subagentTerminalViewId(tab, run, agent);
16360
17783
  const existing = subagentTerminalViews.get(id);
16361
17784
  if (existing) {
@@ -16363,27 +17786,34 @@ async function openSubagentTerminal(tab, run, agent) {
16363
17786
  existing.run = run;
16364
17787
  existing.agent = agent;
16365
17788
  existing.parentTitle = tab.tabTitle;
16366
- } else {
16367
- subagentTerminalViews.set(id, {
16368
- id,
16369
- parentTabId: tab.tabId,
16370
- parentTitle: tab.tabTitle,
16371
- tabIndex: tab.tabIndex,
16372
- tab,
16373
- run,
16374
- agent,
16375
- runId: run.id,
16376
- agentId: agent.id,
16377
- data: null,
16378
- error: "",
16379
- loading: false,
16380
- finished: false,
16381
- requestSerial: 0,
16382
- openedAt: Date.now(),
16383
- });
17789
+ return existing;
16384
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;
16385
17815
  try {
16386
- await activateSubagentTerminalView(id);
17816
+ await activateSubagentTerminalView(view.id);
16387
17817
  } catch (error) {
16388
17818
  addEvent(`could not open subagent terminal: ${error.message || String(error)}`, "error");
16389
17819
  }
@@ -16415,6 +17845,9 @@ async function copySubagentTerminalOutput() {
16415
17845
  }
16416
17846
 
16417
17847
  function removeSubagentTerminalViewsForParent(parentTabId) {
17848
+ for (const key of subagentTerminalRestoredParentTabs) {
17849
+ if (key.startsWith(`${parentTabId}\u0000`)) subagentTerminalRestoredParentTabs.delete(key);
17850
+ }
16418
17851
  for (const [viewId, view] of subagentTerminalViews) {
16419
17852
  if (view.parentTabId !== parentTabId) continue;
16420
17853
  view.requestSerial += 1;
@@ -16424,17 +17857,64 @@ function removeSubagentTerminalViewsForParent(parentTabId) {
16424
17857
  }
16425
17858
 
16426
17859
  function syncSubagentTerminalViewsFromOverview() {
17860
+ let changed = false;
17861
+ const overviewTabs = Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : [];
16427
17862
  for (const view of subagentTerminalViews.values()) {
16428
- const tab = (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : []).find((candidate) => candidate.tabId === view.parentTabId);
17863
+ const tab = overviewTabs.find((candidate) => candidate.tabId === view.parentTabId);
16429
17864
  const run = (Array.isArray(tab?.runs) ? tab.runs : []).find((candidate) => candidate.id === view.runId);
16430
17865
  const agent = (Array.isArray(run?.agents) ? run.agents : []).find((candidate) => candidate.id === view.agentId);
16431
17866
  if (tab) {
16432
17867
  view.tab = tab;
16433
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;
16434
17879
  }
16435
- if (run) view.run = run;
16436
- if (agent) view.agent = agent;
16437
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
+ }
17915
+ }
17916
+ }
17917
+ return materialized;
16438
17918
  }
16439
17919
 
16440
17920
  function renderSubagentTerminalTab(view) {
@@ -16471,9 +17951,10 @@ function openSubagentOutput(tab, run, agent) {
16471
17951
  }
16472
17952
 
16473
17953
  function renderSubagentAgent(tab, run, agent) {
16474
- 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"}`);
16475
17956
  row.type = "button";
16476
- const dot = make("span", "subagent-running-dot");
17957
+ const dot = make("span", running ? "subagent-running-dot" : `subagent-state-dot ${agent?.status || "done"}`);
16477
17958
  dot.setAttribute("aria-hidden", "true");
16478
17959
  const content = make("div", "subagent-agent-content");
16479
17960
  content.append(make("strong", "subagent-agent-name", agent?.name || "subagent"));
@@ -16484,17 +17965,55 @@ function renderSubagentAgent(tab, run, agent) {
16484
17965
  subagentSourceLabel(run?.source),
16485
17966
  ...subagentExecutionFacts(agent),
16486
17967
  agent?.currentTool ? `tool: ${agent.currentTool}` : "",
16487
- elapsed ? `running ${elapsed}` : "",
17968
+ running && elapsed ? `running ${elapsed}` : agent?.status || subagentRunStateLabel(run),
16488
17969
  ].filter(Boolean);
16489
17970
  content.append(make("span", "subagent-agent-meta", facts.join(" · ")));
16490
17971
  row.append(dot, content);
16491
- const destination = subagentOpenMode === "tab" ? "subagent tab" : "live output overlay";
17972
+ const destination = subagentOpenMode === "tab" ? "subagent tab" : "output overlay";
16492
17973
  row.title = `${agent?.name || "subagent"} · ${facts.join(" · ")} · run ${run?.id || "unknown"} · open ${destination}`;
16493
17974
  row.setAttribute("aria-label", `Open ${destination} for ${agent?.name || "subagent"} in ${tab?.tabTitle || `Terminal ${tab?.tabIndex || "?"}`}`);
16494
17975
  row.addEventListener("click", () => openSubagentOutput(tab, run, agent));
16495
17976
  return row;
16496
17977
  }
16497
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
+
16498
18017
  function subagentGateStatusLabel(status) {
16499
18018
  return status === "satisfied" ? "satisfied" : status === "running" ? "running" : status === "cancelled" ? "cancelled" : "failed";
16500
18019
  }
@@ -16566,21 +18085,22 @@ function renderSubagentTabGroup(tab) {
16566
18085
  make("strong", undefined, tab.tabTitle || `Terminal ${tab.tabIndex || "?"}`),
16567
18086
  make("span", "subagent-tab-session", `Terminal ${tab.tabIndex || "?"} · ${subagentTabMeta(tab)}`),
16568
18087
  );
16569
- 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(" · ");
16570
18098
  header.append(title, make("span", "subagent-tab-count", countLabel));
16571
18099
  header.addEventListener("click", () => switchTab(tab.tabId));
16572
18100
  group.append(header);
16573
18101
 
16574
18102
  const list = make("div", "subagent-agent-list");
16575
- const runs = (Array.isArray(tab.runs) ? tab.runs : [])
16576
- .slice()
16577
- .sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0) || String(a.id || "").localeCompare(String(b.id || "")));
16578
- for (const run of runs) {
16579
- const agents = (Array.isArray(run.agents) ? run.agents : [])
16580
- .filter((agent) => agent?.status === "running")
16581
- .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
16582
- for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
16583
- }
18103
+ for (const run of runs) list.append(renderSubagentRun(tab, run));
16584
18104
  for (const gate of (Array.isArray(tab.gates) ? tab.gates : []).slice().sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0))) {
16585
18105
  list.append(renderSubagentGate(tab, gate));
16586
18106
  }
@@ -16592,26 +18112,29 @@ function renderSubagents() {
16592
18112
  const box = elements.subagentsBox;
16593
18113
  if (!box) return;
16594
18114
  const activeTabs = subagentTabsWithRunningAgents();
16595
- 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);
16596
18119
  const totalGates = activeTabs.reduce((count, tab) => count + Number(tab.gateCount || 0), 0);
16597
- const totalItems = totalAgents + totalGates;
18120
+ const hasItems = activeTabs.length > 0;
16598
18121
  if (elements.subagentCountBadge) {
16599
- elements.subagentCountBadge.textContent = String(totalItems);
16600
- elements.subagentCountBadge.hidden = totalItems === 0;
18122
+ elements.subagentCountBadge.textContent = String(totalAgents);
18123
+ elements.subagentCountBadge.hidden = totalAgents === 0;
16601
18124
  }
16602
18125
  if (elements.subagentsStatus) {
16603
- elements.subagentsStatus.textContent = totalItems > 0
16604
- ? [`${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(" · ")
16605
18128
  : subagentsLoading && !latestSubagents
16606
18129
  ? "Checking subagents and retry gates…"
16607
- : "No running subagents or retained retry gates.";
18130
+ : "No running subagents, retained runs, or retry gates.";
16608
18131
  }
16609
18132
 
16610
18133
  box.replaceChildren();
16611
- box.classList.toggle("muted", totalItems === 0);
16612
- box.classList.toggle("has-items", totalItems > 0);
16613
- if (totalItems === 0) {
16614
- 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."));
16615
18138
  return;
16616
18139
  }
16617
18140
  for (const tab of activeTabs) box.append(renderSubagentTabGroup(tab));
@@ -16620,25 +18143,34 @@ function renderSubagents() {
16620
18143
 
16621
18144
  async function refreshSubagents() {
16622
18145
  if (subagentsLoading) return;
18146
+ let subagentViewsChanged = false;
18147
+ let materializedTerminalViews = false;
16623
18148
  subagentsLoading = true;
16624
18149
  renderSubagents();
16625
18150
  try {
16626
18151
  const response = await api("/api/subagents", { scoped: false });
16627
18152
  latestSubagents = response.data || null;
16628
18153
  pruneDismissedSubagentGateKeys(latestSubagents?.tabs, dismissedSubagentGateKeys);
16629
- syncSubagentTerminalViewsFromOverview();
18154
+ subagentViewsChanged = syncSubagentTerminalViewsFromOverview();
18155
+ materializedTerminalViews = materializeRetainedSubagentTerminalViews();
16630
18156
  subagentsError = null;
16631
18157
  } catch (error) {
16632
18158
  subagentsError = error;
16633
18159
  } finally {
16634
18160
  subagentsLoading = false;
16635
18161
  renderSubagents();
18162
+ if (subagentOverlaySelection?.tabId === activeTabId) renderWidgets();
18163
+ if (activeSubagentTerminalId) {
18164
+ renderSubagentTerminalView();
18165
+ scheduleSubagentTerminalRefresh();
18166
+ }
18167
+ if (subagentViewsChanged || materializedTerminalViews) renderTabs();
16636
18168
  }
16637
18169
  }
16638
18170
 
16639
18171
  function scheduleRefreshSubagents(delay) {
16640
18172
  clearTimeout(refreshSubagentsTimer);
16641
- const totalAgents = Number(latestSubagents?.totalAgents || 0);
18173
+ const totalAgents = Number(latestSubagents?.runningAgents || 0);
16642
18174
  const hasRunningGate = (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : []).some((tab) => (Array.isArray(tab?.gates) ? tab.gates : []).some((gate) => gate?.status === "running"));
16643
18175
  const nextDelay = delay ?? (document.visibilityState === "hidden" ? SUBAGENTS_HIDDEN_REFRESH_MS : totalAgents > 0 || hasRunningGate ? SUBAGENTS_ACTIVE_REFRESH_MS : SUBAGENTS_IDLE_REFRESH_MS);
16644
18176
  refreshSubagentsTimer = setTimeout(() => {
@@ -22479,12 +24011,20 @@ function resumeGitWorkflowForActiveTab(tabContext = activeTabContext()) {
22479
24011
 
22480
24012
  function normalizeQueuedMessages(event) {
22481
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";
22482
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,
22483
24019
  steering: normalize(event?.steering),
22484
24020
  followUp: normalize(event?.followUp),
22485
24021
  };
22486
24022
  }
22487
24023
 
24024
+ function queuedSnapshotForTab(tabId = activeTabId) {
24025
+ return tabId ? latestQueuedMessagesByTab.get(tabId) || normalizeQueuedMessages({}) : normalizeQueuedMessages({});
24026
+ }
24027
+
22488
24028
  function queueMessageCount(snapshot) {
22489
24029
  return (snapshot?.steering?.length || 0) + (snapshot?.followUp?.length || 0);
22490
24030
  }
@@ -22502,13 +24042,331 @@ function queueSummaryPill(label, count, tone) {
22502
24042
  return pill;
22503
24043
  }
22504
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
+
22505
24363
  async function removeQueuedFollowUpPrompt(index, message, tabId = activeTabId) {
22506
- if (!tabId) return false;
22507
- const tabContext = activeTabContext(tabId);
24364
+ if (!tabId || queuedSnapshotForTab(tabId).source !== "pi-runtime") return false;
24365
+ const tabContext = queueTabContext(tabId);
22508
24366
  try {
22509
24367
  const response = await api("/api/queue/remove", { method: "POST", body: { kind: "followUp", index, message }, tabId });
22510
24368
  const data = response?.data || {};
22511
- if (data.queue && isCurrentTabContext(tabContext)) renderQueue({ tabId, ...data.queue });
24369
+ if (data.queue) applyAuthoritativeQueuedSnapshot(tabContext, data.queue);
22512
24370
  if (data.removed) {
22513
24371
  if (isCurrentTabContext(tabContext)) addEvent(`removed queued follow-up #${index + 1}`);
22514
24372
  scheduleRefreshState(120, tabContext);
@@ -22558,6 +24416,7 @@ function renderQueue(event) {
22558
24416
  const snapshot = normalizeQueuedMessages(event);
22559
24417
  const tabId = event?.tabId || activeTabId;
22560
24418
  if (tabId) latestQueuedMessagesByTab.set(tabId, snapshot);
24419
+ if (tabId && tabId !== activeTabId) return;
22561
24420
  const steering = snapshot.steering;
22562
24421
  const followUp = snapshot.followUp;
22563
24422
  const total = queueMessageCount(snapshot);
@@ -22567,6 +24426,7 @@ function renderQueue(event) {
22567
24426
  elements.queueBox.classList.toggle("has-items", total > 0);
22568
24427
  if (total === 0) {
22569
24428
  elements.queueBox.append(make("div", "queue-empty", "No queued messages."));
24429
+ if (tabId === activeTabId) renderFollowUpQueueOverlay();
22570
24430
  updateStickyUserPromptButton();
22571
24431
  return;
22572
24432
  }
@@ -22580,19 +24440,16 @@ function renderQueue(event) {
22580
24440
 
22581
24441
  elements.queueBox.append(summary);
22582
24442
  if (steering.length) elements.queueBox.append(renderQueueGroup("Steering", steering, "steering", { tabId }));
22583
- if (followUp.length) elements.queueBox.append(renderQueueGroup("Follow-up", followUp, "follow-up", { removable: true, tabId }));
22584
- 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();
22585
24448
  updateStickyUserPromptButton();
22586
24449
  }
22587
24450
 
22588
- function nextQueuedFollowUpPrompt(tabId = activeTabId) {
22589
- const snapshot = tabId ? latestQueuedMessagesByTab.get(tabId) : null;
22590
- const next = Array.isArray(snapshot?.followUp) ? snapshot.followUp.find((item) => String(item || "").trim()) : null;
22591
- return next ? stickyUserPromptPreviewText(next) : "";
22592
- }
22593
-
22594
24451
  function queuedMessagesForComposer(tabId = activeTabId) {
22595
- const snapshot = latestQueuedMessagesByTab.get(tabId) || { steering: [], followUp: [] };
24452
+ const snapshot = queuedSnapshotForTab(tabId);
22596
24453
  return [...(snapshot.steering || []), ...(snapshot.followUp || [])].map((item) => String(item || "").trim()).filter(Boolean);
22597
24454
  }
22598
24455
 
@@ -24448,6 +26305,12 @@ function renderEmptyStartState() {
24448
26305
  className: "primary",
24449
26306
  onClick: (button) => createTerminalTabFromChosenDirectory({ triggerButton: button }),
24450
26307
  }),
26308
+ emptyStartAction({
26309
+ title: "Load workspace",
26310
+ description: "Restore a saved tab constellation",
26311
+ symbol: "⇱",
26312
+ onClick: (button) => openWorkspaceLoadPicker({ triggerButton: button }),
26313
+ }),
24451
26314
  emptyStartAction({
24452
26315
  title: "Resume session",
24453
26316
  description: "Continue previous work and context",
@@ -24550,21 +26413,15 @@ function updateStickyUserPromptButton() {
24550
26413
  button.dataset.compacted = target.compacted ? "true" : "false";
24551
26414
  if (Number.isInteger(target.index) && target.index >= 0) button.dataset.messageIndex = String(target.index);
24552
26415
  else button.removeAttribute("data-message-index");
24553
- const nextFollowUp = nextQueuedFollowUpPrompt();
24554
26416
  const baseTitle = target.compacted ? `Prompt was compacted; jump to compaction summary: ${target.preview}` : `Jump to ${label.toLowerCase()}: ${target.preview}`;
24555
26417
  const baseAriaLabel = target.compacted ? `Prompt was compacted; jump to compaction summary: ${target.preview}` : `Jump to ${label.toLowerCase()} (${ordinal} of ${targets.length}): ${target.preview}`;
24556
- button.title = nextFollowUp ? `${baseTitle}\nNext follow-up prompt: ${nextFollowUp}` : baseTitle;
24557
- button.setAttribute("aria-label", nextFollowUp ? `${baseAriaLabel}. Next follow-up prompt: ${nextFollowUp}` : baseAriaLabel);
26418
+ button.title = baseTitle;
26419
+ button.setAttribute("aria-label", baseAriaLabel);
24558
26420
  const children = [
24559
26421
  make("span", "sticky-user-prompt-label", label),
24560
26422
  make("span", "sticky-user-prompt-text", target.preview),
24561
26423
  make("span", "sticky-user-prompt-meta", meta),
24562
26424
  ];
24563
- if (nextFollowUp) {
24564
- const followUp = make("span", "sticky-user-follow-up-prompt");
24565
- followUp.append(make("span", "sticky-user-follow-up-label", "Next follow-up"), make("span", "sticky-user-follow-up-text", nextFollowUp));
24566
- children.push(followUp);
24567
- }
24568
26425
  button.replaceChildren(...children);
24569
26426
  }
24570
26427
 
@@ -26068,8 +27925,19 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
26068
27925
  });
26069
27926
  }
26070
27927
 
26071
- if (data.download && handleNativeDownloadResponse(data.download, data.command, data.serverPath)) {
26072
- addEvent(data.command === "export" ? `export ready: ${data.download.fileName || data.download.url}` : `download started: ${data.download.fileName || data.download.url}`, "info");
27928
+ if (data.download) {
27929
+ const downloadLabel = data.download.fileName || data.download.url || "unnamed download";
27930
+ try {
27931
+ const opened = handleNativeDownloadResponse(data.download, data.command, data.serverPath);
27932
+ if (opened) {
27933
+ addEvent(data.command === "export" ? `export ready: ${downloadLabel}` : `download started: ${downloadLabel}`, "info");
27934
+ } else {
27935
+ addEvent(`could not open ${data.command === "export" ? "HTML export" : "download"}: missing or invalid browser URL (${downloadLabel})`, "error");
27936
+ }
27937
+ } catch (error) {
27938
+ const reason = error?.message || String(error);
27939
+ addEvent(`could not open ${data.command === "export" ? "HTML export" : "download"} ${downloadLabel}: ${reason}`, "error");
27940
+ }
26073
27941
  }
26074
27942
 
26075
27943
  const cards = Array.isArray(data.cards) && data.cards.length ? data.cards : null;
@@ -26342,6 +28210,7 @@ async function sendBtwPromptFromButton() {
26342
28210
  }
26343
28211
 
26344
28212
  function setPublishMenuOpen(open) {
28213
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26345
28214
  publishMenuOpen = !!open;
26346
28215
  elements.publishButton.setAttribute("aria-expanded", publishMenuOpen ? "true" : "false");
26347
28216
  elements.publishButton.classList.toggle("menu-open", publishMenuOpen);
@@ -26351,6 +28220,7 @@ function setPublishMenuOpen(open) {
26351
28220
  }
26352
28221
 
26353
28222
  function setNativeCommandMenuOpen(open) {
28223
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26354
28224
  nativeCommandMenuOpen = !!open;
26355
28225
  elements.nativeCommandMenuButton.setAttribute("aria-expanded", nativeCommandMenuOpen ? "true" : "false");
26356
28226
  elements.nativeCommandMenuButton.classList.toggle("menu-open", nativeCommandMenuOpen);
@@ -26360,6 +28230,7 @@ function setNativeCommandMenuOpen(open) {
26360
28230
  }
26361
28231
 
26362
28232
  function setAppRunnerMenuOpen(open) {
28233
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26363
28234
  appRunnerMenuOpen = !!open;
26364
28235
  elements.appRunnerMenuButton?.setAttribute("aria-expanded", appRunnerMenuOpen ? "true" : "false");
26365
28236
  elements.appRunnerMenuButton?.classList.toggle("menu-open", appRunnerMenuOpen);
@@ -26369,6 +28240,7 @@ function setAppRunnerMenuOpen(open) {
26369
28240
  }
26370
28241
 
26371
28242
  function setOptionsMenuOpen(open) {
28243
+ if (open && followUpQueueOpen) setFollowUpQueueOpen(false);
26372
28244
  optionsMenuOpen = !!open;
26373
28245
  elements.optionsMenuButton.setAttribute("aria-expanded", optionsMenuOpen ? "true" : "false");
26374
28246
  elements.optionsMenuButton.classList.toggle("menu-open", optionsMenuOpen);
@@ -26583,23 +28455,85 @@ async function refreshOptionalFeaturePackageStatuses({ announce = false } = {})
26583
28455
  }
26584
28456
  }
26585
28457
 
28458
+ function clearGitFooterPayloadState(tabId) {
28459
+ if (!tabId) return;
28460
+ gitFooterPayloadRequestSerialByTab.set(tabId, (gitFooterPayloadRequestSerialByTab.get(tabId) || 0) + 1);
28461
+ clearTimeout(gitFooterPayloadSettlementTimersByTab.get(tabId));
28462
+ gitFooterPayloadSettlementTimersByTab.delete(tabId);
28463
+ gitFooterPayloadStateByTab.delete(tabId);
28464
+ gitFooterPayloadRefreshInFlightByTab.delete(tabId);
28465
+ }
28466
+
28467
+ function settleGitFooterPayload(tabId, phase, error = "") {
28468
+ if (!tabId) return;
28469
+ clearTimeout(gitFooterPayloadSettlementTimersByTab.get(tabId));
28470
+ gitFooterPayloadSettlementTimersByTab.delete(tabId);
28471
+ gitFooterPayloadStateByTab.set(tabId, { phase, error });
28472
+ }
28473
+
28474
+ function waitForGitFooterPayloadSettlement(tabContext, requestSerial) {
28475
+ clearTimeout(gitFooterPayloadSettlementTimersByTab.get(tabContext.tabId));
28476
+ const timer = setTimeout(() => {
28477
+ gitFooterPayloadSettlementTimersByTab.delete(tabContext.tabId);
28478
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
28479
+ if (gitFooterPayloadStateByTab.get(tabContext.tabId)?.phase === "waiting") {
28480
+ settleGitFooterPayload(tabContext.tabId, "failed", "Git footer status was not received — refresh to retry");
28481
+ }
28482
+ if (isCurrentTabContext(tabContext)) renderFooter();
28483
+ }, GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS);
28484
+ gitFooterPayloadSettlementTimersByTab.set(tabContext.tabId, timer);
28485
+ }
28486
+
26586
28487
  function requestGitFooterWebuiPayload(tabContext = activeTabContext(), { force = false, silent = true, allowDuringRun = false } = {}) {
26587
28488
  if (!tabContext.tabId || isOptionalFeatureDisabled("gitFooterStatus")) return;
26588
28489
  if (!allowDuringRun && (currentState?.isStreaming || currentState?.isCompacting)) return;
26589
28490
  const refreshCommand = resolveAvailableCommandName("git-footer-refresh", { rpcOnly: true });
26590
- if (!refreshCommand || (!force && statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY))) return;
28491
+ if (!refreshCommand) {
28492
+ if (hasAvailableCommand("git-footer-refresh") || optionalFeatureAvailability.gitFooterStatus) {
28493
+ gitFooterPayloadRefreshInFlightByTab.delete(tabContext.tabId);
28494
+ const requestSerial = (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) || 0) + 1;
28495
+ gitFooterPayloadRequestSerialByTab.set(tabContext.tabId, requestSerial);
28496
+ settleGitFooterPayload(tabContext.tabId, "waiting");
28497
+ const timer = setTimeout(() => {
28498
+ gitFooterPayloadSettlementTimersByTab.delete(tabContext.tabId);
28499
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
28500
+ if (gitFooterPayloadStateByTab.get(tabContext.tabId)?.phase === "waiting") {
28501
+ settleGitFooterPayload(tabContext.tabId, "failed", "Git footer refresh command is unavailable — reload to retry");
28502
+ }
28503
+ if (isCurrentTabContext(tabContext)) renderFooter();
28504
+ }, GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS);
28505
+ gitFooterPayloadSettlementTimersByTab.set(tabContext.tabId, timer);
28506
+ if (isCurrentTabContext(tabContext)) renderFooter();
28507
+ }
28508
+ return;
28509
+ }
28510
+ if (!force && statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY)) return;
26591
28511
  if (gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId)) return;
26592
28512
 
28513
+ const requestSerial = (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) || 0) + 1;
28514
+ gitFooterPayloadRequestSerialByTab.set(tabContext.tabId, requestSerial);
28515
+ settleGitFooterPayload(tabContext.tabId, "waiting");
26593
28516
  gitFooterPayloadRefreshInFlightByTab.add(tabContext.tabId);
26594
28517
  if (isCurrentTabContext(tabContext)) renderFooter();
26595
28518
  return api("/api/prompt", {
26596
28519
  method: "POST",
26597
28520
  body: { message: `/${refreshCommand}${silent ? " --webui-silent" : ""}`, streamingBehavior: "steer" },
26598
28521
  tabId: tabContext.tabId,
28522
+ signal: AbortSignal.timeout(GIT_FOOTER_PAYLOAD_REQUEST_TIMEOUT_MS),
28523
+ }).then(() => {
28524
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
28525
+ if (gitFooterPayloadStateByTab.get(tabContext.tabId)?.phase === "waiting") waitForGitFooterPayloadSettlement(tabContext, requestSerial);
26599
28526
  }).catch((error) => {
26600
- if (isCurrentTabContext(tabContext)) addEvent(`git footer payload refresh failed: ${error.message || String(error)}`, "warn");
28527
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
28528
+ const message = `Git footer refresh failed: ${error.message || String(error)}`;
28529
+ settleGitFooterPayload(tabContext.tabId, "failed", "Git footer refresh failed — refresh to retry");
28530
+ if (isCurrentTabContext(tabContext)) {
28531
+ if (silent) addEvent(message, "warn");
28532
+ else surfaceRuntimeDiagnostic("Git footer refresh failed", message, "warn");
28533
+ }
26601
28534
  }).finally(() => {
26602
28535
  gitFooterPayloadRefreshInFlightByTab.delete(tabContext.tabId);
28536
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
26603
28537
  if (isCurrentTabContext(tabContext)) renderFooter();
26604
28538
  });
26605
28539
  }
@@ -30769,6 +32703,10 @@ function commandPaletteCoreItems() {
30769
32703
  { kind: "Pi", label: "/tools", description: "Manage active tools", keywords: "capabilities", run: () => runNativeCommandMenu("/tools") },
30770
32704
  { kind: "Pi", label: "/skills", description: "Manage active skills", keywords: "system prompt", run: () => runNativeCommandMenu("/skills") },
30771
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 }) });
30772
32710
  if (isOptionalFeatureEnabled("statsCommand")) items.push({ kind: "Pi", label: "/stats-webui", description: "Open usage dashboard", keywords: "tokens cost budget", run: () => openStatsOverlay({ refresh: true }) });
30773
32711
  return items;
30774
32712
  }
@@ -31501,9 +33439,18 @@ function handleExtensionUiRequest(request) {
31501
33439
  }
31502
33440
  if (request.statusText) {
31503
33441
  statusEntries.set(statusKey, request.statusText);
31504
- if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) cacheGitFooterWebuiPayload(request.statusText, request.tabId);
33442
+ if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) {
33443
+ const validPayload = !!parseGitFooterWebuiPayloadRaw(request.statusText);
33444
+ cacheGitFooterWebuiPayload(request.statusText, request.tabId);
33445
+ settleGitFooterPayload(
33446
+ request.tabId || activeTabId,
33447
+ validPayload ? "ready" : "failed",
33448
+ validPayload ? "" : "Git footer returned invalid status data — refresh to retry",
33449
+ );
33450
+ }
31505
33451
  } else {
31506
33452
  statusEntries.delete(statusKey);
33453
+ if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) settleGitFooterPayload(request.tabId || activeTabId, "idle");
31507
33454
  }
31508
33455
  if (statusKey === STATS_WEBUI_STATUS_KEY) handleStatsWebuiStatus(request.statusText);
31509
33456
  if (statusKey === BTW_WEBUI_STATUS_KEY) handleBtwWebuiStatus(request.statusText);
@@ -31981,7 +33928,7 @@ function handleInactiveTabEvent(event) {
31981
33928
  setWidgetForTab(event.tabId, AUR_REVIEW_RPC_WIDGET_KEY, event);
31982
33929
  updateOptionalFeatureAvailability();
31983
33930
  renderTabs();
31984
- } else if (event.type === "agent_end") {
33931
+ } else if (event.type === "agent_settled") {
31985
33932
  notifyAgentDone(event.tabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
31986
33933
  }
31987
33934
  }
@@ -32163,6 +34110,7 @@ function handleEvent(event) {
32163
34110
  break;
32164
34111
  case "agent_start":
32165
34112
  assistantErrorSurfacedThisRun = false;
34113
+ markTabWorkingLocally(event.tabId || activeTabId, { runStarted: true });
32166
34114
  if (currentState) currentState = { ...currentState, isStreaming: true };
32167
34115
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ streaming: true });
32168
34116
  setRunIndicatorActivity("Agent run started; waiting for first output or action…");
@@ -32181,34 +34129,11 @@ function handleEvent(event) {
32181
34129
  assistantErrorSurfacedThisRun = true;
32182
34130
  }
32183
34131
  }
32184
- addEvent("agent finished");
32185
- notifyAgentDone(event.tabId || activeTabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
32186
- clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
32187
- if (currentState) currentState = { ...currentState, isStreaming: false };
32188
- // handleAssistantTurnEnd resets the controller's streaming/tool flags and
32189
- // flushes queued interruptions itself; calling setAssistantActivity here
32190
- // first would flush the queue and then speak the interrupted answer.
32191
- if (voiceConversationActiveFor(event.tabId || activeTabId)) void handleVoiceConversationTurnEnd(tabContext);
32192
- clearRunIndicatorActivity();
32193
- markTabOutputSeen();
32194
- requestGitFooterWebuiPayload(tabContext, { force: true });
32195
- scheduleRefreshState();
34132
+ addEvent("agent run ended; waiting for settlement");
34133
+ if (runIndicatorIsActive()) setRunIndicatorActivity("Agent run ended; checking for retry or continuation…", { scroll: false });
32196
34134
  scheduleRefreshMessages();
34135
+ scheduleRefreshState();
32197
34136
  scheduleRefreshFooter();
32198
- scheduleRefreshCodexUsage(2200);
32199
- scheduleRefreshClaudeUsage(2200);
32200
- renderFeedbackTray();
32201
- {
32202
- const workflowTabId = event.tabId || activeTabId;
32203
- const workflow = gitWorkflowForTab(workflowTabId, { create: false });
32204
- if (workflow?.active && workflow.step === "generating") {
32205
- loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
32206
- } else if (workflow?.active && workflow.step === "branchNaming") {
32207
- loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
32208
- } else if (workflow?.active && workflow.step === "prGenerating") {
32209
- loadGitWorkflowPr({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
32210
- }
32211
- }
32212
34137
  break;
32213
34138
  case "message_start":
32214
34139
  if (event.message?.role === "assistant") {
@@ -32294,6 +34219,35 @@ function handleEvent(event) {
32294
34219
  break;
32295
34220
  case "agent_settled":
32296
34221
  if (compactOutputActive()) finishCompactLiveOutput(tabContext);
34222
+ streamMessageActive = false;
34223
+ addEvent("agent finished");
34224
+ notifyAgentDone(event.tabId || activeTabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
34225
+ clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
34226
+ if (currentState) currentState = { ...currentState, isStreaming: false };
34227
+ // handleAssistantTurnEnd resets the controller's streaming/tool flags and
34228
+ // flushes queued interruptions itself; calling setAssistantActivity here
34229
+ // first would flush the queue and then speak the interrupted answer.
34230
+ if (voiceConversationActiveFor(event.tabId || activeTabId)) void handleVoiceConversationTurnEnd(tabContext);
34231
+ clearRunIndicatorActivity();
34232
+ markTabOutputSeen();
34233
+ requestGitFooterWebuiPayload(tabContext, { force: true });
34234
+ scheduleRefreshState();
34235
+ scheduleRefreshMessages();
34236
+ scheduleRefreshFooter();
34237
+ scheduleRefreshCodexUsage(2200);
34238
+ scheduleRefreshClaudeUsage(2200);
34239
+ renderFeedbackTray();
34240
+ {
34241
+ const workflowTabId = event.tabId || activeTabId;
34242
+ const workflow = gitWorkflowForTab(workflowTabId, { create: false });
34243
+ if (workflow?.active && workflow.step === "generating") {
34244
+ loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
34245
+ } else if (workflow?.active && workflow.step === "branchNaming") {
34246
+ loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
34247
+ } else if (workflow?.active && workflow.step === "prGenerating") {
34248
+ loadGitWorkflowPr({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
34249
+ }
34250
+ }
32297
34251
  break;
32298
34252
  case "auto_retry_start": {
32299
34253
  const seconds = Math.max(0, Math.ceil(Number(event.delayMs || 0) / 1000));
@@ -32443,6 +34397,10 @@ elements.composer.addEventListener("submit", (event) => {
32443
34397
  event.preventDefault();
32444
34398
  sendPrompt("prompt");
32445
34399
  });
34400
+ elements.followUpQueueTrigger?.addEventListener("click", () => {
34401
+ setFollowUpQueueOpen(!followUpQueueOpen);
34402
+ });
34403
+ elements.followUpQueueCloseButton?.addEventListener("click", () => setFollowUpQueueOpen(false, { restoreFocus: true }));
32446
34404
  elements.composerActionsButton.addEventListener("click", () => {
32447
34405
  setComposerActionsOpen(!document.body.classList.contains("composer-actions-open"));
32448
34406
  });
@@ -32545,6 +34503,7 @@ elements.newTabCurrentDirectoryButton?.addEventListener("click", () => createTer
32545
34503
  elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerminalTabFromChosenDirectory({ triggerButton: elements.newTabChooseDirectoryButton }));
32546
34504
  elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
32547
34505
  elements.splitTabButton?.addEventListener("click", () => splitActiveTerminalTab());
34506
+ elements.workspaceSaveButton?.addEventListener("click", () => saveWebuiWorkspace());
32548
34507
  elements.terminalSplitCloseButton?.addEventListener("click", () => closeTerminalSplitView());
32549
34508
  elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
32550
34509
  elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
@@ -32789,6 +34748,30 @@ elements.confirmationDialog?.addEventListener("cancel", (event) => {
32789
34748
  elements.confirmationDialog?.addEventListener("close", () => {
32790
34749
  if (activeConfirmationResolve) finishApplicationConfirmation(false);
32791
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
+ });
32792
34775
  elements.gitWorktreeBaseCancelButton?.addEventListener("click", () => finishGitWorktreeBaseChoice(null));
32793
34776
  elements.gitWorktreeBaseCreateButton?.addEventListener("click", () => finishGitWorktreeBaseChoice(elements.gitWorktreeBaseCurrentHead?.checked ? "HEAD" : "origin/main"));
32794
34777
  elements.gitWorktreeBaseDialog?.querySelector("form")?.addEventListener("submit", (event) => {
@@ -33255,6 +35238,23 @@ elements.subagentTerminalCopyButton?.addEventListener("click", () => copySubagen
33255
35238
  elements.subagentTerminalRefreshButton?.addEventListener("click", () => {
33256
35239
  refreshSubagentTerminalView(activeSubagentTerminalId, { showLoading: true }).finally(() => scheduleSubagentTerminalRefresh());
33257
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
+ });
33258
35258
  elements.piVersionButton?.addEventListener("click", () => {
33259
35259
  openPiReleaseNotes().catch((error) => addEvent(error.message || String(error), "error"));
33260
35260
  });
@@ -33301,6 +35301,9 @@ document.addEventListener("pointerdown", (event) => {
33301
35301
  if (document.body.classList.contains("composer-actions-open") && !elements.composer.contains(event.target)) {
33302
35302
  setComposerActionsOpen(false);
33303
35303
  }
35304
+ if (followUpQueueOpen && !event.target?.closest?.("#followUpQueueOverlay, #followUpQueueTrigger")) {
35305
+ setFollowUpQueueOpen(false, { restoreFocus: true });
35306
+ }
33304
35307
  if (publishMenuOpen && !event.target?.closest?.(".composer-publish-menu")) {
33305
35308
  setPublishMenuOpen(false);
33306
35309
  }
@@ -33478,6 +35481,7 @@ function stepChatSearch(step) {
33478
35481
 
33479
35482
  function openChatSearch() {
33480
35483
  if (!elements.chatSearchBar) return;
35484
+ closeFileViewerSearch({ restoreFocus: false });
33481
35485
  elements.chatSearchBar.hidden = false;
33482
35486
  elements.chatSearchInput?.focus();
33483
35487
  elements.chatSearchInput?.select();
@@ -33516,7 +35520,8 @@ elements.chatSearchCloseButton?.addEventListener("click", closeChatSearch);
33516
35520
  window.addEventListener("keydown", (event) => {
33517
35521
  if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") {
33518
35522
  event.preventDefault();
33519
- openChatSearch();
35523
+ if (activeFileViewer && elements.fileViewerPane?.contains(event.target)) openFileViewerSearch();
35524
+ else openChatSearch();
33520
35525
  }
33521
35526
  });
33522
35527
 
@@ -33542,6 +35547,11 @@ window.addEventListener("keydown", (event) => {
33542
35547
  if (event.key !== "Escape") return;
33543
35548
  if (event.defaultPrevented) return;
33544
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
+ }
33545
35555
  if (publishMenuOpen) {
33546
35556
  setPublishMenuOpen(false);
33547
35557
  return;
@@ -33752,12 +35762,33 @@ elements.fileViewerCloseButton?.addEventListener("click", closeFileViewer);
33752
35762
  elements.fileViewerChangesModeButton?.addEventListener("click", () => setFileViewerMode("changes"));
33753
35763
  elements.fileViewerSourceModeButton?.addEventListener("click", () => setFileViewerMode("source"));
33754
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());
33755
35785
  elements.fileViewerEditor?.addEventListener("input", () => {
33756
35786
  if (!activeFileViewer) return;
33757
35787
  activeFileViewer.content = elements.fileViewerEditor.value || "";
33758
35788
  activeFileViewer.size = new Blob([activeFileViewer.content]).size;
33759
35789
  setFileViewerDirty(true);
33760
35790
  updateFileViewerSelectionFromEditor();
35791
+ if (elements.fileViewerSearchBar && !elements.fileViewerSearchBar.hidden) runFileViewerSearch();
33761
35792
  });
33762
35793
  for (const eventName of ["select", "keyup", "mouseup"]) {
33763
35794
  elements.fileViewerEditor?.addEventListener(eventName, updateFileViewerSelectionFromEditor);
@@ -33885,6 +35916,7 @@ elements.promptInput.addEventListener("blur", () => {
33885
35916
  });
33886
35917
 
33887
35918
  installModalPrimitives();
35919
+ initializeIssueWizard();
33888
35920
  resizePromptInput();
33889
35921
  restoreSidePanelWidthPreference();
33890
35922
  restoreFileViewerWidthPreference();