@firstpick/pi-package-webui 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +60 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +612 -0
  3. package/bin/pi-webui.mjs +1051 -95
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +317 -0
  6. package/lib/rpc-supervisor-protocol.mjs +245 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +4 -4
  10. package/public/app.js +1986 -170
  11. package/public/index.html +388 -25
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +8 -1
  15. package/public/styles.css +578 -52
  16. package/public/subagent-gate-visibility.mjs +36 -0
  17. package/public/workflow-status-stack.mjs +69 -0
  18. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  19. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  20. package/tests/completion-signal-contract.test.mjs +156 -0
  21. package/tests/cwd-footer-reliability-static.test.mjs +107 -0
  22. package/tests/durable-rpc-supervisor-harness.test.mjs +275 -0
  23. package/tests/fast-mode-client-static.test.mjs +2 -2
  24. package/tests/fixtures/fake-pi.mjs +90 -6
  25. package/tests/footer-context-contrast-static.test.mjs +10 -0
  26. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  27. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  28. package/tests/http-endpoints-harness.test.mjs +458 -33
  29. package/tests/issue-bot-client.test.mjs +135 -0
  30. package/tests/issue-wizard-state.test.mjs +126 -0
  31. package/tests/mobile-static.test.mjs +79 -16
  32. package/tests/native-parity-harness.test.mjs +2 -1
  33. package/tests/native-parity.test.mjs +13 -2
  34. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  35. package/tests/open-issue-wizard-static.test.mjs +75 -0
  36. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  37. package/tests/prompt-routing-tab-status.test.mjs +108 -0
  38. package/tests/rpc-supervisor-host.test.mjs +408 -0
  39. package/tests/rpc-supervisor-protocol.test.mjs +93 -0
  40. package/tests/rpc-supervisor-state.test.mjs +62 -0
  41. package/tests/run-all.mjs +4 -1
  42. package/tests/streaming-ui-coupling.test.mjs +18 -2
  43. package/tests/subagent-gate-visibility.test.mjs +66 -0
  44. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  45. package/tests/subagents-helper.test.mjs +136 -0
  46. package/tests/terminal-tab-workspace-static.test.mjs +99 -0
  47. package/tests/workflow-status-stack.test.mjs +87 -0
  48. package/webui-rpc-helper.mjs +160 -2
package/public/app.js CHANGED
@@ -3,6 +3,10 @@ import { guidedGitReviewAvailableForTabCatalog, resolveCommandForTabCatalog, res
3
3
  import { guidedGitReviewCanRequestStagedContent, guidedGitReviewHasApprovedBinding, guidedGitReviewProcessNavigationAllowed, guidedGitReviewProcessSelectionPatch, guidedGitReviewTransition, guidedGitReviewWidgetRemovalTransition } from "./guided-git-review-state.mjs";
4
4
  import { createFastOutputLiveState, createSustainedFlushScheduler, fastOutputLiveTextAndThinking, reduceFastOutputLiveEvent, seedFastOutputLiveState, shouldConsumeFastOutputLiveEvent } from "./fast-output-live.mjs";
5
5
  import { addLaunchSlot, cloneLaunchSlotRoles, launchSlotRolesEqual, removeLaunchSlot, updateLaunchSlot } from "./subagent-launch-slot-state.mjs";
6
+ import { pruneDismissedSubagentGateKeys, subagentGateIsTerminal, subagentGateKey, visibleSubagentGates } from "./subagent-gate-visibility.mjs";
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";
6
10
 
7
11
  const $ = (selector) => document.querySelector(selector);
8
12
 
@@ -129,6 +133,7 @@ const elements = {
129
133
  optionsNameButton: $("#optionsNameButton"),
130
134
  optionsCloneButton: $("#optionsCloneButton"),
131
135
  optionsSettingsButton: $("#optionsSettingsButton"),
136
+ optionsWorkflowSetupButton: $("#optionsWorkflowSetupButton"),
132
137
  optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
133
138
  optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
134
139
  optionsExportButton: $("#optionsExportButton"),
@@ -223,10 +228,12 @@ const elements = {
223
228
  fileViewerSaveButton: $("#fileViewerSaveButton"),
224
229
  fileViewerCloseButton: $("#fileViewerCloseButton"),
225
230
  fileViewerHelp: $("#fileViewerHelp"),
231
+ fileViewerChangesModeButton: $("#fileViewerChangesModeButton"),
226
232
  fileViewerSourceModeButton: $("#fileViewerSourceModeButton"),
227
233
  fileViewerPreviewModeButton: $("#fileViewerPreviewModeButton"),
228
234
  fileViewerEditor: $("#fileViewerEditor"),
229
235
  fileViewerPreview: $("#fileViewerPreview"),
236
+ fileViewerChanges: $("#fileViewerChanges"),
230
237
  fileViewerStatus: $("#fileViewerStatus"),
231
238
  fileSelectionBar: $("#fileSelectionBar"),
232
239
  fileSelectionSummary: $("#fileSelectionSummary"),
@@ -239,6 +246,24 @@ const elements = {
239
246
  sidePanelExpandButton: $("#sidePanelExpandButton"),
240
247
  sidePanelBackdrop: $("#sidePanelBackdrop"),
241
248
  sidePanel: $("#sidePanel"),
249
+ openIssueButton: $("#openIssueButton"),
250
+ issueWizardDialog: $("#issueWizardDialog"),
251
+ issueWizardPages: $("#issueWizardPages"),
252
+ issueWizardProgress: $("#issueWizardProgress"),
253
+ issueWizardStatus: $("#issueWizardStatus"),
254
+ issueWizardSubmissionStatus: $("#issueWizardSubmissionStatus"),
255
+ issueWizardSubmissionMessage: $("#issueWizardSubmissionMessage"),
256
+ issueWizardSubmissionLink: $("#issueWizardSubmissionLink"),
257
+ issueWizardRefreshButton: $("#issueWizardRefreshButton"),
258
+ issueWizardSecurityGuidance: $("#issueWizardSecurityGuidance"),
259
+ issueWizardSecurityLink: $("#issueWizardSecurityLink"),
260
+ issueWizardTurnstile: $("#issueWizardTurnstile"),
261
+ issueWizardCloseButton: $("#issueWizardCloseButton"),
262
+ issueWizardBackButton: $("#issueWizardBackButton"),
263
+ issueWizardContinueButton: $("#issueWizardContinueButton"),
264
+ issueWizardCopyButton: $("#issueWizardCopyButton"),
265
+ issueWizardBotButton: $("#issueWizardBotButton"),
266
+ issueWizardBotHint: $("#issueWizardBotHint"),
242
267
  stateDetails: $("#stateDetails"),
243
268
  subagentsStatus: $("#subagentsStatus"),
244
269
  subagentsBox: $("#subagentsBox"),
@@ -386,6 +411,8 @@ let activeTextAttachmentEditor = null;
386
411
  let activeSkillEditor = null;
387
412
  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() };
388
413
  let activeFileViewer = null;
414
+ let fileViewerOpenRequestSerial = 0;
415
+ let fileViewerGitChangesRequestSerial = 0;
389
416
  let fileViewerSelection = null;
390
417
  let fileContextMenuState = null;
391
418
  let sidePanelContextMenuState = null;
@@ -395,6 +422,7 @@ let sidePanelResizeState = null;
395
422
  let fileTreeSearchTimer = null;
396
423
  let fileTreeSearchRequestSerial = 0;
397
424
  let tabActivities = new Map();
425
+ const promptRoutingTabs = new Set();
398
426
  let tabSeenCompletionSerials = new Map();
399
427
  let streamBubble = null;
400
428
  let streamText = null;
@@ -447,6 +475,11 @@ let refreshTabsTimer = null;
447
475
  let tabsRenderFrame = null;
448
476
  let foregroundReconcileTimer = null;
449
477
  let eventSource = null;
478
+ const supervisorEventCursors = new Map();
479
+ const supervisorRetiredEpochs = new Map();
480
+ const supervisorGapWarnings = new Set();
481
+ const supervisorContinuityRefreshes = new Map();
482
+ const supervisorEnvelopeWarnings = new Set();
450
483
  let activeDialog = null;
451
484
  let activeConfirmationResolve = null;
452
485
  let activeGitWorktreeBaseResolve = null;
@@ -492,6 +525,9 @@ const skillUsageByTab = new Map();
492
525
  let appRunnerCustomDraft = { id: "", label: "", command: "./", path: "", args: "" };
493
526
  let appRunnerCustomFeedback = { type: "", message: "" };
494
527
  let appRunnerFileBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
528
+ let appRunnerSearchPathDraft = "";
529
+ let appRunnerSearchPathFeedback = { type: "", message: "" };
530
+ let appRunnerDirectoryBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
495
531
  let optionsMenuOpen = false;
496
532
  let availableCommands = [];
497
533
  let rawAvailableCommands = [];
@@ -543,6 +579,7 @@ let latestSubagents = null;
543
579
  let subagentsError = null;
544
580
  let subagentsLoading = false;
545
581
  let refreshSubagentsTimer = null;
582
+ const dismissedSubagentGateKeys = new Set();
546
583
  let subagentOverlaySelection = null;
547
584
  let subagentOverlayData = null;
548
585
  let subagentOverlayError = "";
@@ -696,6 +733,8 @@ const GIT_FOOTER_WEBUI_STATUS_KEY = "git-footer-webui";
696
733
  const GIT_FOOTER_WEBUI_PAYLOAD_TYPE = "firstpick.git-footer-status.footer";
697
734
  const GIT_FOOTER_WEBUI_PAYLOAD_VERSION = 1;
698
735
  const GIT_FOOTER_WEBUI_PAYLOAD_CACHE_KEY = "pi-webui-git-footer-webui-payload-cache";
736
+ const GIT_FOOTER_PAYLOAD_REQUEST_TIMEOUT_MS = 10_000;
737
+ const GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS = 2_000;
699
738
  const GIT_FOOTER_STATUS_SETUP_STORAGE_KEY = "pi-webui-git-footer-status-setup";
700
739
  const GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS = Object.freeze({
701
740
  tokens: true,
@@ -927,6 +966,7 @@ const optionalFeatureAvailability = {
927
966
  };
928
967
  const APP_RUNNER_CONTEXT_DEFAULT_LINES = 80;
929
968
  const APP_RUNNER_CONTEXT_MAX_LINES = 1000;
969
+ const APP_RUNNER_SEARCH_PATH_LIMIT = 24;
930
970
  const OPTIONAL_FEATURES = [
931
971
  {
932
972
  id: "bangCommandAutocomplete",
@@ -1049,6 +1089,389 @@ const OPTIONAL_FEATURES = [
1049
1089
  },
1050
1090
  ];
1051
1091
  const OPTIONAL_FEATURE_BY_ID = new Map(OPTIONAL_FEATURES.map((feature) => [feature.id, feature]));
1092
+
1093
+ let issueWizardCatalog = null;
1094
+ let issueWizardState = createIssueWizardState();
1095
+ const issueBotRuntimeConfig = readIssueBotRuntimeConfig();
1096
+ let issueBotClient = null;
1097
+ let issueBotAbortController = null;
1098
+ let issueBotSubmissionHandle = null;
1099
+ let issueBotSubmissionResult = null;
1100
+ let issueBotRequestActive = false;
1101
+
1102
+ function setIssueWizardStatus(message) {
1103
+ if (elements.issueWizardStatus) elements.issueWizardStatus.textContent = message;
1104
+ }
1105
+
1106
+ function issueWizardPage(step) {
1107
+ return elements.issueWizardPages?.querySelector(`[data-issue-wizard-page="${step}"]`) || null;
1108
+ }
1109
+
1110
+ function issueWizardChoiceButton({ label, description = "", preview = "", selected, action, value, group }) {
1111
+ const button = make("button", "issue-wizard-choice");
1112
+ button.type = "button";
1113
+ button.dataset.issueWizardAction = action;
1114
+ button.dataset.issueWizardValue = value;
1115
+ button.dataset.issueWizardGroup = group;
1116
+ button.setAttribute("aria-pressed", selected ? "true" : "false");
1117
+ button.classList.toggle("selected", selected);
1118
+ button.append(make("strong", undefined, label));
1119
+ if (description) button.append(make("span", "issue-wizard-choice-description", description));
1120
+ if (preview) button.append(make("span", "issue-wizard-choice-preview", preview));
1121
+ return button;
1122
+ }
1123
+
1124
+ function focusIssueWizardChoice(action, value) {
1125
+ queueMicrotask(() => {
1126
+ const buttons = issueWizardPage(issueWizardState.step)?.querySelectorAll(`[data-issue-wizard-action="${action}"]`) || [];
1127
+ const target = Array.from(buttons).find((button) => button.dataset.issueWizardValue === value);
1128
+ target?.focus({ preventScroll: true });
1129
+ });
1130
+ }
1131
+
1132
+ function focusIssueWizardPage() {
1133
+ queueMicrotask(() => {
1134
+ const page = issueWizardPage(issueWizardState.step);
1135
+ const target = page?.querySelector('[aria-pressed="true"], button, select, textarea');
1136
+ target?.focus({ preventScroll: true });
1137
+ });
1138
+ }
1139
+
1140
+ function renderIssueWizardChoices(page, items, { selectedId, action, group, emptyMessage }) {
1141
+ const choices = make("div", "issue-wizard-choice-grid");
1142
+ choices.setAttribute("role", "group");
1143
+ choices.setAttribute("aria-label", group);
1144
+ if (!items.length) {
1145
+ choices.append(make("p", "issue-wizard-empty muted", emptyMessage));
1146
+ } else {
1147
+ for (const item of items) {
1148
+ const preview = action === "select-template" && item.fields?.length
1149
+ ? `Includes: ${item.fields.map((field) => field.label).join(" · ")}`
1150
+ : "";
1151
+ const button = issueWizardChoiceButton({ label: item.label, description: item.description, preview, selected: item.id === selectedId, action, value: item.id, group });
1152
+ button.addEventListener("click", () => {
1153
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: action, [`${action.split("-")[1]}Id`]: item.id }, issueWizardCatalog);
1154
+ renderIssueWizard();
1155
+ focusIssueWizardChoice(action, item.id);
1156
+ });
1157
+ choices.append(button);
1158
+ }
1159
+ }
1160
+ page.append(choices);
1161
+ }
1162
+
1163
+ function renderIssueWizardDetails(page) {
1164
+ const template = issueWizardCatalog.templates.find((item) => item.id === issueWizardState.templateId);
1165
+ if (!template) {
1166
+ page.append(make("p", "issue-wizard-empty muted", "Choose a compatible template before adding details."));
1167
+ return;
1168
+ }
1169
+ const summary = make("textarea", "issue-wizard-textarea");
1170
+ summary.id = "issueWizardSummary";
1171
+ summary.rows = 2;
1172
+ summary.maxLength = 160;
1173
+ summary.value = issueWizardState.summary;
1174
+ summary.placeholder = "Short summary";
1175
+ summary.setAttribute("aria-describedby", "issueWizardSummaryHint");
1176
+ summary.addEventListener("input", () => {
1177
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-summary", summary: summary.value }, issueWizardCatalog);
1178
+ renderIssueWizardNavigation();
1179
+ });
1180
+ const summaryLabel = make("label", "issue-wizard-field");
1181
+ summaryLabel.htmlFor = summary.id;
1182
+ summaryLabel.append(make("span", "issue-wizard-field-label", "Short summary"), summary, make("small", "muted", "Required. This completes the GitHub issue title."));
1183
+ summaryLabel.lastElementChild.id = "issueWizardSummaryHint";
1184
+ page.append(summaryLabel);
1185
+
1186
+ for (const field of template.fields) {
1187
+ const fieldWrap = make("div", "issue-wizard-field");
1188
+ const label = make("span", "issue-wizard-field-label", field.label);
1189
+ label.id = `issueWizardFieldLabel-${field.id}`;
1190
+ fieldWrap.append(label);
1191
+ if (field.kind === "textarea") {
1192
+ const input = make("textarea", "issue-wizard-textarea");
1193
+ input.rows = 4;
1194
+ input.value = issueWizardState.fields[field.id] || "";
1195
+ input.setAttribute("aria-labelledby", label.id);
1196
+ input.addEventListener("input", () => {
1197
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-field", fieldId: field.id, value: input.value }, issueWizardCatalog);
1198
+ renderIssueWizardNavigation();
1199
+ });
1200
+ fieldWrap.append(input);
1201
+ } else if (field.kind === "select") {
1202
+ const select = make("select", "issue-wizard-select");
1203
+ select.setAttribute("aria-labelledby", label.id);
1204
+ const placeholder = make("option", undefined, "Choose one…");
1205
+ placeholder.value = "";
1206
+ select.append(placeholder);
1207
+ for (const option of field.options || []) {
1208
+ const item = make("option", undefined, option.label);
1209
+ item.value = option.id;
1210
+ item.selected = issueWizardState.fields[field.id] === option.id;
1211
+ select.append(item);
1212
+ }
1213
+ select.addEventListener("change", () => {
1214
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-field", fieldId: field.id, value: select.value }, issueWizardCatalog);
1215
+ renderIssueWizardNavigation();
1216
+ });
1217
+ fieldWrap.append(select);
1218
+ } else {
1219
+ const choices = make("div", "issue-wizard-inline-choices");
1220
+ choices.setAttribute("role", "group");
1221
+ choices.setAttribute("aria-labelledby", label.id);
1222
+ for (const option of field.options || []) {
1223
+ const button = issueWizardChoiceButton({ label: option.label, selected: issueWizardState.fields[field.id] === option.id, action: "set-field", value: option.id, group: field.label });
1224
+ button.addEventListener("click", () => {
1225
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "set-field", fieldId: field.id, value: option.id }, issueWizardCatalog);
1226
+ renderIssueWizard();
1227
+ focusIssueWizardChoice("set-field", option.id);
1228
+ });
1229
+ choices.append(button);
1230
+ }
1231
+ fieldWrap.append(choices);
1232
+ }
1233
+ page.append(fieldWrap);
1234
+ }
1235
+ }
1236
+
1237
+ function renderIssueWizardReview(page) {
1238
+ let payload;
1239
+ try {
1240
+ payload = buildIssuePayload(issueWizardState, issueWizardCatalog);
1241
+ } catch {
1242
+ page.append(make("p", "issue-wizard-empty muted", "Complete the required details to preview the issue."));
1243
+ return;
1244
+ }
1245
+ const title = make("textarea", "issue-wizard-preview-title");
1246
+ title.readOnly = true;
1247
+ title.rows = 2;
1248
+ title.value = payload.title;
1249
+ title.setAttribute("aria-label", "GitHub issue title preview");
1250
+ const body = make("textarea", "issue-wizard-preview-body");
1251
+ body.readOnly = true;
1252
+ body.rows = 12;
1253
+ body.value = payload.body;
1254
+ body.setAttribute("aria-label", "GitHub issue Markdown body preview");
1255
+ const titleWrap = make("label", "issue-wizard-preview");
1256
+ titleWrap.append(make("span", "issue-wizard-field-label", "GitHub issue title"), title);
1257
+ const bodyWrap = make("label", "issue-wizard-preview");
1258
+ bodyWrap.append(make("span", "issue-wizard-field-label", "GitHub issue Markdown body"), body);
1259
+ page.append(titleWrap, bodyWrap);
1260
+ }
1261
+
1262
+ function issueBotMessage(result) {
1263
+ if (result?.phase === "admitting") return "Verifying bot protection and submitting the structured report…";
1264
+ switch (result?.status) {
1265
+ case "queued": return result.timedOut ? "The report is still queued. Refresh status when you are ready." : "The report is queued for automated checks…";
1266
+ case "checking": return result.timedOut ? "The report is still being checked. Refresh status when you are ready." : "The report is being checked…";
1267
+ case "created": return `GitHub issue #${result.issueNumber} was created.`;
1268
+ case "rejected": return "This report was not accepted for automated public issue creation. You can still copy it and create an issue manually.";
1269
+ case "review": return "This report needs manual review and was not published automatically. You can still copy it and create an issue manually.";
1270
+ case "unknown": return "The creation result is unknown; no further automatic issue creation will be attempted. You can copy the issue instead.";
1271
+ default: return "Automated submission is unavailable. You can still copy the complete issue.";
1272
+ }
1273
+ }
1274
+
1275
+ function renderIssueWizardSubmissionStatus() {
1276
+ const result = issueBotSubmissionResult;
1277
+ if (elements.issueWizardSubmissionStatus) elements.issueWizardSubmissionStatus.hidden = !result;
1278
+ if (elements.issueWizardSubmissionMessage) elements.issueWizardSubmissionMessage.textContent = result ? issueBotMessage(result) : "";
1279
+ const created = result?.status === "created" && typeof result.issueUrl === "string";
1280
+ if (elements.issueWizardSubmissionLink) {
1281
+ elements.issueWizardSubmissionLink.hidden = !created;
1282
+ elements.issueWizardSubmissionLink.href = created ? result.issueUrl : "";
1283
+ elements.issueWizardSubmissionLink.textContent = created ? "View confirmed GitHub issue" : "";
1284
+ }
1285
+ const showRefresh = !!result?.timedOut && !!issueBotSubmissionHandle;
1286
+ if (elements.issueWizardRefreshButton) {
1287
+ elements.issueWizardRefreshButton.hidden = !showRefresh;
1288
+ elements.issueWizardRefreshButton.disabled = issueBotRequestActive;
1289
+ }
1290
+ const sensitive = result?.reasonCode === "sensitive_content";
1291
+ const hasPrivateReportUrl = !!issueBotRuntimeConfig.privateSecurityReportUrl;
1292
+ if (elements.issueWizardSecurityGuidance) elements.issueWizardSecurityGuidance.hidden = !sensitive || !hasPrivateReportUrl;
1293
+ if (elements.issueWizardSecurityLink) {
1294
+ elements.issueWizardSecurityLink.hidden = !sensitive || !hasPrivateReportUrl;
1295
+ elements.issueWizardSecurityLink.href = sensitive && hasPrivateReportUrl ? issueBotRuntimeConfig.privateSecurityReportUrl : "";
1296
+ }
1297
+ }
1298
+
1299
+ function renderIssueWizardNavigation() {
1300
+ const step = issueWizardState.step;
1301
+ const botAvailable = !!issueBotClient?.available;
1302
+ if (elements.issueWizardProgress) elements.issueWizardProgress.textContent = `Step ${step} of 5`;
1303
+ if (elements.issueWizardBackButton) elements.issueWizardBackButton.disabled = step === 1 || issueBotRequestActive;
1304
+ if (elements.issueWizardContinueButton) {
1305
+ elements.issueWizardContinueButton.hidden = step === 5;
1306
+ elements.issueWizardContinueButton.disabled = issueBotRequestActive || !isIssueWizardStepValid(issueWizardState, issueWizardCatalog, step);
1307
+ elements.issueWizardContinueButton.textContent = step === 4 ? "Review issue" : "Continue";
1308
+ }
1309
+ if (elements.issueWizardCopyButton) elements.issueWizardCopyButton.hidden = step !== 5;
1310
+ if (elements.issueWizardBotButton) {
1311
+ elements.issueWizardBotButton.hidden = step !== 5;
1312
+ elements.issueWizardBotButton.disabled = !botAvailable || issueBotRequestActive;
1313
+ elements.issueWizardBotButton.textContent = issueBotRequestActive ? "Checking issue status…" : "Send";
1314
+ }
1315
+ if (elements.issueWizardBotHint) {
1316
+ elements.issueWizardBotHint.hidden = step !== 5;
1317
+ elements.issueWizardBotHint.textContent = botAvailable
1318
+ ? "The bot submits only the structured wizard state. Keep private security details out of public reports."
1319
+ : "Automated submission is not enabled. Copy the issue and create it manually instead.";
1320
+ }
1321
+ renderIssueWizardSubmissionStatus();
1322
+ setIssueWizardStatus(`Step ${step} of 5.`);
1323
+ }
1324
+
1325
+ function renderIssueWizard() {
1326
+ if (!issueWizardCatalog || !elements.issueWizardPages) return;
1327
+ for (let step = 1; step <= 5; step += 1) {
1328
+ const page = issueWizardPage(step);
1329
+ if (!page) continue;
1330
+ page.hidden = step !== issueWizardState.step;
1331
+ page.replaceChildren();
1332
+ }
1333
+ const page = issueWizardPage(issueWizardState.step);
1334
+ if (!page) return;
1335
+ if (issueWizardState.step === 1) {
1336
+ page.append(make("p", "issue-wizard-intro", "What kind of issue would you like to report?"));
1337
+ renderIssueWizardChoices(page, issueWizardCatalog.categories, { selectedId: issueWizardState.categoryId, action: "select-category", group: "Issue category", emptyMessage: "No categories are available." });
1338
+ } else if (issueWizardState.step === 2) {
1339
+ page.append(make("p", "issue-wizard-intro", "Which part of Pi Web UI is affected?"));
1340
+ renderIssueWizardChoices(page, issueWizardCatalog.components, { selectedId: issueWizardState.componentId, action: "select-component", group: "Affected component", emptyMessage: "No components are available." });
1341
+ } else if (issueWizardState.step === 3) {
1342
+ page.append(make("p", "issue-wizard-intro", "Choose the structured template that best matches this issue."));
1343
+ renderIssueWizardChoices(page, getCompatibleTemplates(issueWizardCatalog, issueWizardState.categoryId, issueWizardState.componentId), { selectedId: issueWizardState.templateId, action: "select-template", group: "Issue template", emptyMessage: "Choose a category and component first." });
1344
+ } else if (issueWizardState.step === 4) {
1345
+ page.append(make("p", "issue-wizard-intro", "Add the details needed for a clear, actionable issue."));
1346
+ renderIssueWizardDetails(page);
1347
+ } else {
1348
+ page.append(make("p", "issue-wizard-intro", "Review the exact GitHub title and Markdown body before copying or submitting."));
1349
+ renderIssueWizardReview(page);
1350
+ }
1351
+ renderIssueWizardNavigation();
1352
+ }
1353
+
1354
+ async function copyIssueWizardPayload() {
1355
+ try {
1356
+ const payload = buildIssuePayload(issueWizardState, issueWizardCatalog);
1357
+ await copyText(issueClipboardText(payload));
1358
+ setIssueWizardStatus("Complete issue copied. Paste it into a new GitHub issue.");
1359
+ } catch {
1360
+ setIssueWizardStatus("Could not copy the issue. Select the preview text and copy it manually.");
1361
+ }
1362
+ }
1363
+
1364
+ function structuredIssueWizardState() {
1365
+ return {
1366
+ categoryId: issueWizardState.categoryId,
1367
+ componentId: issueWizardState.componentId,
1368
+ templateId: issueWizardState.templateId,
1369
+ summary: issueWizardState.summary,
1370
+ fields: { ...issueWizardState.fields },
1371
+ };
1372
+ }
1373
+
1374
+ function reportIssueBotStatus(result) {
1375
+ issueBotSubmissionResult = result;
1376
+ renderIssueWizardSubmissionStatus();
1377
+ }
1378
+
1379
+ function clearIssueBotSubmission({ abort = false } = {}) {
1380
+ if (abort) issueBotAbortController?.abort();
1381
+ issueBotAbortController = null;
1382
+ issueBotSubmissionHandle = null;
1383
+ issueBotSubmissionResult = null;
1384
+ issueBotRequestActive = false;
1385
+ elements.issueWizardTurnstile?.replaceChildren();
1386
+ renderIssueWizardSubmissionStatus();
1387
+ }
1388
+
1389
+ async function sendIssueToGithubBot() {
1390
+ if (!issueBotClient?.available || issueBotRequestActive) return;
1391
+ try {
1392
+ // Preserve the existing canonical builder as the review/copy authority, but never send title/body to the gateway.
1393
+ buildIssuePayload(issueWizardState, issueWizardCatalog);
1394
+ } catch {
1395
+ setIssueWizardStatus("Complete the required wizard details before submitting.");
1396
+ return;
1397
+ }
1398
+ const controller = new AbortController();
1399
+ issueBotAbortController = controller;
1400
+ issueBotRequestActive = true;
1401
+ issueBotSubmissionHandle = null;
1402
+ reportIssueBotStatus(Object.freeze({ status: "checking", phase: "admitting" }));
1403
+ renderIssueWizardNavigation();
1404
+ try {
1405
+ const submission = await issueBotClient.submit({
1406
+ issue: structuredIssueWizardState(),
1407
+ signal: controller.signal,
1408
+ onStatus: reportIssueBotStatus,
1409
+ });
1410
+ if (controller.signal.aborted || issueBotAbortController !== controller) return;
1411
+ issueBotSubmissionHandle = submission.handle;
1412
+ reportIssueBotStatus(submission.result);
1413
+ } catch (error) {
1414
+ if (error?.name !== "AbortError" && issueBotAbortController === controller) {
1415
+ reportIssueBotStatus(Object.freeze({ ok: false, status: "unavailable", reasonCode: "unavailable" }));
1416
+ }
1417
+ } finally {
1418
+ if (issueBotAbortController !== controller) return;
1419
+ issueBotAbortController = null;
1420
+ issueBotRequestActive = false;
1421
+ renderIssueWizardNavigation();
1422
+ }
1423
+ }
1424
+
1425
+ async function refreshIssueBotStatus() {
1426
+ if (!issueBotSubmissionHandle || issueBotRequestActive) return;
1427
+ const controller = new AbortController();
1428
+ issueBotAbortController = controller;
1429
+ issueBotRequestActive = true;
1430
+ renderIssueWizardNavigation();
1431
+ try {
1432
+ const result = await issueBotSubmissionHandle.refresh({ signal: controller.signal, onStatus: reportIssueBotStatus });
1433
+ if (!controller.signal.aborted && issueBotAbortController === controller) reportIssueBotStatus(result);
1434
+ } catch (error) {
1435
+ if (error?.name !== "AbortError" && issueBotAbortController === controller) {
1436
+ reportIssueBotStatus(Object.freeze({ ok: false, status: "unavailable", reasonCode: "unavailable" }));
1437
+ }
1438
+ } finally {
1439
+ if (issueBotAbortController !== controller) return;
1440
+ issueBotAbortController = null;
1441
+ issueBotRequestActive = false;
1442
+ renderIssueWizardNavigation();
1443
+ }
1444
+ }
1445
+
1446
+ function initializeIssueWizard() {
1447
+ if (!elements.openIssueButton || !elements.issueWizardDialog) return;
1448
+ issueWizardCatalog = createIssueWizardCatalog(OPTIONAL_FEATURES.map((feature) => feature.label));
1449
+ issueBotClient = createIssueBotClient({ config: issueBotRuntimeConfig, turnstileContainer: elements.issueWizardTurnstile });
1450
+ elements.openIssueButton.addEventListener("click", () => {
1451
+ clearIssueBotSubmission({ abort: true });
1452
+ issueWizardState = createIssueWizardState();
1453
+ renderIssueWizard();
1454
+ if (!elements.issueWizardDialog.open) elements.issueWizardDialog.showModal();
1455
+ queueMicrotask(() => issueWizardPage(1)?.querySelector("button")?.focus({ preventScroll: true }));
1456
+ });
1457
+ elements.issueWizardCloseButton?.addEventListener("click", () => elements.issueWizardDialog.close());
1458
+ elements.issueWizardDialog.addEventListener("close", () => clearIssueBotSubmission({ abort: true }));
1459
+ elements.issueWizardBackButton?.addEventListener("click", () => {
1460
+ if (issueBotRequestActive) return;
1461
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "back" }, issueWizardCatalog);
1462
+ renderIssueWizard();
1463
+ focusIssueWizardPage();
1464
+ });
1465
+ elements.issueWizardContinueButton?.addEventListener("click", () => {
1466
+ if (issueBotRequestActive) return;
1467
+ issueWizardState = reduceIssueWizardState(issueWizardState, { type: "next" }, issueWizardCatalog);
1468
+ renderIssueWizard();
1469
+ focusIssueWizardPage();
1470
+ });
1471
+ elements.issueWizardCopyButton?.addEventListener("click", () => copyIssueWizardPayload());
1472
+ elements.issueWizardBotButton?.addEventListener("click", () => sendIssueToGithubBot());
1473
+ elements.issueWizardRefreshButton?.addEventListener("click", () => refreshIssueBotStatus());
1474
+ }
1052
1475
  const OPTIONAL_FEATURE_SECTIONS = [
1053
1476
  {
1054
1477
  id: "composer-commands",
@@ -1096,6 +1519,7 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
1096
1519
  ["aur-review", "aurReview"],
1097
1520
  ["workflow", "workflows"],
1098
1521
  ["workflow-clear", "workflows"],
1522
+ ["workflow-setup", "workflows"],
1099
1523
  ["safety-guard", "safetyGuard"],
1100
1524
  ["safety-guard-setup", "safetyGuard"],
1101
1525
  ["skills", "tuiSkillsCommand"],
@@ -1113,7 +1537,7 @@ const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
1113
1537
  HIDDEN_COMMAND_NAMES.add("stats-webui");
1114
1538
  HIDDEN_COMMAND_NAMES.add("btw-status");
1115
1539
  HIDDEN_COMMAND_NAMES.add("btw-transfer");
1116
- const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
1540
+ const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "workflow-setup", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
1117
1541
  const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
1118
1542
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
1119
1543
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
@@ -1143,6 +1567,9 @@ const optionalFeatureInstallStates = new Map();
1143
1567
  const optionalFeatureInstallProgressTimers = new Map();
1144
1568
  let optionalFeaturePackageStatusError = "";
1145
1569
  const gitFooterPayloadRefreshInFlightByTab = new Set();
1570
+ const gitFooterPayloadStateByTab = new Map();
1571
+ const gitFooterPayloadSettlementTimersByTab = new Map();
1572
+ const gitFooterPayloadRequestSerialByTab = new Map();
1146
1573
  const gitFooterSyncPushInFlightByTab = new Set();
1147
1574
  const gitFooterPiCalibrationInFlightByTab = new Set();
1148
1575
  let gitFooterVisibilityApplyInFlight = false;
@@ -3623,9 +4050,12 @@ function triggerNativeDownload(download) {
3623
4050
  anchor.rel = "noopener";
3624
4051
  anchor.hidden = true;
3625
4052
  document.body.append(anchor);
3626
- anchor.click();
3627
- anchor.remove();
3628
- return true;
4053
+ try {
4054
+ anchor.click();
4055
+ return true;
4056
+ } finally {
4057
+ anchor.remove();
4058
+ }
3629
4059
  }
3630
4060
 
3631
4061
  function isStandalonePwaWindow() {
@@ -3673,9 +4103,12 @@ function openNativeDownloadInBrowser(download) {
3673
4103
  anchor.rel = "noopener";
3674
4104
  anchor.hidden = true;
3675
4105
  document.body.append(anchor);
3676
- anchor.click();
3677
- anchor.remove();
3678
- return true;
4106
+ try {
4107
+ anchor.click();
4108
+ return true;
4109
+ } finally {
4110
+ anchor.remove();
4111
+ }
3679
4112
  }
3680
4113
 
3681
4114
  function openNativeExportDownloadPrompt(download, serverPath = "") {
@@ -5114,6 +5547,7 @@ function workflowOverlayHasContent() {
5114
5547
  if (!isOptionalFeatureEnabled("workflows")) return false;
5115
5548
  const inspector = activeWorkflowInspectorPayload();
5116
5549
  if (inspector?.runs?.length) return true;
5550
+ if (getWidgetLines("workflow").length) return true;
5117
5551
  return !!parseWorkflowSubprocessPayload(getWidgetLines("workflow:subprocess"));
5118
5552
  }
5119
5553
 
@@ -5123,7 +5557,11 @@ function workflowOverlayIsMinimized() {
5123
5557
 
5124
5558
  function renderWorkflowOverlayControls() {
5125
5559
  const openAvailable = workflowOverlayHasContent() && workflowOverlayIsMinimized();
5126
- if (elements.workflowOverlayOpenButton) elements.workflowOverlayOpenButton.hidden = !openAvailable;
5560
+ if (elements.workflowOverlayOpenButton) {
5561
+ elements.workflowOverlayOpenButton.hidden = !openAvailable;
5562
+ elements.workflowOverlayOpenButton.setAttribute("aria-expanded", openAvailable ? "false" : "true");
5563
+ applyStyledTooltip(elements.workflowOverlayOpenButton, "Open the minimized workflow overlay.", { ariaLabel: true, align: "end" });
5564
+ }
5127
5565
  if (elements.workflowModeControls) {
5128
5566
  elements.workflowModeControls.hidden = Boolean(elements.workflowModeButton?.hidden) && !openAvailable;
5129
5567
  elements.workflowModeControls.classList.toggle("has-open-control", openAvailable);
@@ -5160,13 +5598,14 @@ function renderWorkflowModeControls() {
5160
5598
  elements.workflowModeButton.disabled = !commandName || pending;
5161
5599
  elements.workflowModeButton.classList.toggle("active", active);
5162
5600
  elements.workflowModeButton.setAttribute("aria-pressed", active ? "true" : "false");
5163
- elements.workflowModeButton.toggleAttribute("aria-busy", pending);
5601
+ if (pending) elements.workflowModeButton.setAttribute("aria-busy", "true");
5602
+ else elements.workflowModeButton.removeAttribute("aria-busy");
5164
5603
  const tooltip = pending
5165
5604
  ? "Updating JavaScript Workflow Mode for this Pi tab."
5166
5605
  : commandName
5167
5606
  ? `${active ? "Disable" : "Enable"} JavaScript Workflow Mode for this Pi tab via /${commandName} mode ${active ? "off" : "on"}.`
5168
5607
  : "Workflow Mode is unavailable because the /workflow command is not loaded.";
5169
- applyStyledTooltip(elements.workflowModeButton, tooltip, { ariaLabel: true, align: "start", floating: false });
5608
+ applyStyledTooltip(elements.workflowModeButton, tooltip, { ariaLabel: true, align: "end" });
5170
5609
  }
5171
5610
  renderWorkflowOverlayControls();
5172
5611
 
@@ -5907,6 +6346,7 @@ function setOptionalFeatureDisabled(featureId, disabled) {
5907
6346
  if (featureId === "gitFooterStatus") {
5908
6347
  statusEntries.delete(GIT_FOOTER_WEBUI_STATUS_KEY);
5909
6348
  clearGitFooterWebuiPayloadCache();
6349
+ for (const tabId of new Set([...gitFooterPayloadStateByTab.keys(), ...gitFooterPayloadSettlementTimersByTab.keys(), ...gitFooterPayloadRefreshInFlightByTab])) clearGitFooterPayloadState(tabId);
5910
6350
  }
5911
6351
  if (featureId === "btwCommand") {
5912
6352
  statusEntries.delete(BTW_WEBUI_STATUS_KEY);
@@ -7189,6 +7629,8 @@ function updateActiveFileViewerAfterMove(sourcePath = "", destinationPath = "")
7189
7629
  extension: fileExtensionForPath(nextPath),
7190
7630
  language,
7191
7631
  mode: activeFileViewer.mode === "preview" && language === "markdown" ? "preview" : "source",
7632
+ // The open-time diff snapshot belongs to the previous path.
7633
+ gitChanges: null,
7192
7634
  };
7193
7635
  if (fileViewerSelection) fileViewerSelection = { ...fileViewerSelection, path: nextPath, fileName: activeFileViewer.name };
7194
7636
  updateFileViewerUi();
@@ -7594,10 +8036,21 @@ async function openFileTreeEntryInWebui(entry = fileContextMenuState?.entry) {
7594
8036
  await openFileInViewer(path);
7595
8037
  }
7596
8038
 
8039
+ // Changes mode only exists for Git-originated opens; every other viewer keeps
8040
+ // the original Source/Markdown-Preview behavior.
8041
+ function resolveFileViewerMode(viewer) {
8042
+ if (!viewer) return "source";
8043
+ const hasChanges = !!viewer.gitChanges;
8044
+ if (viewer.mode === "changes") return hasChanges ? "changes" : "source";
8045
+ if (viewer.sourceAvailable === false) return hasChanges ? "changes" : "source";
8046
+ return viewer.mode === "preview" && viewer.language === "markdown" ? "preview" : "source";
8047
+ }
8048
+
7597
8049
  function setFileViewerMode(mode = "source") {
7598
8050
  if (!activeFileViewer) return;
7599
- const nextMode = mode === "preview" && activeFileViewer.language === "markdown" ? "preview" : "source";
7600
- activeFileViewer.mode = nextMode;
8051
+ const previousMode = activeFileViewer.mode;
8052
+ activeFileViewer.mode = resolveFileViewerMode({ ...activeFileViewer, mode });
8053
+ if (activeFileViewer.mode === "changes" && previousMode !== "changes") clearFileViewerSelection();
7601
8054
  updateFileViewerUi();
7602
8055
  }
7603
8056
 
@@ -7618,20 +8071,31 @@ function updateFileViewerUi() {
7618
8071
  if (!isSidePanelOverlayView()) applyFileViewerWidth(currentFileViewerWidth());
7619
8072
  const viewer = activeFileViewer;
7620
8073
  const isMarkdown = viewer.language === "markdown";
7621
- const mode = viewer.mode === "preview" && isMarkdown ? "preview" : "source";
8074
+ const hasChanges = !!viewer.gitChanges;
8075
+ const sourceAvailable = viewer.sourceAvailable !== false;
8076
+ const mode = resolveFileViewerMode(viewer);
7622
8077
  viewer.mode = mode;
7623
8078
  if (elements.fileViewerTitle) elements.fileViewerTitle.textContent = viewer.name || fileDisplayName(viewer.path);
7624
8079
  if (elements.fileViewerMeta) {
7625
8080
  const lineCount = textLineCount(viewer.content || "");
7626
- elements.fileViewerMeta.textContent = [viewer.path, formatBytes(viewer.size), `${lineCount} ${lineCount === 1 ? "line" : "lines"}`].filter(Boolean).join(" · ");
8081
+ const sourceMeta = sourceAvailable ? [formatBytes(viewer.size), `${lineCount} ${lineCount === 1 ? "line" : "lines"}`] : ["source unavailable"];
8082
+ elements.fileViewerMeta.textContent = [viewer.path, ...sourceMeta].filter(Boolean).join(" · ");
8083
+ }
8084
+ if (elements.fileViewerChangesModeButton) {
8085
+ elements.fileViewerChangesModeButton.hidden = !hasChanges;
8086
+ elements.fileViewerChangesModeButton.disabled = !hasChanges;
8087
+ elements.fileViewerChangesModeButton.setAttribute("aria-pressed", mode === "changes" ? "true" : "false");
8088
+ elements.fileViewerChangesModeButton.classList.toggle("active", mode === "changes");
8089
+ elements.fileViewerChangesModeButton.title = hasChanges ? `${viewer.gitChanges.label || "Git"} changes for this file` : "";
7627
8090
  }
7628
8091
  if (elements.fileViewerSourceModeButton) {
8092
+ elements.fileViewerSourceModeButton.disabled = !sourceAvailable;
7629
8093
  elements.fileViewerSourceModeButton.setAttribute("aria-pressed", mode === "source" ? "true" : "false");
7630
8094
  elements.fileViewerSourceModeButton.classList.toggle("active", mode === "source");
7631
8095
  }
7632
8096
  if (elements.fileViewerPreviewModeButton) {
7633
8097
  elements.fileViewerPreviewModeButton.hidden = !isMarkdown;
7634
- elements.fileViewerPreviewModeButton.disabled = !isMarkdown;
8098
+ elements.fileViewerPreviewModeButton.disabled = !isMarkdown || !sourceAvailable;
7635
8099
  elements.fileViewerPreviewModeButton.setAttribute("aria-pressed", mode === "preview" ? "true" : "false");
7636
8100
  elements.fileViewerPreviewModeButton.classList.toggle("active", mode === "preview");
7637
8101
  }
@@ -7644,6 +8108,11 @@ function updateFileViewerUi() {
7644
8108
  elements.fileViewerPreview.hidden = mode !== "preview";
7645
8109
  if (mode === "preview") renderMarkdown(elements.fileViewerPreview, viewer.content || "");
7646
8110
  }
8111
+ if (elements.fileViewerChanges) {
8112
+ elements.fileViewerChanges.hidden = mode !== "changes";
8113
+ if (mode === "changes") renderFileViewerChanges(viewer.gitChanges);
8114
+ else elements.fileViewerChanges.replaceChildren();
8115
+ }
7647
8116
  if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = viewer.readOnly === true || !viewer.dirty;
7648
8117
  if (elements.fileViewerOpenDefaultButton) {
7649
8118
  const viewerPath = normalizeFileTreePath(viewer.path || "");
@@ -7653,6 +8122,75 @@ function updateFileViewerUi() {
7653
8122
  renderFileViewerSelectionBar();
7654
8123
  }
7655
8124
 
8125
+ function fileViewerChangesNotice(text, level = "") {
8126
+ return make("p", `file-viewer-changes-notice ${level}`.trim(), text);
8127
+ }
8128
+
8129
+ function fileViewerChangesHeading(snapshot) {
8130
+ const heading = make("div", "git-diff-section-heading");
8131
+ heading.append(
8132
+ make("div", "git-diff-section-title", `${snapshot.label || "Git"} changes`),
8133
+ make("div", "git-diff-section-meta", snapshot.command || "git diff"),
8134
+ );
8135
+ return heading;
8136
+ }
8137
+
8138
+ // git diff --cc emits combined "@@@" hunks that the two-column parser cannot
8139
+ // represent, so those diffs fall back to readable raw text.
8140
+ function gitFileDiffUsesCombinedSyntax(diffText = "") {
8141
+ return /^@@@+ /m.test(String(diffText || ""));
8142
+ }
8143
+
8144
+ function renderFileViewerUntrackedChanges(snapshot) {
8145
+ const entry = normalizeGitUntrackedEntry({
8146
+ path: snapshot.path || "file",
8147
+ size: snapshot.size,
8148
+ binary: snapshot.binary,
8149
+ error: snapshot.contentError,
8150
+ ...(typeof snapshot.content === "string" ? { content: snapshot.content } : {}),
8151
+ });
8152
+ if (!entry) return fileViewerChangesNotice("Untracked file content is unavailable.", "error");
8153
+ if (entry.contentMissing) return fileViewerChangesNotice("Untracked file content is unavailable.", "error");
8154
+ if (entry.error || entry.binary) return renderGitUntrackedRawFile(entry);
8155
+ return renderGitDiffFile(gitUntrackedEntryToDiffFile(entry));
8156
+ }
8157
+
8158
+ function renderFileViewerTrackedChanges(snapshot) {
8159
+ const diff = String(snapshot.diff || "");
8160
+ if (!diff.trim()) return fileViewerChangesNotice(`No ${String(snapshot.label || "Git").toLowerCase()} changes for this file.`);
8161
+ if (gitFileDiffUsesCombinedSyntax(diff)) return make("pre", "git-diff-raw", diff);
8162
+ const files = parseGitUnifiedDiff(diff);
8163
+ if (!files.length) return make("pre", "git-diff-raw", diff);
8164
+ const fragment = document.createDocumentFragment();
8165
+ for (const file of files) fragment.append(renderGitDiffFile(file));
8166
+ return fragment;
8167
+ }
8168
+
8169
+ function renderFileViewerChangesTruncation(snapshot) {
8170
+ const notice = make("div", "git-diff-truncated-notice");
8171
+ notice.append(make("span", undefined, `Diff truncated at ${formatBytes(snapshot.capBytes || 0)} — showing the bounded snapshot. Run the full command in a terminal for the complete diff:`));
8172
+ notice.append(make("code", "git-tools-command", snapshot.command || "git diff"));
8173
+ return notice;
8174
+ }
8175
+
8176
+ function renderFileViewerChanges(snapshot = activeFileViewer?.gitChanges) {
8177
+ const container = elements.fileViewerChanges;
8178
+ if (!container) return;
8179
+ if (!snapshot) {
8180
+ container.replaceChildren();
8181
+ return;
8182
+ }
8183
+ const wrapper = make("section", `git-diff-section file-viewer-changes-section ${snapshot.category || ""}`.trim());
8184
+ wrapper.append(fileViewerChangesHeading(snapshot));
8185
+ if (snapshot.loading) wrapper.append(fileViewerChangesNotice("Loading Git changes…"));
8186
+ else if (snapshot.error) wrapper.append(fileViewerChangesNotice(snapshot.error, "error"));
8187
+ else {
8188
+ wrapper.append(snapshot.category === "untracked" ? renderFileViewerUntrackedChanges(snapshot) : renderFileViewerTrackedChanges(snapshot));
8189
+ if (snapshot.truncated) wrapper.append(renderFileViewerChangesTruncation(snapshot));
8190
+ }
8191
+ container.replaceChildren(wrapper);
8192
+ }
8193
+
7656
8194
  function clearFileViewerSelection() {
7657
8195
  fileViewerSelection = null;
7658
8196
  renderFileViewerSelectionBar();
@@ -7774,6 +8312,7 @@ async function sendFileSelectionToSession() {
7774
8312
  }
7775
8313
 
7776
8314
  function closeFileViewer() {
8315
+ fileViewerOpenRequestSerial += 1;
7777
8316
  activeFileViewer = null;
7778
8317
  clearFileViewerSelection();
7779
8318
  document.body.classList.remove("file-viewer-open");
@@ -7786,20 +8325,80 @@ function closeFileViewer() {
7786
8325
  elements.fileViewerEditor.readOnly = false;
7787
8326
  }
7788
8327
  if (elements.fileViewerPreview) elements.fileViewerPreview.replaceChildren();
8328
+ if (elements.fileViewerChanges) {
8329
+ elements.fileViewerChanges.hidden = true;
8330
+ elements.fileViewerChanges.replaceChildren();
8331
+ }
7789
8332
  setFileViewerStatus("");
7790
8333
  }
7791
8334
 
7792
- async function openFileInViewer(path = "") {
8335
+ // Side-panel Git categories are UI labels; the read API uses its own allowlist.
8336
+ const GIT_FILE_DIFF_CATEGORY_BY_PANEL = Object.freeze({
8337
+ staged: "staged",
8338
+ changes: "unstaged",
8339
+ conflicted: "conflicted",
8340
+ untracked: "untracked",
8341
+ });
8342
+
8343
+ function gitFileDiffCategory(panelCategory = "") {
8344
+ return GIT_FILE_DIFF_CATEGORY_BY_PANEL[String(panelCategory || "").trim()] || "";
8345
+ }
8346
+
8347
+ // The changes view is the bounded snapshot loaded when the file was opened;
8348
+ // reopening the Git row refreshes it. Failures become a visible viewer state
8349
+ // instead of a rejected open.
8350
+ async function loadGitFileChangesSnapshot(repoRelPath, category, tabId) {
8351
+ const snapshot = { category, path: repoRelPath, label: "", command: "", diff: "", truncated: false, capBytes: 0, error: "" };
8352
+ try {
8353
+ const params = new URLSearchParams({ path: repoRelPath, category });
8354
+ const response = await api(`/api/git-file-diff?${params.toString()}`, { tabId });
8355
+ if (!response.ok) throw new Error(response.error || "Failed to load Git changes for this file");
8356
+ const data = response.data || {};
8357
+ return {
8358
+ ...snapshot,
8359
+ ...data,
8360
+ category,
8361
+ path: data.path || repoRelPath,
8362
+ diff: String(data.diff || ""),
8363
+ truncated: data.truncated === true,
8364
+ capBytes: Number(data.capBytes) || 0,
8365
+ contentError: data.error ? String(data.error) : "",
8366
+ error: "",
8367
+ };
8368
+ } catch (error) {
8369
+ return { ...snapshot, error: error.message || String(error) };
8370
+ }
8371
+ }
8372
+
8373
+ function gitFileChangesPlaceholder(category, repoRelPath, requestSerial) {
8374
+ return { category, path: repoRelPath, label: "", command: "", diff: "", truncated: false, capBytes: 0, loading: true, requestSerial, error: "" };
8375
+ }
8376
+
8377
+ async function applyGitFileChangesSnapshot(request, tabContext, viewerPath, requestSerial) {
8378
+ const snapshot = await request;
8379
+ if (!isCurrentTabContext(tabContext)) return;
8380
+ if (!activeFileViewer?.gitChanges?.loading || activeFileViewer.path !== viewerPath || activeFileViewer.gitChanges.requestSerial !== requestSerial) return;
8381
+ activeFileViewer.gitChanges = snapshot;
8382
+ updateFileViewerUi();
8383
+ }
8384
+
8385
+ async function openFileInViewer(path = "", { gitCategory = "", gitPath = "" } = {}) {
7793
8386
  const normalized = normalizeFileTreePath(path);
7794
8387
  if (!normalized) return;
8388
+ const openRequestSerial = ++fileViewerOpenRequestSerial;
7795
8389
  const tabContext = activeTabContext();
7796
8390
  fileTreeState.selectedPath = normalized;
7797
8391
  renderFileTree();
7798
8392
  setFileViewerStatus(`Opening ${normalized}…`);
8393
+ const category = gitFileDiffCategory(gitCategory);
8394
+ const changesPath = normalizeFileTreePath(gitPath) || normalized;
8395
+ const changesRequestSerial = category ? ++fileViewerGitChangesRequestSerial : 0;
8396
+ const changesRequest = category ? loadGitFileChangesSnapshot(changesPath, category, tabContext.tabId) : null;
7799
8397
  try {
7800
8398
  const response = await api(fileApiPath("/api/files/content", normalized), { tabId: tabContext.tabId });
7801
- if (!isCurrentTabContext(tabContext)) return;
8399
+ if (!isCurrentTabContext(tabContext) || openRequestSerial !== fileViewerOpenRequestSerial) return;
7802
8400
  const data = response.data || {};
8401
+ const gitChanges = changesRequest ? gitFileChangesPlaceholder(category, changesPath, changesRequestSerial) : null;
7803
8402
  activeFileViewer = {
7804
8403
  path: normalizeFileTreePath(data.path || normalized),
7805
8404
  name: data.name || fileDisplayName(normalized),
@@ -7808,19 +8407,45 @@ async function openFileInViewer(path = "") {
7808
8407
  mtimeMs: Number(data.mtimeMs) || 0,
7809
8408
  extension: data.extension || "",
7810
8409
  language: data.language || "text",
7811
- mode: data.language === "markdown" ? "preview" : "source",
8410
+ mode: gitChanges ? "changes" : data.language === "markdown" ? "preview" : "source",
7812
8411
  dirty: false,
7813
8412
  readOnly: false,
8413
+ sourceAvailable: true,
8414
+ gitChanges,
7814
8415
  };
7815
8416
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
7816
8417
  clearFileViewerSelection();
7817
8418
  updateFileViewerUi();
7818
8419
  setFileViewerStatus("Opened in WebUI.", "success");
8420
+ if (changesRequest) void applyGitFileChangesSnapshot(changesRequest, tabContext, activeFileViewer.path, changesRequestSerial);
7819
8421
  } catch (error) {
7820
- if (isCurrentTabContext(tabContext)) {
7821
- setFileViewerStatus(error.message || String(error), "error");
7822
- addEvent(`file open failed: ${error.message || String(error)}`, "error");
8422
+ const message = error.message || String(error);
8423
+ // A deleted tracked file has no live source but still has a diff worth showing.
8424
+ const gitChanges = changesRequest ? await changesRequest : null;
8425
+ if (!isCurrentTabContext(tabContext) || openRequestSerial !== fileViewerOpenRequestSerial) return;
8426
+ if (gitChanges && !gitChanges.error) {
8427
+ activeFileViewer = {
8428
+ path: normalized,
8429
+ name: fileDisplayName(normalized),
8430
+ content: "",
8431
+ size: 0,
8432
+ mtimeMs: 0,
8433
+ extension: fileExtensionForPath(normalized),
8434
+ language: fileLanguageForPath(normalized),
8435
+ mode: "changes",
8436
+ dirty: false,
8437
+ readOnly: true,
8438
+ sourceAvailable: false,
8439
+ gitChanges,
8440
+ };
8441
+ if (elements.fileViewerEditor) elements.fileViewerEditor.value = "";
8442
+ clearFileViewerSelection();
8443
+ updateFileViewerUi();
8444
+ setFileViewerStatus("File content unavailable; showing Git changes (read-only).", "warn");
8445
+ return;
7823
8446
  }
8447
+ setFileViewerStatus(message, "error");
8448
+ addEvent(`file open failed: ${message}`, "error");
7824
8449
  }
7825
8450
  }
7826
8451
 
@@ -7894,6 +8519,7 @@ function normalizeTabActivity(activity = {}) {
7894
8519
  ...activity,
7895
8520
  status,
7896
8521
  isWorking: status === "working",
8522
+ runStarted: activity.runStarted === true,
7897
8523
  completionSerial: Number.isFinite(completionSerial) ? completionSerial : 0,
7898
8524
  };
7899
8525
  }
@@ -7925,13 +8551,14 @@ function decrementTabPendingBlockerCount(tabId) {
7925
8551
  }
7926
8552
 
7927
8553
  function tabActivityStateChanged(previous, next) {
7928
- return !previous || previous.status !== next.status || previous.isWorking !== next.isWorking || previous.completionSerial !== next.completionSerial;
8554
+ return !previous || previous.status !== next.status || previous.isWorking !== next.isWorking || previous.runStarted !== next.runStarted || previous.completionSerial !== next.completionSerial;
7929
8555
  }
7930
8556
 
7931
8557
  function setTabActivity(tabId, activity = {}) {
7932
8558
  if (!tabId) return null;
7933
8559
  const previous = tabActivities.get(tabId);
7934
8560
  const normalized = normalizeTabActivity(activity);
8561
+ if (promptRoutingTabs.has(tabId) && previous?.isWorking && !normalized.isWorking) return previous;
7935
8562
  tabActivities.set(tabId, normalized);
7936
8563
  if (!tabSeenCompletionSerials.has(tabId) || (previous && normalized.completionSerial < previous.completionSerial)) {
7937
8564
  tabSeenCompletionSerials.set(tabId, normalized.completionSerial);
@@ -7973,6 +8600,8 @@ function syncTabMetadata(nextTabs = []) {
7973
8600
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
7974
8601
  clearGitWorkflowForTab(tabId);
7975
8602
  commandCatalogsByTab.delete(tabId);
8603
+ clearGitFooterPayloadState(tabId);
8604
+ gitFooterPayloadRequestSerialByTab.delete(tabId);
7976
8605
  }
7977
8606
  }
7978
8607
  for (const tabId of tabMessagesCache.keys()) {
@@ -8066,11 +8695,20 @@ function syncTabPolling() {
8066
8695
  }
8067
8696
  }
8068
8697
 
8069
- function markTabWorkingLocally(tabId = activeTabId) {
8698
+ function markTabWorkingLocally(tabId = activeTabId, { runStarted = false } = {}) {
8070
8699
  const tab = tabs.find((item) => item.id === tabId);
8071
8700
  if (!tab) return false;
8701
+ suppressPendingAgentDoneNotificationsForTab(tabId);
8072
8702
  const previous = activityForTab(tab);
8073
- const next = normalizeTabActivity({ ...previous, status: "working", isWorking: true });
8703
+ const timestamp = new Date().toISOString();
8704
+ const next = normalizeTabActivity({
8705
+ ...previous,
8706
+ status: "working",
8707
+ isWorking: true,
8708
+ runStarted: previous.runStarted === true || runStarted === true,
8709
+ lastStartedAt: timestamp,
8710
+ lastChangedAt: timestamp,
8711
+ });
8074
8712
  tabActivities.set(tabId, next);
8075
8713
  if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
8076
8714
  return true;
@@ -8080,20 +8718,23 @@ function markTabIdleLocally(tabId = activeTabId) {
8080
8718
  const tab = tabs.find((item) => item.id === tabId);
8081
8719
  if (!tab) return false;
8082
8720
  const previous = activityForTab(tab);
8083
- const next = normalizeTabActivity({ ...previous, status: "idle", isWorking: false });
8721
+ const next = normalizeTabActivity({ ...previous, status: "idle", isWorking: false, runStarted: false });
8084
8722
  tabActivities.set(tabId, next);
8085
8723
  if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
8086
8724
  return true;
8087
8725
  }
8088
8726
 
8089
8727
  function markTabDoneLocally(tabId = activeTabId) {
8728
+ if (promptRoutingTabs.has(tabId)) return false;
8090
8729
  const tab = tabs.find((item) => item.id === tabId);
8091
8730
  if (!tab) return false;
8092
8731
  const previous = activityForTab(tab);
8732
+ if (!previous.runStarted) return markTabIdleLocally(tabId);
8093
8733
  const next = normalizeTabActivity({
8094
8734
  ...previous,
8095
8735
  status: "done",
8096
8736
  isWorking: false,
8737
+ runStarted: false,
8097
8738
  completionSerial: (Number(previous.completionSerial) || 0) + 1,
8098
8739
  lastCompletedAt: new Date().toISOString(),
8099
8740
  });
@@ -8120,7 +8761,9 @@ function syncActiveTabActivityFromState(state = currentState) {
8120
8761
  return false;
8121
8762
  }
8122
8763
  if (stateHasVisibleWork(state)) {
8123
- if (!activity.isWorking) return markTabWorkingLocally(tab.id);
8764
+ if (!activity.isWorking || (state.isStreaming && !activity.runStarted)) {
8765
+ return markTabWorkingLocally(tab.id, { runStarted: state.isStreaming === true });
8766
+ }
8124
8767
  return false;
8125
8768
  }
8126
8769
  if (activity.isWorking && !tabActivityRecentlyStarted(activity)) return markTabDoneLocally(tab.id);
@@ -8230,7 +8873,7 @@ function restoreActiveDraft() {
8230
8873
 
8231
8874
  function focusPromptInput({ defer = false } = {}) {
8232
8875
  const focus = () => {
8233
- 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;
8876
+ 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;
8234
8877
  try {
8235
8878
  elements.promptInput.focus({ preventScroll: true });
8236
8879
  } catch {
@@ -8890,9 +9533,18 @@ function renderGitPanelFolder(node, card, category, depth = 0) {
8890
9533
  function renderGitPanelFile(entry, card, category) {
8891
9534
  const row = make("div", `git-side-panel-file ${category}`);
8892
9535
  const fullPath = entry.oldPath ? `${entry.oldPath} → ${entry.path}` : entry.path;
8893
- row.title = `${fullPath} · Right-click for Git actions`;
9536
+ row.title = `${fullPath} · Open in WebUI · Right-click for Git actions`;
8894
9537
  row.tabIndex = 0;
8895
- row.setAttribute("aria-label", `${entry.name || entry.path}, ${gitPanelStatsText(entry, category) || "no line statistics"}`);
9538
+ row.setAttribute("role", "button");
9539
+ row.setAttribute("aria-label", `Open ${entry.name || entry.path} in WebUI, ${gitPanelStatsText(entry, category) || "no line statistics"}`);
9540
+ const open = () => openGitFileInViewer(entry.path, { root: card.root, candidates: card.candidates, category })
9541
+ .catch((error) => addEvent(error.message || String(error), "error"));
9542
+ row.addEventListener("click", open);
9543
+ row.addEventListener("keydown", (event) => {
9544
+ if (event.repeat || (event.key !== "Enter" && event.key !== " ")) return;
9545
+ event.preventDefault();
9546
+ open();
9547
+ });
8896
9548
  const status = make("span", "git-side-panel-file-status", entry.status?.trim() || (entry.untracked ? "?" : "•"));
8897
9549
  const name = make("span", "git-side-panel-file-name", entry.name || entry.path);
8898
9550
  const statsText = gitPanelStatsText(entry, category);
@@ -8940,6 +9592,26 @@ function gitPanelHistoryDate(value) {
8940
9592
  return Number.isNaN(date.getTime()) ? String(value || "") : date.toLocaleString();
8941
9593
  }
8942
9594
 
9595
+ function gitPanelDataRenderSignature(data) {
9596
+ if (!data) return null;
9597
+ return {
9598
+ branch: data.branch || "",
9599
+ changes: Array.isArray(data.changes) ? data.changes : [],
9600
+ history: Array.isArray(data.history) ? data.history : [],
9601
+ };
9602
+ }
9603
+
9604
+ function updateGitPanelRepositoryMeta(cards = gitPanelRepositoryCards()) {
9605
+ const sections = [...elements.gitPanelGroups?.querySelectorAll(".git-side-panel-repository[data-git-root]") || []];
9606
+ for (const card of cards) {
9607
+ const snapshot = gitPanelSnapshot(card.root);
9608
+ if (!snapshot?.data) continue;
9609
+ const section = sections.find((candidate) => candidate.dataset.gitRoot === card.root);
9610
+ const status = section?.querySelector(".git-side-panel-repository-updated");
9611
+ if (status) status.textContent = snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(snapshot.data.generatedAt)}`;
9612
+ }
9613
+ }
9614
+
8943
9615
  function renderGitPanelHistory(card, data) {
8944
9616
  const wrapper = make("div", "git-side-panel-history");
8945
9617
  const history = Array.isArray(data?.history) ? data.history : [];
@@ -9011,7 +9683,7 @@ function renderGitPanelRepositoryContent(card, snapshot) {
9011
9683
  const meta = make("div", "git-side-panel-repository-meta");
9012
9684
  meta.append(
9013
9685
  make("strong", undefined, data.branch || "detached"),
9014
- make("span", undefined, snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(data.generatedAt)}`),
9686
+ make("span", "git-side-panel-repository-updated", snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(data.generatedAt)}`),
9015
9687
  );
9016
9688
  const changesPanel = renderGitPanelChanges(card, data);
9017
9689
  changesPanel.id = "git-side-panel-changes-panel";
@@ -9041,6 +9713,7 @@ function renderGitPanelRepositoryCard(card) {
9041
9713
  const snapshot = gitPanelSnapshot(card.root);
9042
9714
  const expanded = gitPanelState.expandedCardKey === card.key;
9043
9715
  const section = make("section", `git-side-panel-repository${expanded ? " expanded" : ""}`);
9716
+ section.dataset.gitRoot = card.root;
9044
9717
  const button = make("button", "git-side-panel-repository-toggle");
9045
9718
  button.type = "button";
9046
9719
  button.setAttribute("aria-expanded", expanded ? "true" : "false");
@@ -9087,12 +9760,13 @@ function renderGitPanel() {
9087
9760
  cards: cards.map((card) => {
9088
9761
  const snapshot = gitPanelSnapshot(card.root);
9089
9762
  const data = snapshot?.data;
9090
- 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"];
9763
+ return [card.key, card.root, card.cwd, card.tabId, snapshot?.error || "", !data && !!snapshot?.loading, gitPanelDataRenderSignature(data), gitPanelState.activeViews.get(card.root) || "changes"];
9091
9764
  }),
9092
9765
  repositoryCount,
9093
9766
  discovering,
9094
9767
  });
9095
9768
  if (signature === gitPanelRenderSignature && elements.gitPanelGroups.childElementCount === cards.length) {
9769
+ updateGitPanelRepositoryMeta(cards);
9096
9770
  ensureGitPanelRepositoriesDiscovered();
9097
9771
  ensureGitPanelVisibleRepositoriesFresh(cards);
9098
9772
  return;
@@ -9136,10 +9810,6 @@ function terminalAppRunnerLabel(run) {
9136
9810
  return command && command !== "app runner" ? `app runner: ${command}` : "app runner running";
9137
9811
  }
9138
9812
 
9139
- function terminalAppRunnerTooltip(run) {
9140
- return appRunnerIsRunning(run) ? ` · ${terminalAppRunnerLabel(run)}` : "";
9141
- }
9142
-
9143
9813
  function tabConversationMode(tab) {
9144
9814
  if (!tab?.id) return normalizeConversationModeState(tab?.conversationMode || {});
9145
9815
  return normalizeConversationModeState(conversationModeByTab.get(tab.id) || tab.conversationMode || {});
@@ -9149,22 +9819,16 @@ function tabConversationModeActive(tab) {
9149
9819
  return tabConversationMode(tab).enabled === true;
9150
9820
  }
9151
9821
 
9152
- function terminalConversationModeTooltip(tab) {
9153
- const mode = tabConversationMode(tab);
9154
- return mode.enabled ? ` · natural conversation: ${mode.uiState || "listening"}` : "";
9155
- }
9156
-
9157
9822
  function tabWorkflowModeActive(tab) {
9158
9823
  return normalizeWorkflowModeState(workflowModeByTab.get(tab?.id) || {}).enabled === true;
9159
9824
  }
9160
9825
 
9161
- function terminalWorkflowTooltip(tab) {
9162
- const count = workflowRunningCountForTab(tab?.id);
9163
- return `${tabWorkflowModeActive(tab) ? " · workflow mode active" : ""}${count ? ` · ${count} workflow run${count === 1 ? "" : "s"} active` : ""}`;
9826
+ function terminalTabWorkspaceName(tab) {
9827
+ return tabGroupTitle(tab?.cwd, "workspace");
9164
9828
  }
9165
9829
 
9166
9830
  function terminalTabMeta(tab, indicator) {
9167
- const parts = [tab.running ? `${indicator.meta} · pid ${tab.pid || "…"}` : "stopped"];
9831
+ const parts = [tab.running ? `${indicator.meta} · ${terminalTabWorkspaceName(tab)}` : "stopped"];
9168
9832
  if (tabAppRunnerRunningRun(tab)) parts.push("app runner");
9169
9833
  if (tabConversationModeActive(tab)) parts.push("voice");
9170
9834
  if (tabWorkflowModeActive(tab)) parts.push("workflow mode");
@@ -9173,6 +9837,86 @@ function terminalTabMeta(tab, indicator) {
9173
9837
  return parts.join(" · ");
9174
9838
  }
9175
9839
 
9840
+ function terminalTabGitTooltip(tab) {
9841
+ const workspace = normalizeGitWorkspaceInfo(tab?.gitWorkspace);
9842
+ if (!workspace) return "";
9843
+ const checkout = workspace.worktreePath ? (workspace.isMainWorktree ? "main worktree" : "worktree") : "";
9844
+ return [workspace.branch || "detached", checkout].filter(Boolean).join(" · ");
9845
+ }
9846
+
9847
+ function terminalTabActiveTooltip(tab) {
9848
+ const active = [];
9849
+ const appRunnerRun = tabAppRunnerRunningRun(tab);
9850
+ if (appRunnerRun) active.push(terminalAppRunnerLabel(appRunnerRun));
9851
+ const conversationMode = tabConversationMode(tab);
9852
+ if (conversationMode.enabled) active.push(`voice: ${conversationMode.uiState || "listening"}`);
9853
+ const workflowCount = workflowRunningCountForTab(tab?.id);
9854
+ if (tabWorkflowModeActive(tab)) active.push(workflowCount ? `workflow: ${workflowCount} run${workflowCount === 1 ? "" : "s"}` : "workflow mode");
9855
+ else if (workflowCount) active.push(`workflow: ${workflowCount} run${workflowCount === 1 ? "" : "s"}`);
9856
+ return active.join(" · ");
9857
+ }
9858
+
9859
+ function terminalTabTooltip(tab) {
9860
+ const lines = [
9861
+ `${tab?.title || "Terminal tab"} · ${tabIndicator(tab).label}`,
9862
+ `Working folder: ${normalizeDisplayPath(tab?.cwd || "") || "Not set"}`,
9863
+ ];
9864
+ const git = terminalTabGitTooltip(tab);
9865
+ if (git) lines.push(`Git: ${git}`);
9866
+ const active = terminalTabActiveTooltip(tab);
9867
+ if (active) lines.push(`Active: ${active}`);
9868
+ lines.push("Click to switch · Drag to group");
9869
+ return lines.join("\n");
9870
+ }
9871
+
9872
+ function terminalTabGroupStatusTooltip(groupTabs = []) {
9873
+ const counts = { blocked: 0, working: 0, done: 0, idle: 0, stopped: 0 };
9874
+ for (const tab of groupTabs) {
9875
+ const state = tab?.running ? tabIndicator(tab).state : "stopped";
9876
+ counts[state] = (counts[state] || 0) + 1;
9877
+ }
9878
+ return ["blocked", "working", "done", "idle", "stopped"]
9879
+ .filter((state) => counts[state])
9880
+ .map((state) => `${counts[state]} ${state}`)
9881
+ .join(" · ");
9882
+ }
9883
+
9884
+ function terminalTabGroupWorkspaceTooltip(group) {
9885
+ const paths = [...new Set((group?.tabs || []).map((tab) => normalizeDisplayPath(tab?.cwd || "")).filter(Boolean))];
9886
+ if (!group?.custom || paths.length <= 1) return `Working folder: ${paths[0] || normalizeDisplayPath(group?.cwd || "") || "Not set"}`;
9887
+ const names = paths.map((path) => path.split("/").filter(Boolean).slice(-2).join("/") || path);
9888
+ const remainder = names.length - 2;
9889
+ return `Workspaces: ${names.slice(0, 2).join(", ")}${remainder > 0 ? ` +${remainder} more` : ""}`;
9890
+ }
9891
+
9892
+ function terminalTabGroupActiveTooltip(groupTabs = []) {
9893
+ const appRunners = groupTabs.filter(tabAppRunnerRunningRun).length;
9894
+ const voices = groupTabs.filter(tabConversationModeActive).length;
9895
+ const workflowTabs = groupTabs.filter(tabWorkflowModeActive).length;
9896
+ const workflowRuns = groupTabs.reduce((total, tab) => total + workflowRunningCountForTab(tab?.id), 0);
9897
+ return [
9898
+ appRunners ? `${appRunners} app runner${appRunners === 1 ? "" : "s"}` : "",
9899
+ voices ? `${voices} voice` : "",
9900
+ workflowTabs ? `${workflowTabs} workflow tab${workflowTabs === 1 ? "" : "s"}` : "",
9901
+ workflowRuns ? `${workflowRuns} workflow run${workflowRuns === 1 ? "" : "s"}` : "",
9902
+ ].filter(Boolean).join(" · ");
9903
+ }
9904
+
9905
+ function terminalTabGroupTooltip(group, groupTitle = terminalDisplayGroupTitle(group)) {
9906
+ const groupTabs = group?.tabs || [];
9907
+ const lines = [
9908
+ `${groupTitle} · ${groupTabs.length} tab${groupTabs.length === 1 ? "" : "s"}`,
9909
+ terminalTabGroupWorkspaceTooltip(group),
9910
+ `Status: ${terminalTabGroupStatusTooltip(groupTabs) || "No tabs"}`,
9911
+ ];
9912
+ const active = terminalTabGroupActiveTooltip(groupTabs);
9913
+ if (active) lines.push(`Active: ${active}`);
9914
+ lines.push("Click to switch · Drop tabs here to add");
9915
+ return lines.join("\n");
9916
+ }
9917
+
9918
+ let terminalTabGroupSummarySerial = 0;
9919
+
9176
9920
  function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null, conversationModeActive = false, workflowModeActive = false, workflowCount = 0, subagent = false }) {
9177
9921
  const titleRow = make("span", "terminal-tab-title-row");
9178
9922
  const indicatorDot = make("span", "terminal-tab-activity-indicator");
@@ -9204,8 +9948,7 @@ function renderTerminalTab(tab) {
9204
9948
  button.setAttribute("role", "tab");
9205
9949
  button.setAttribute("aria-selected", isActive ? "true" : "false");
9206
9950
  button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
9207
- 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`;
9208
- applyStyledTooltip(button, tooltip, { ariaLabel: false });
9951
+ applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace" });
9209
9952
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
9210
9953
  button.addEventListener("click", () => switchTab(tab.id));
9211
9954
  wrapper.append(button);
@@ -9244,8 +9987,7 @@ function renderTerminalTabGroupItem(tab, group) {
9244
9987
  button.setAttribute("role", "tab");
9245
9988
  button.setAttribute("aria-selected", isActive ? "true" : "false");
9246
9989
  button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}${conversationLabel}${workflowModeActive ? ", workflow mode active" : ""}${workflowCount ? `, ${workflowCount} workflow runs active` : ""}`);
9247
- 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`;
9248
- applyStyledTooltip(button, tooltip, { ariaLabel: false });
9990
+ applyStyledTooltip(button, terminalTabTooltip(tab), { ariaLabel: false, align: "start", description: true, variant: "workspace" });
9249
9991
  appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun, conversationModeActive, workflowModeActive, workflowCount });
9250
9992
  button.addEventListener("click", (event) => {
9251
9993
  event.stopPropagation();
@@ -9288,7 +10030,6 @@ function renderTerminalTabGroup(group, groupCount = 1) {
9288
10030
  const workflowModeActive = groupTabs.some(tabWorkflowModeActive);
9289
10031
  const groupTitle = terminalDisplayGroupTitle(group, activeGroupTab?.title || "group");
9290
10032
  const activeTitle = activeGroupTab?.title || groupTitle;
9291
- const groupDetail = terminalDisplayGroupDetail(group, groupTitle);
9292
10033
  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" : ""}`);
9293
10034
  wrapper.dataset.groupKey = group.key;
9294
10035
  if (group.customGroupId) wrapper.dataset.customGroupId = group.customGroupId;
@@ -9309,8 +10050,6 @@ function renderTerminalTabGroup(group, groupCount = 1) {
9309
10050
  button.setAttribute("aria-haspopup", "true");
9310
10051
  button.setAttribute("aria-expanded", group.key === openTerminalTabGroupKey ? "true" : "false");
9311
10052
  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}`);
9312
- 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`;
9313
- applyStyledTooltip(button, tooltip, { ariaLabel: false });
9314
10053
  appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}${workflowModeActive ? " · workflow mode" : ""}${workflowCount ? ` · ${workflowCount} workflows` : ""}`, appRunnerRun, count: groupTabs.length, workflowModeActive, workflowCount });
9315
10054
  button.addEventListener("click", () => switchTab(activeGroupTab.id));
9316
10055
  wrapper.append(button);
@@ -9331,6 +10070,10 @@ function renderTerminalTabGroup(group, groupCount = 1) {
9331
10070
  const menu = make("div", "terminal-tab-group-menu");
9332
10071
  menu.setAttribute("role", "group");
9333
10072
  menu.setAttribute("aria-label", `${groupTitle} tabs`);
10073
+ const summary = make("div", "terminal-tab-group-summary", terminalTabGroupTooltip(group, groupTitle));
10074
+ summary.id = `terminalTabGroupSummary${++terminalTabGroupSummarySerial}`;
10075
+ button.setAttribute("aria-describedby", summary.id);
10076
+ menu.append(summary);
9334
10077
  for (const tab of groupTabs) menu.append(renderTerminalTabGroupItem(tab, group));
9335
10078
 
9336
10079
  const add = make("button", "terminal-tab-group-add", "+ Tab");
@@ -10075,7 +10818,8 @@ function queueAgentDoneBrowserNotification({ key, tabId, title, body }) {
10075
10818
  clearPendingAgentDoneNotification(key);
10076
10819
  const timer = setTimeout(() => {
10077
10820
  pendingAgentDoneNotificationTimers.delete(key);
10078
- if (isAutoRetryingTab(tabId)) return;
10821
+ const tab = tabs.find((item) => item.id === tabId);
10822
+ if (isAutoRetryingTab(tabId) || promptRoutingTabs.has(tabId) || activityForTab(tab).isWorking) return;
10079
10823
  showAgentDoneBrowserNotification({ tabId, title, body });
10080
10824
  }, AGENT_DONE_NOTIFICATION_RETRY_GRACE_MS);
10081
10825
  pendingAgentDoneNotificationTimers.set(key, { tabId, timer });
@@ -10586,6 +11330,8 @@ let footerTooltipPendingTarget = null;
10586
11330
  function ensureFooterTooltipNode() {
10587
11331
  if (!footerTooltipNode) {
10588
11332
  footerTooltipNode = make("div", "footer-floating-tooltip");
11333
+ footerTooltipNode.id = "footerFloatingTooltip";
11334
+ footerTooltipNode.setAttribute("role", "tooltip");
10589
11335
  footerTooltipNode.hidden = true;
10590
11336
  document.body.append(footerTooltipNode);
10591
11337
  }
@@ -10594,6 +11340,9 @@ function ensureFooterTooltipNode() {
10594
11340
  const update = () => positionFooterTooltip(footerTooltipTarget);
10595
11341
  window.addEventListener("resize", update, { passive: true });
10596
11342
  window.addEventListener("scroll", update, { passive: true, capture: true });
11343
+ document.addEventListener("keydown", (event) => {
11344
+ if (event.key === "Escape" && footerTooltipTarget) hideFooterTooltip(footerTooltipTarget);
11345
+ }, true);
10597
11346
  }
10598
11347
  return footerTooltipNode;
10599
11348
  }
@@ -10635,6 +11384,9 @@ function showFooterTooltip(target) {
10635
11384
  if (!text) return;
10636
11385
  footerTooltipTarget = target;
10637
11386
  const tooltip = ensureFooterTooltipNode();
11387
+ const variant = target.getAttribute("data-tooltip-variant");
11388
+ if (variant) tooltip.dataset.variant = variant;
11389
+ else delete tooltip.dataset.variant;
10638
11390
  tooltip.textContent = text;
10639
11391
  tooltip.hidden = false;
10640
11392
  tooltip.classList.add("visible");
@@ -10661,6 +11413,7 @@ function hideFooterTooltip(target) {
10661
11413
  if (!footerTooltipNode) return;
10662
11414
  footerTooltipNode.hidden = true;
10663
11415
  footerTooltipNode.classList.remove("visible");
11416
+ delete footerTooltipNode.dataset.variant;
10664
11417
  }
10665
11418
 
10666
11419
  function bindStyledTooltipEvents(node) {
@@ -10668,10 +11421,15 @@ function bindStyledTooltipEvents(node) {
10668
11421
  node._styledTooltipBound = true;
10669
11422
  node.addEventListener("mouseenter", () => scheduleFooterTooltip(node));
10670
11423
  node.addEventListener("mouseleave", () => hideFooterTooltip(node));
10671
- node.addEventListener("focus", () => showFooterTooltip(node));
11424
+ node.addEventListener("focus", () => {
11425
+ if (node.getAttribute("data-tooltip-variant") === "workspace" && !node.matches(":focus-visible")) return;
11426
+ showFooterTooltip(node);
11427
+ });
10672
11428
  node.addEventListener("blur", () => hideFooterTooltip(node));
10673
11429
  }
10674
11430
 
11431
+ let styledTooltipDescriptionSerial = 0;
11432
+
10675
11433
  function applyStyledTooltip(node, tooltip, options = {}) {
10676
11434
  if (!node) return node;
10677
11435
  const text = cleanTooltipText(tooltip);
@@ -10682,7 +11440,15 @@ function applyStyledTooltip(node, tooltip, options = {}) {
10682
11440
  const ariaLabel = typeof options.ariaLabel === "string" ? options.ariaLabel : text.replace(/\s+/g, " ");
10683
11441
  node.setAttribute("aria-label", ariaLabel);
10684
11442
  }
11443
+ if (options.description === true) {
11444
+ const description = make("span", "sr-only styled-tooltip-description", text);
11445
+ description.id = `styledTooltipDescription${++styledTooltipDescriptionSerial}`;
11446
+ node.append(description);
11447
+ const describedBy = [node.getAttribute("aria-describedby"), description.id].filter(Boolean).join(" ");
11448
+ node.setAttribute("aria-describedby", describedBy);
11449
+ }
10685
11450
  if (options.align) node.setAttribute("data-tooltip-align", options.align);
11451
+ if (options.variant) node.setAttribute("data-tooltip-variant", options.variant);
10686
11452
  if (options.floating !== false) bindStyledTooltipEvents(node);
10687
11453
  return node;
10688
11454
  }
@@ -11998,25 +12764,59 @@ function copyGitPathToClipboard(path) {
11998
12764
  copyGitTextToClipboard(path, "path");
11999
12765
  }
12000
12766
 
12001
- // Git paths are repo-root-relative; the file viewer resolves against the tab
12002
- // cwd. Translate when the tab sits at (or above within) the repo root.
12767
+ // Git paths are repo-root-relative; the file viewer resolves against a tab's
12768
+ // cwd. Prefer the active tab when it contains the file, otherwise use another
12769
+ // tab that exposes the repository path.
12770
+ function gitFileViewerTarget(repoRelPath, root, candidates = []) {
12771
+ const path = normalizeFileTreePath(repoRelPath);
12772
+ const normalizedRoot = String(root || "").trim().replace(/\\/g, "/");
12773
+ const repoRoot = normalizedRoot === "/" ? "/" : normalizedRoot.replace(/\/+$/, "");
12774
+ if (!path || !repoRoot) return null;
12775
+ const absolute = `${repoRoot === "/" ? "/" : `${repoRoot}/`}${path}`;
12776
+ const current = activeTab();
12777
+ const ordered = [current ? { tabId: current.id, cwd: current.cwd } : null, ...candidates].filter(Boolean);
12778
+ const seen = new Set();
12779
+ for (const candidate of ordered) {
12780
+ const tabId = String(candidate?.tabId || candidate?.id || "");
12781
+ const normalizedCwd = String(candidate?.cwd || "").trim().replace(/\\/g, "/");
12782
+ const cwd = normalizedCwd === "/" ? "/" : normalizedCwd.replace(/\/+$/, "");
12783
+ if (!tabId || !cwd || seen.has(tabId)) continue;
12784
+ seen.add(tabId);
12785
+ const prefix = cwd === "/" ? "/" : `${cwd}/`;
12786
+ const caseInsensitive = /^[a-z]:\//i.test(absolute) && /^[a-z]:\//i.test(prefix);
12787
+ const comparableAbsolute = caseInsensitive ? absolute.toLowerCase() : absolute;
12788
+ const comparablePrefix = caseInsensitive ? prefix.toLowerCase() : prefix;
12789
+ if (!comparableAbsolute.startsWith(comparablePrefix)) continue;
12790
+ const viewerPath = absolute.slice(prefix.length);
12791
+ if (viewerPath) return { tabId, path: viewerPath };
12792
+ }
12793
+ return null;
12794
+ }
12795
+
12796
+ async function openGitFileInViewer(repoRelPath, { root = "", candidates = [], closeChanges = false, category = "" } = {}) {
12797
+ const target = gitFileViewerTarget(repoRelPath, root, candidates);
12798
+ if (!target) {
12799
+ addEvent(`Cannot open ${repoRelPath}: it is outside the available tab working directories.`, "error");
12800
+ return;
12801
+ }
12802
+ if (closeChanges) closeGitChangesDialog();
12803
+ if (target.tabId !== activeTabId) await switchTab(target.tabId);
12804
+ if (target.tabId !== activeTabId) {
12805
+ addEvent(`Cannot open ${repoRelPath}: its terminal tab is no longer available.`, "error");
12806
+ return;
12807
+ }
12808
+ setSidePanelCollapsed(false);
12809
+ await openFileInViewer(target.path, { gitCategory: category, gitPath: normalizeFileTreePath(repoRelPath) });
12810
+ }
12811
+
12003
12812
  async function openGitFileFromChanges(repoRelPath) {
12004
12813
  const tabId = gitChangesState.tabId || activeTabId;
12005
- const root = gitChangesState.data?.root || "";
12006
12814
  const tab = tabs.find((item) => item.id === tabId);
12007
- let viewerPath = repoRelPath;
12008
- if (root && tab?.cwd) {
12009
- const absolute = `${root.replace(/\/+$/, "")}/${repoRelPath}`;
12010
- const cwd = tab.cwd.replace(/\/+$/, "");
12011
- if (absolute.startsWith(`${cwd}/`)) viewerPath = absolute.slice(cwd.length + 1);
12012
- else if (root !== cwd) {
12013
- addEvent(`Cannot open ${repoRelPath}: it is outside this tab's working directory.`, "error");
12014
- return;
12015
- }
12016
- }
12017
- closeGitChangesDialog();
12018
- setSidePanelCollapsed(false);
12019
- await openFileInViewer(viewerPath);
12815
+ await openGitFileInViewer(repoRelPath, {
12816
+ root: gitChangesState.data?.root || "",
12817
+ candidates: tab ? [{ tabId: tab.id, cwd: tab.cwd }] : [],
12818
+ closeChanges: true,
12819
+ });
12020
12820
  }
12021
12821
 
12022
12822
  function gitChangesCommonFileActions(path) {
@@ -13426,10 +14226,13 @@ function gitFooterFallbackMessage() {
13426
14226
  const tabContext = activeTabContext();
13427
14227
  const commandsStillLoading = availableCommands.length === 0 && rawAvailableCommands.length === 0;
13428
14228
  const footerRefreshPending = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
14229
+ const payloadState = tabContext.tabId ? gitFooterPayloadStateByTab.get(tabContext.tabId) : null;
13429
14230
  const extensionDetected = hasAvailableCommand("git-footer-refresh") || optionalFeatureAvailability.gitFooterStatus;
13430
- return commandsStillLoading || footerRefreshPending || extensionDetected
13431
- ? "Loading git footer status…"
13432
- : "Git footer status extension unavailable";
14231
+ if (commandsStillLoading || footerRefreshPending || payloadState?.phase === "waiting") return "Loading git footer status…";
14232
+ if (payloadState?.phase === "failed") return payloadState.error || "Git footer status was not received — refresh to retry";
14233
+ if (payloadState?.phase === "idle") return "Git footer status unavailable — refresh to retry";
14234
+ if (extensionDetected) return "Loading git footer status…";
14235
+ return "Git footer status extension unavailable";
13433
14236
  }
13434
14237
 
13435
14238
  function renderMinimalFooter() {
@@ -13736,7 +14539,11 @@ function renderWorkspaceDashboard() {
13736
14539
  make("span", "workspace-dashboard-chip", `${tabs.length} tab${tabs.length === 1 ? "" : "s"}`),
13737
14540
  make("span", `workspace-dashboard-chip ${queueCount ? "attention" : ""}`.trim(), queueCount ? `${queueCount} queued` : "queue clear"),
13738
14541
  );
13739
- title.append(make("span", "workspace-dashboard-kicker", "Workspace"), heading, cwd, meta);
14542
+ const summary = make("div", "workspace-dashboard-summary-row");
14543
+ summary.append(make("span", "workspace-dashboard-kicker", "Workspace"), meta);
14544
+ const identity = make("div", "workspace-dashboard-identity");
14545
+ identity.append(heading, cwd);
14546
+ title.append(summary, identity);
13740
14547
  const actions = make("div", "workspace-dashboard-actions");
13741
14548
  actions.append(
13742
14549
  dashboardAction("Command palette", () => openCommandPalette(), "primary"),
@@ -15138,7 +15945,12 @@ function closePathPicker(cwd) {
15138
15945
  }
15139
15946
 
15140
15947
  function pickCwd(tab, initialCwd, { title } = {}) {
15141
- if (pathPickerState) return Promise.resolve(null);
15948
+ if (pathPickerState) {
15949
+ addEvent("working-directory picker is already open", "warn");
15950
+ elements.pathPickerDialog.focus();
15951
+ elements.pathPickerSearchInput.focus({ preventScroll: true });
15952
+ return Promise.resolve(null);
15953
+ }
15142
15954
 
15143
15955
  return new Promise((resolve) => {
15144
15956
  const pickerTab = tab || { id: "path-picker", title: "tab" };
@@ -15179,27 +15991,46 @@ async function changeActiveTabCwd() {
15179
15991
  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;
15180
15992
 
15181
15993
  saveActiveDraft();
15994
+ if (isCurrentTabContext(tabContext)) {
15995
+ addTransientMessage({
15996
+ role: "native",
15997
+ title: "Changing working folder…",
15998
+ content: `Restarting ${tab.title} in ${cwd}. This can take a few seconds.`,
15999
+ level: "info",
16000
+ });
16001
+ }
16002
+ let response;
15182
16003
  try {
15183
- const response = await api(`/api/tabs/${encodeURIComponent(tab.id)}`, { method: "PATCH", body: { cwd }, scoped: false });
15184
- tabs = response.data?.tabs || tabs;
15185
- syncTabMetadata(tabs);
15186
- if (!isCurrentTabContext(tabContext)) {
15187
- renderTabs();
15188
- return;
15189
- }
15190
- const nextContext = setActiveTabId(response.data?.tab?.id || activeTabId);
15191
- resetGitWorkflowForTab(nextContext.tabId);
15192
- resetActiveTabUi();
16004
+ response = await api(`/api/tabs/${encodeURIComponent(tab.id)}`, { method: "PATCH", body: { cwd }, scoped: false });
16005
+ } catch (error) {
16006
+ const message = `Could not change ${tab.title} to ${cwd}. The existing working folder was kept.\n\n${error.message || String(error)}`;
16007
+ if (isCurrentTabContext(tabContext)) surfaceRuntimeDiagnostic("Working folder change failed", message);
16008
+ else addEvent(`working folder change failed for ${tab.title}: ${error.message || String(error)}`, "error");
16009
+ return;
16010
+ }
16011
+
16012
+ tabs = response.data?.tabs || tabs;
16013
+ syncTabMetadata(tabs);
16014
+ const changedTabId = response.data?.tab?.id || tab.id;
16015
+ const changedCwd = response.data?.tab?.cwd || cwd;
16016
+ resetGitWorkflowForTab(changedTabId);
16017
+ clearGitFooterPayloadState(changedTabId);
16018
+ if (!isCurrentTabContext(tabContext)) {
15193
16019
  renderTabs();
15194
- restoreActiveDraft();
15195
- connectEvents(nextContext);
15196
- await refreshAll(nextContext);
15197
- if (!isCurrentTabContext(nextContext)) return;
15198
- const changedCwd = response.data?.tab?.cwd || cwd;
15199
16020
  addEvent(response.data?.changed === false ? `cwd unchanged: ${changedCwd}` : `changed ${tab.title} cwd to ${changedCwd}`, "info");
15200
- } catch (error) {
15201
- if (isCurrentTabContext(tabContext)) addEvent(error.message, "error");
16021
+ return;
15202
16022
  }
16023
+
16024
+ const nextContext = setActiveTabId(response.data?.tab?.id || activeTabId);
16025
+ resetActiveTabUi();
16026
+ renderTabs();
16027
+ restoreActiveDraft();
16028
+ connectEvents(nextContext);
16029
+ await refreshAll(nextContext);
16030
+ if (!isCurrentTabContext(nextContext)) return;
16031
+ const successMessage = response.data?.changed === false ? `cwd unchanged: ${changedCwd}` : `changed ${tab.title} cwd to ${changedCwd}`;
16032
+ addEvent(successMessage, "info");
16033
+ if (response.data?.changed !== false) addTransientMessage({ role: "native", title: "Working folder changed", content: `${tab.title} restarted in ${changedCwd}.`, level: "info" });
15203
16034
  }
15204
16035
 
15205
16036
  function renderFooter() {
@@ -15567,7 +16398,13 @@ function initializeClaudeUsage() {
15567
16398
  }
15568
16399
 
15569
16400
  function subagentTabsWithRunningAgents() {
16401
+ const serverNow = Number(latestSubagents?.updatedAt);
16402
+ const now = Number.isFinite(serverNow) ? serverNow : Date.now();
15570
16403
  return (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : [])
16404
+ .map((tab) => {
16405
+ const gates = visibleSubagentGates(tab, dismissedSubagentGateKeys, now);
16406
+ return { ...tab, gates, gateCount: gates.length };
16407
+ })
15571
16408
  .filter((tab) => Number(tab?.agentCount || 0) > 0 || Number(tab?.gateCount || 0) > 0)
15572
16409
  .sort((a, b) => Number(a.tabIndex || 0) - Number(b.tabIndex || 0) || String(a.tabTitle || "").localeCompare(String(b.tabTitle || "")));
15573
16410
  }
@@ -15588,6 +16425,10 @@ function subagentRunElapsed(run) {
15588
16425
  return Number.isFinite(startedAt) ? formatDuration(Math.max(0, Date.now() - startedAt)) : "";
15589
16426
  }
15590
16427
 
16428
+ function subagentSourceLabel(source = "") {
16429
+ return source === "foreground" || source === "workflow" ? source : "async";
16430
+ }
16431
+
15591
16432
  function subagentExecutionFacts(agent = {}) {
15592
16433
  const thinking = String(agent?.thinking || "").trim();
15593
16434
  let model = String(agent?.model || "").trim();
@@ -15729,7 +16570,7 @@ function subagentOverlayStateFacts(data = subagentOverlayData) {
15729
16570
  return [
15730
16571
  agent.status || "running",
15731
16572
  data?.mode || subagentOverlaySelection?.run?.mode,
15732
- data?.source || subagentOverlaySelection?.run?.source,
16573
+ subagentSourceLabel(data?.source || subagentOverlaySelection?.run?.source),
15733
16574
  agent.nested ? "nested" : "",
15734
16575
  ...subagentExecutionFacts(agent),
15735
16576
  agent.currentTool ? `tool ${agent.currentTool}` : "",
@@ -15983,7 +16824,7 @@ function renderSubagentTerminalView() {
15983
16824
  const facts = [
15984
16825
  view.finished ? "finished" : running ? "running" : agent.status || "finished",
15985
16826
  view.run?.mode,
15986
- view.run?.source === "foreground" ? "foreground" : "async",
16827
+ subagentSourceLabel(view.data?.source || view.run?.source),
15987
16828
  agent.nested ? "nested" : "",
15988
16829
  ...subagentExecutionFacts(agent),
15989
16830
  agent.currentTool ? `tool ${agent.currentTool}` : "",
@@ -16181,7 +17022,7 @@ function renderSubagentTerminalTab(view) {
16181
17022
  appendTerminalTabContent(button, {
16182
17023
  title: subagentTerminalViewTitle(view),
16183
17024
  indicator: { state: running ? "working" : "done" },
16184
- meta: ["Subagent", ...subagentExecutionFacts(view.data?.agent || view.agent), view.parentTitle || "parent terminal"].join(" · "),
17025
+ meta: ["Subagent", subagentSourceLabel(view.data?.source || view.run?.source), ...subagentExecutionFacts(view.data?.agent || view.agent), view.parentTitle || "parent terminal"].join(" · "),
16185
17026
  subagent: true,
16186
17027
  });
16187
17028
  button.addEventListener("click", () => activateSubagentTerminalView(view.id));
@@ -16211,7 +17052,7 @@ function renderSubagentAgent(tab, run, agent) {
16211
17052
  const facts = [
16212
17053
  agent?.nested ? "nested" : "",
16213
17054
  run?.mode && run.mode !== "single" ? run.mode : "",
16214
- run?.source === "foreground" ? "foreground" : "async",
17055
+ subagentSourceLabel(run?.source),
16215
17056
  ...subagentExecutionFacts(agent),
16216
17057
  agent?.currentTool ? `tool: ${agent.currentTool}` : "",
16217
17058
  elapsed ? `running ${elapsed}` : "",
@@ -16251,7 +17092,7 @@ function renderSubagentGateAttempt(attempt) {
16251
17092
  return row;
16252
17093
  }
16253
17094
 
16254
- function renderSubagentGate(gate) {
17095
+ function renderSubagentGate(tab, gate) {
16255
17096
  const status = subagentGateStatusLabel(gate?.status);
16256
17097
  const card = make("section", `subagent-gate-card ${status}`);
16257
17098
  const header = make("div", "subagent-gate-header");
@@ -16260,7 +17101,24 @@ function renderSubagentGate(gate) {
16260
17101
  make("strong", undefined, `Retry gate · ${gate?.qualifyingSuccesses || 0}/${gate?.requiredSuccesses || 1}`),
16261
17102
  make("span", undefined, `${status}${gate?.requireDistinctProviders ? " · distinct providers" : ""}`),
16262
17103
  );
16263
- header.append(title, make("span", `subagent-gate-status ${status}`, status));
17104
+ const actions = make("div", "subagent-gate-actions");
17105
+ actions.append(make("span", `subagent-gate-status ${status}`, status));
17106
+ if (subagentGateIsTerminal(gate)) {
17107
+ const close = make("button", "subagent-gate-close", "×");
17108
+ close.type = "button";
17109
+ applyStyledTooltip(close, "Hide finished retry gate", { ariaLabel: "Hide finished retry gate" });
17110
+ close.addEventListener("click", (event) => {
17111
+ const key = subagentGateKey(tab?.tabId, gate?.id);
17112
+ if (key) dismissedSubagentGateKeys.add(key);
17113
+ renderSubagents();
17114
+ if (event.detail === 0) {
17115
+ const focusTarget = elements.subagentsBox?.querySelector(".subagent-gate-close") || document.querySelector("#sidePanelSectionToggleSubagents");
17116
+ focusTarget?.focus({ preventScroll: true });
17117
+ }
17118
+ });
17119
+ actions.append(close);
17120
+ }
17121
+ header.append(title, actions);
16264
17122
  card.append(header);
16265
17123
  const attempts = make("div", "subagent-gate-attempts");
16266
17124
  for (const attempt of Array.isArray(gate?.attempts) ? gate.attempts : []) attempts.append(renderSubagentGateAttempt(attempt));
@@ -16295,7 +17153,7 @@ function renderSubagentTabGroup(tab) {
16295
17153
  for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
16296
17154
  }
16297
17155
  for (const gate of (Array.isArray(tab.gates) ? tab.gates : []).slice().sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0))) {
16298
- list.append(renderSubagentGate(gate));
17156
+ list.append(renderSubagentGate(tab, gate));
16299
17157
  }
16300
17158
  group.append(list);
16301
17159
  return group;
@@ -16338,6 +17196,7 @@ async function refreshSubagents() {
16338
17196
  try {
16339
17197
  const response = await api("/api/subagents", { scoped: false });
16340
17198
  latestSubagents = response.data || null;
17199
+ pruneDismissedSubagentGateKeys(latestSubagents?.tabs, dismissedSubagentGateKeys);
16341
17200
  syncSubagentTerminalViewsFromOverview();
16342
17201
  subagentsError = null;
16343
17202
  } catch (error) {
@@ -16983,7 +17842,10 @@ function textLines(raw) {
16983
17842
  }
16984
17843
 
16985
17844
  function stripTodoProgressLines(text, { streaming = false } = {}) {
16986
- if (!isOptionalFeatureEnabled("todoProgressWidget")) return String(text || "");
17845
+ // Checklist text is transport for the todo-progress extension, not final
17846
+ // assistant output. Keep filtering it when the widget UI is user-disabled;
17847
+ // disabling the renderer does not unload the extension or its prompt policy.
17848
+ if (!isOptionalFeatureDetected("todoProgressWidget")) return String(text || "");
16987
17849
  let inFence = false;
16988
17850
  const kept = [];
16989
17851
  const raw = String(text || "");
@@ -18181,6 +19043,7 @@ const APP_RUNNER_SUPPORTED_ITEMS = [
18181
19043
  "C/C++: CMake, cc/c++ main files",
18182
19044
  "Docker Compose: docker compose up",
18183
19045
  "Shell scripts: bash/zsh/fish in root, dev/, scripts/, dev/scripts/",
19046
+ "Project discovery paths: shell and Python scripts directly inside directories you configure",
18184
19047
  "Deno, make, just, and plain Node entry files",
18185
19048
  ];
18186
19049
  const APP_RUNNER_SUPPORTED_TOOLTIP = [
@@ -18196,7 +19059,12 @@ function appRunnerMenuCanOpen() {
18196
19059
  }
18197
19060
 
18198
19061
  function activeAppRunnerCustomConfig() {
18199
- return activeAppRunnerData().customRunnerConfig || { runners: [], projectRoot: "", displayProjectRoot: "", displayConfigFile: "" };
19062
+ return activeAppRunnerData().customRunnerConfig || { runners: [], searchPaths: [], projectRoot: "", displayProjectRoot: "", displayConfigFile: "" };
19063
+ }
19064
+
19065
+ function activeAppRunnerSearchPaths() {
19066
+ const config = activeAppRunnerCustomConfig();
19067
+ return Array.isArray(config.searchPaths) ? config.searchPaths.filter((item) => typeof item === "string" && item) : [];
18200
19068
  }
18201
19069
 
18202
19070
  function resetAppRunnerCustomDraft({ clearFeedback = true } = {}) {
@@ -18215,6 +19083,13 @@ function appRunnerRelativeDir(filePath) {
18215
19083
  return index === -1 ? "" : normalized.slice(0, index);
18216
19084
  }
18217
19085
 
19086
+ function appRunnerSourceLabel(runner = {}, displayCommand = "") {
19087
+ const projectFile = String(runner.projectFile || "").replace(/\\/g, "/");
19088
+ if (!projectFile) return "";
19089
+ if (String(displayCommand || "").includes(projectFile)) return "";
19090
+ return `from ${projectFile}`;
19091
+ }
19092
+
18218
19093
  function appRunnerCustomArgsText(args) {
18219
19094
  return Array.isArray(args) ? args.join(" ") : String(args || "");
18220
19095
  }
@@ -18336,6 +19211,270 @@ async function deleteAppRunnerCustomRunner(runner = {}) {
18336
19211
  }
18337
19212
  }
18338
19213
 
19214
+ function setAppRunnerSearchPathFeedback(type, message) {
19215
+ appRunnerSearchPathFeedback = { type, message: cleanStatusText(message || "") };
19216
+ }
19217
+
19218
+ function normalizeAppRunnerSearchPathInput(value) {
19219
+ const raw = String(value || "").replace(/\\/g, "/").trim();
19220
+ if (!raw) return "";
19221
+ if (raw === "." || /^\.\/+$/.test(raw)) return ".";
19222
+ const trimmed = raw.replace(/^\.\/+/, "").replace(/\/+$/g, "");
19223
+ return trimmed || ".";
19224
+ }
19225
+
19226
+ function appRunnerSearchPathLabel(searchPath) {
19227
+ return searchPath === "." ? "Project root (.)" : searchPath;
19228
+ }
19229
+
19230
+ async function saveAppRunnerSearchPaths(searchPaths, { successMessage = "Saved project discovery paths.", eventMessage = "saved app runner discovery paths", onSuccess = null } = {}) {
19231
+ const tabContext = activeTabContext();
19232
+ try {
19233
+ const response = await api("/api/app-runner-config", { method: "POST", body: { searchPaths }, tabId: tabContext.tabId });
19234
+ if (!isCurrentTabContext(tabContext)) return false;
19235
+ setAppRunnerData(tabContext.tabId, response.data || {});
19236
+ setAppRunnerSearchPathFeedback("success", successMessage);
19237
+ onSuccess?.(tabContext);
19238
+ renderAppRunnerControls();
19239
+ renderWidgets();
19240
+ renderAppRunnerInfoDialog();
19241
+ addEvent(eventMessage, "info");
19242
+ return true;
19243
+ } catch (error) {
19244
+ if (!isCurrentTabContext(tabContext)) return false;
19245
+ const message = error.message || String(error);
19246
+ setAppRunnerSearchPathFeedback("error", `Project discovery paths were not saved: ${message}`);
19247
+ renderAppRunnerInfoDialog();
19248
+ addEvent(`app runner discovery paths were not saved: ${message}`, "error");
19249
+ return false;
19250
+ }
19251
+ }
19252
+
19253
+ async function addAppRunnerSearchPath(container) {
19254
+ const input = container?.querySelector("#appRunnerSearchPathInput");
19255
+ if (input) appRunnerSearchPathDraft = input.value || "";
19256
+ const searchPath = normalizeAppRunnerSearchPathInput(appRunnerSearchPathDraft);
19257
+ const focusInput = () => requestAnimationFrame(() => document.querySelector("#appRunnerSearchPathInput")?.focus());
19258
+ if (!searchPath) {
19259
+ setAppRunnerSearchPathFeedback("warning", "Enter a project-relative directory, or . for the project root.");
19260
+ renderAppRunnerInfoDialog();
19261
+ focusInput();
19262
+ addEvent("app runner discovery path is required", "warn");
19263
+ return;
19264
+ }
19265
+ const current = activeAppRunnerSearchPaths();
19266
+ if (current.includes(searchPath)) {
19267
+ setAppRunnerSearchPathFeedback("warning", `${appRunnerSearchPathLabel(searchPath)} is already configured.`);
19268
+ renderAppRunnerInfoDialog();
19269
+ focusInput();
19270
+ return;
19271
+ }
19272
+ if (current.length >= APP_RUNNER_SEARCH_PATH_LIMIT) {
19273
+ setAppRunnerSearchPathFeedback("warning", `Project discovery path limit reached (${APP_RUNNER_SEARCH_PATH_LIMIT}). Remove a path first.`);
19274
+ renderAppRunnerInfoDialog();
19275
+ return;
19276
+ }
19277
+ await saveAppRunnerSearchPaths([...current, searchPath], {
19278
+ successMessage: `Added ${appRunnerSearchPathLabel(searchPath)}. Supported shell scripts directly inside it now appear in the Run menu.`,
19279
+ eventMessage: `added app runner discovery path ${searchPath}`,
19280
+ onSuccess: () => {
19281
+ appRunnerSearchPathDraft = "";
19282
+ appRunnerDirectoryBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
19283
+ },
19284
+ });
19285
+ }
19286
+
19287
+ async function removeAppRunnerSearchPath(searchPath) {
19288
+ const current = activeAppRunnerSearchPaths();
19289
+ if (!current.includes(searchPath)) return;
19290
+ const tabContext = activeTabContext();
19291
+ const saved = await saveAppRunnerSearchPaths(current.filter((item) => item !== searchPath), {
19292
+ successMessage: `Removed ${appRunnerSearchPathLabel(searchPath)}.`,
19293
+ eventMessage: `removed app runner discovery path ${searchPath}`,
19294
+ });
19295
+ if (!saved) return;
19296
+ offerUndo({
19297
+ message: `Removed project discovery path “${appRunnerSearchPathLabel(searchPath)}”.`,
19298
+ undo: async () => {
19299
+ const restored = await api("/api/app-runner-config", { method: "POST", body: { searchPaths: current }, tabId: tabContext.tabId });
19300
+ if (!isCurrentTabContext(tabContext)) return;
19301
+ setAppRunnerData(tabContext.tabId, restored.data || {});
19302
+ setAppRunnerSearchPathFeedback("success", `Restored ${appRunnerSearchPathLabel(searchPath)}.`);
19303
+ renderAppRunnerControls();
19304
+ renderWidgets();
19305
+ renderAppRunnerInfoDialog();
19306
+ },
19307
+ successMessage: `Restored project discovery path “${appRunnerSearchPathLabel(searchPath)}”.`,
19308
+ });
19309
+ }
19310
+
19311
+ async function loadAppRunnerDirectoryBrowser(relativePath = "") {
19312
+ const tabContext = activeTabContext();
19313
+ const path = String(relativePath || "").replace(/^\.\/+/, "").replace(/\/+$/g, "");
19314
+ appRunnerDirectoryBrowserState = { open: true, loading: true, path, data: null, error: "" };
19315
+ renderAppRunnerInfoDialog();
19316
+ try {
19317
+ const response = await api(`/api/app-runner-files?path=${encodeURIComponent(path)}`, { tabId: tabContext.tabId });
19318
+ if (!isCurrentTabContext(tabContext)) return;
19319
+ appRunnerDirectoryBrowserState = { open: true, loading: false, path, data: response.data || {}, error: "" };
19320
+ renderAppRunnerInfoDialog();
19321
+ } catch (error) {
19322
+ if (!isCurrentTabContext(tabContext)) return;
19323
+ appRunnerDirectoryBrowserState = { open: true, loading: false, path, data: null, error: error.message || String(error) };
19324
+ renderAppRunnerInfoDialog();
19325
+ }
19326
+ }
19327
+
19328
+ function chooseAppRunnerSearchPath(relativeDir) {
19329
+ const searchPath = normalizeAppRunnerSearchPathInput(relativeDir) || ".";
19330
+ appRunnerSearchPathDraft = searchPath;
19331
+ appRunnerDirectoryBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
19332
+ setAppRunnerSearchPathFeedback("info", `Selected ${appRunnerSearchPathLabel(searchPath)}. Choose Add path to save it.`);
19333
+ renderAppRunnerInfoDialog();
19334
+ requestAnimationFrame(() => document.querySelector("#appRunnerSearchPathAddButton")?.focus());
19335
+ }
19336
+
19337
+ function renderAppRunnerDirectoryBrowser() {
19338
+ if (!appRunnerDirectoryBrowserState.open) return null;
19339
+ const browser = make("div", "app-runner-file-browser app-runner-directory-browser");
19340
+ if (appRunnerDirectoryBrowserState.loading) {
19341
+ browser.append(make("div", "muted", "Loading project directories…"));
19342
+ return browser;
19343
+ }
19344
+ if (appRunnerDirectoryBrowserState.error) {
19345
+ browser.append(make("div", "path-picker-error", appRunnerDirectoryBrowserState.error));
19346
+ return browser;
19347
+ }
19348
+ const data = appRunnerDirectoryBrowserState.data || {};
19349
+ const currentDir = normalizeAppRunnerSearchPathInput(data.relativeDir || "") || ".";
19350
+ const header = make("div", "app-runner-file-browser-header");
19351
+ header.append(make("strong", "", data.displayRelativeDir || "."));
19352
+ const headerActions = make("div", "app-runner-directory-browser-actions");
19353
+ const use = make("button", "app-runner-directory-use", "Use this directory");
19354
+ use.type = "button";
19355
+ use.title = `Use ${appRunnerSearchPathLabel(currentDir)} as a project discovery path`;
19356
+ use.addEventListener("click", () => chooseAppRunnerSearchPath(currentDir));
19357
+ const close = make("button", "app-runner-file-browser-close", "Hide browser");
19358
+ close.type = "button";
19359
+ close.addEventListener("click", () => {
19360
+ appRunnerDirectoryBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
19361
+ renderAppRunnerInfoDialog();
19362
+ });
19363
+ headerActions.append(use, close);
19364
+ header.append(headerActions);
19365
+ browser.append(header);
19366
+
19367
+ const roots = make("div", "path-picker-roots app-runner-file-browser-roots");
19368
+ if (data.parent !== null && data.parent !== undefined) roots.append(pathPickerButton("↑ Parent", data.parent || ".", () => loadAppRunnerDirectoryBrowser(data.parent || ""), "path-picker-root-button"));
19369
+ roots.append(pathPickerButton("Project root", data.displayProjectRoot || "Project root", () => loadAppRunnerDirectoryBrowser(""), "path-picker-root-button"));
19370
+ browser.append(roots);
19371
+
19372
+ const list = make("div", "path-picker-list app-runner-file-browser-list");
19373
+ const directories = Array.isArray(data.directories) ? data.directories : [];
19374
+ for (const directory of directories) {
19375
+ const row = make("div", "app-runner-directory-row");
19376
+ row.append(pathPickerButton(`${directory.name}/`, directory.path, () => loadAppRunnerDirectoryBrowser(directory.path), `path-picker-directory${directory.hidden ? " hidden-directory" : ""}`));
19377
+ const choose = make("button", "app-runner-directory-choose", "Use");
19378
+ choose.type = "button";
19379
+ choose.title = `Use ${directory.path} as a project discovery path`;
19380
+ choose.setAttribute("aria-label", `Use ${directory.path} as a project discovery path`);
19381
+ choose.addEventListener("click", () => chooseAppRunnerSearchPath(directory.path));
19382
+ row.append(choose);
19383
+ list.append(row);
19384
+ }
19385
+ if (!directories.length) list.append(make("div", "path-picker-empty muted", "No subdirectories here. Use this directory to scan it directly."));
19386
+ browser.append(list);
19387
+ if (data.truncated) browser.append(make("div", "path-picker-error", "Showing the first project entries only."));
19388
+ return browser;
19389
+ }
19390
+
19391
+ function renderAppRunnerSearchPathSection() {
19392
+ const config = activeAppRunnerCustomConfig();
19393
+ const searchPaths = activeAppRunnerSearchPaths();
19394
+ const section = make("section", "app-runner-info-section app-runner-search-path-section");
19395
+ const titleRow = make("div", "app-runner-section-title-row");
19396
+ titleRow.append(make("h3", "", "Project discovery paths"));
19397
+ if (config.displayProjectRoot) titleRow.append(make("code", "", config.displayProjectRoot));
19398
+ section.append(titleRow);
19399
+ section.append(make("p", "muted", "Scan extra project directories for runnable shell and Python scripts. Paths are project-local, relative to the project root, saved in .pi-webui-runners.json, and scanned one level deep only (no subdirectories). Supported scripts are .sh, .bash, .zsh, .fish, and .py files plus extensionless files with a bash/sh, zsh, fish, or Python shebang. Python scripts use uv and/or python3/python when available, and all discovered scripts run from the project root."));
19400
+
19401
+ const list = make("div", "app-runner-custom-list app-runner-search-path-list");
19402
+ if (!searchPaths.length) {
19403
+ list.append(make("div", "app-runner-custom-empty muted", "No project discovery paths configured. Built-in root, dev/, scripts/, and dev/scripts/ detection still applies."));
19404
+ } else {
19405
+ for (const searchPath of searchPaths) {
19406
+ const row = make("div", "app-runner-custom-item app-runner-search-path-item");
19407
+ const details = make("div", "app-runner-custom-item-details");
19408
+ details.append(make("code", "", appRunnerSearchPathLabel(searchPath)));
19409
+ const diagnostic = (Array.isArray(config.diagnostics) ? config.diagnostics : []).find((item) => item?.message && item.path === searchPath);
19410
+ if (diagnostic) {
19411
+ row.classList.add("unavailable");
19412
+ details.append(make("span", "app-runner-custom-warning", diagnostic.message));
19413
+ }
19414
+ const actions = make("div", "app-runner-custom-item-actions");
19415
+ const remove = make("button", "danger", "Remove");
19416
+ remove.type = "button";
19417
+ remove.title = `Stop scanning ${appRunnerSearchPathLabel(searchPath)}`;
19418
+ remove.setAttribute("aria-label", `Remove project discovery path ${appRunnerSearchPathLabel(searchPath)}`);
19419
+ remove.addEventListener("click", () => removeAppRunnerSearchPath(searchPath));
19420
+ actions.append(remove);
19421
+ row.append(details, actions);
19422
+ list.append(row);
19423
+ }
19424
+ }
19425
+ section.append(list);
19426
+
19427
+ const form = make("div", "app-runner-custom-form app-runner-search-path-form");
19428
+ const field = make("label", "app-runner-custom-field");
19429
+ field.setAttribute("for", "appRunnerSearchPathInput");
19430
+ field.append(make("span", "", "Project-relative directory"));
19431
+ const input = make("input", "dialog-input");
19432
+ input.id = "appRunnerSearchPathInput";
19433
+ input.type = "text";
19434
+ input.value = appRunnerSearchPathDraft;
19435
+ input.placeholder = "tools";
19436
+ input.autocomplete = "off";
19437
+ input.spellcheck = false;
19438
+ input.setAttribute("aria-label", "Project-relative directory to scan for shell and Python scripts");
19439
+ field.append(input);
19440
+ field.append(make("small", "muted", `Use . for the project root. Up to ${APP_RUNNER_SEARCH_PATH_LIMIT} paths; absolute paths and .. segments are rejected.`));
19441
+ input.addEventListener("input", () => { appRunnerSearchPathDraft = input.value; });
19442
+ input.addEventListener("keydown", (event) => {
19443
+ if (event.key !== "Enter") return;
19444
+ event.preventDefault();
19445
+ addAppRunnerSearchPath(form);
19446
+ });
19447
+ const pathRow = make("div", "app-runner-custom-path-row");
19448
+ pathRow.append(field);
19449
+ const browse = make("button", "app-runner-custom-browse", "Browse…");
19450
+ browse.type = "button";
19451
+ browse.title = "Browse project directories";
19452
+ browse.addEventListener("click", () => loadAppRunnerDirectoryBrowser(normalizeAppRunnerSearchPathInput(appRunnerSearchPathDraft) === "." ? "" : normalizeAppRunnerSearchPathInput(appRunnerSearchPathDraft)));
19453
+ pathRow.append(browse);
19454
+ form.append(pathRow);
19455
+
19456
+ const formActions = make("div", "app-runner-custom-form-actions");
19457
+ const add = make("button", "primary", "Add path");
19458
+ add.id = "appRunnerSearchPathAddButton";
19459
+ add.type = "button";
19460
+ add.addEventListener("click", () => addAppRunnerSearchPath(form));
19461
+ const clear = make("button", "", "Reset");
19462
+ clear.type = "button";
19463
+ clear.addEventListener("click", () => {
19464
+ appRunnerSearchPathDraft = "";
19465
+ appRunnerDirectoryBrowserState = { open: false, loading: false, path: "", data: null, error: "" };
19466
+ setAppRunnerSearchPathFeedback("", "");
19467
+ renderAppRunnerInfoDialog();
19468
+ });
19469
+ formActions.append(add, clear);
19470
+ form.append(formActions);
19471
+ if (appRunnerSearchPathFeedback.message) form.append(make("div", `app-runner-custom-feedback ${appRunnerSearchPathFeedback.type || "info"}`, appRunnerSearchPathFeedback.message));
19472
+ const browser = renderAppRunnerDirectoryBrowser();
19473
+ if (browser) form.append(browser);
19474
+ section.append(form);
19475
+ return section;
19476
+ }
19477
+
18339
19478
  async function loadAppRunnerFileBrowser(relativePath = "") {
18340
19479
  const tabContext = activeTabContext();
18341
19480
  const path = String(relativePath || "").replace(/^\.\/+/, "").replace(/\/+$/g, "");
@@ -18488,9 +19627,14 @@ function renderAppRunnerControls() {
18488
19627
  const running = appRunnerIsRunning(activeRun);
18489
19628
  menu.hidden = false;
18490
19629
  menu.classList.toggle("has-runners", runners.length > 0);
19630
+ menu.classList.toggle("no-runners", runners.length === 0);
18491
19631
  if (elements.appRunnerInfoButton) {
18492
- elements.appRunnerInfoButton.hidden = runners.length === 0;
18493
- elements.appRunnerInfoButton.disabled = runners.length === 0;
19632
+ elements.appRunnerInfoButton.hidden = false;
19633
+ elements.appRunnerInfoButton.disabled = false;
19634
+ elements.appRunnerInfoButton.title = runners.length
19635
+ ? "Explain app runners and configure project discovery paths"
19636
+ : "No app runners detected: configure project discovery paths or custom runners";
19637
+ elements.appRunnerInfoButton.setAttribute("aria-label", elements.appRunnerInfoButton.title);
18494
19638
  }
18495
19639
  button.disabled = running;
18496
19640
  button.title = running
@@ -18508,7 +19652,8 @@ function renderAppRunnerControls() {
18508
19652
  item.type = "button";
18509
19653
  item.setAttribute("role", "menuitem");
18510
19654
  const runnerDisplayCommand = runner.shortDisplayCommand || runner.displayCommand;
18511
- item.title = runner.description ? `${runnerDisplayCommand}\n${runner.description}` : runnerDisplayCommand;
19655
+ const runnerSource = appRunnerSourceLabel(runner, runnerDisplayCommand);
19656
+ item.title = [runnerDisplayCommand, runnerSource, runner.description].filter(Boolean).join("\n");
18512
19657
  item.addEventListener("click", () => runAppRunner(runner.id));
18513
19658
  const label = make("span", "app-runner-menu-item-label", runner.label || runnerDisplayCommand);
18514
19659
  const command = make("span", "app-runner-menu-item-command", runnerDisplayCommand);
@@ -18535,6 +19680,8 @@ function renderAppRunnerInfoDialog() {
18535
19680
  make("strong", "", runner.label || command || "runner"),
18536
19681
  make("code", "", command || "detected command"),
18537
19682
  );
19683
+ const source = appRunnerSourceLabel(runner, command);
19684
+ if (source) item.append(make("span", "app-runner-info-source muted", source));
18538
19685
  if (runner.description) item.append(make("span", "", runner.description));
18539
19686
  list.append(item);
18540
19687
  }
@@ -18552,6 +19699,7 @@ function renderAppRunnerInfoDialog() {
18552
19699
  "Starting a runner keeps live output pinned above the chat/terminal area.",
18553
19700
  "While a runner is active, the widget can send line-oriented stdin to interactive scripts.",
18554
19701
  "Only one app runner can be active per tab; Close/Stop terminates the process/server.",
19702
+ "Project discovery paths are project-local, relative to the project root, and scanned one level deep only.",
18555
19703
  ]) howList.append(make("li", "", line));
18556
19704
  how.append(howList);
18557
19705
 
@@ -18561,7 +19709,7 @@ function renderAppRunnerInfoDialog() {
18561
19709
  for (const itemText of APP_RUNNER_SUPPORTED_ITEMS) supportedList.append(make("li", "", itemText));
18562
19710
  supported.append(supportedList);
18563
19711
 
18564
- body.append(current, renderAppRunnerCustomSection(), how, supported);
19712
+ body.append(current, renderAppRunnerSearchPathSection(), renderAppRunnerCustomSection(), how, supported);
18565
19713
  }
18566
19714
 
18567
19715
  function openAppRunnerInfoDialog() {
@@ -18589,6 +19737,7 @@ function renderAppRunnerInputForm(run) {
18589
19737
  input.setAttribute("aria-label", "Send input to app runner stdin");
18590
19738
  input.addEventListener("input", () => { appRunnerInputDraftByRun.set(key, input.value); });
18591
19739
  input.addEventListener("keydown", (event) => {
19740
+ if (insertNumpadDecimal(event)) return;
18592
19741
  if (event.key !== "Enter" || event.shiftKey) return;
18593
19742
  event.preventDefault();
18594
19743
  form.requestSubmit();
@@ -19799,6 +20948,7 @@ function renderWidgets() {
19799
20948
  for (const [key, value] of widgets) {
19800
20949
  const widgetFeatureId = optionalFeatureWidgetFeatureId(key);
19801
20950
  if (widgetFeatureId && !isOptionalFeatureEnabled(widgetFeatureId)) continue;
20951
+ if (widgetFeatureId === "workflows" && workflowOverlayIsMinimized()) continue;
19802
20952
  if (widgetFeatureId && optionalFeatureWidgetHasSpecializedRenderer(key)) continue;
19803
20953
  const lines = Array.isArray(value.widgetLines) ? value.widgetLines : [];
19804
20954
  if (key === "pi-remote-webui") continue;
@@ -24431,13 +25581,64 @@ const WEBUI_TOOL_RENDERERS = {
24431
25581
  ls: renderLsToolExecution,
24432
25582
  };
24433
25583
 
24434
- function renderToolExecution(parent, message) {
25584
+ function renderSingleToolExecution(parent, message) {
24435
25585
  const tool = normalizeToolExecution(message);
24436
25586
  const renderer = WEBUI_TOOL_RENDERERS[tool.name] || renderGenericToolExecution;
24437
25587
  renderer(parent, tool);
24438
25588
  appendToolRawDetails(parent, tool);
24439
25589
  }
24440
25590
 
25591
+ function renderWorkflowStatusStack(parent, message) {
25592
+ const updates = Array.isArray(message?.workflowStatusUpdates) ? message.workflowStatusUpdates : [];
25593
+ const latest = updates.at(-1);
25594
+ if (!latest) return;
25595
+ const snapshot = workflowStatusSnapshot(toolResultText(toolExecutionResult(latest)));
25596
+ const hasStructuredSnapshot = snapshot.workflow || snapshot.run || snapshot.status || snapshot.tasks;
25597
+ const countLabel = `${updates.length} update${updates.length === 1 ? "" : "s"}`;
25598
+ const snapshotFields = [["Workflow", snapshot.workflow], ["Run", snapshot.run], ["Status", snapshot.status], ["Tasks", snapshot.tasks]];
25599
+ const latestLabel = hasStructuredSnapshot
25600
+ ? `latest ${snapshotFields.filter(([, value]) => value).map(([label, value]) => `${label} ${value}`).join(", ")}`
25601
+ : `latest ${snapshot.fallback}`;
25602
+
25603
+ const details = make("details", "workflow-status-stack-details");
25604
+ details.open = !!message.isError;
25605
+ const summary = make("summary", "workflow-status-stack-summary");
25606
+ summary.setAttribute("aria-label", `Workflow status updates, ${countLabel}; ${latestLabel}${message.isError ? "; contains an error" : ""}`);
25607
+ const heading = make("span", "workflow-status-stack-heading");
25608
+ heading.append(make("span", "tool-name", "workflow_status"), make("span", "workflow-status-stack-count", countLabel));
25609
+ if (message.isError) heading.append(make("span", "workflow-status-stack-error", "contains error"));
25610
+ const snapshotLine = make("span", "workflow-status-stack-snapshot");
25611
+ if (hasStructuredSnapshot) {
25612
+ for (const [label, value] of snapshotFields) {
25613
+ if (value) snapshotLine.append(make("span", "workflow-status-stack-field", `${label}: ${value}`));
25614
+ }
25615
+ } else {
25616
+ snapshotLine.append(make("span", "workflow-status-stack-field", snapshot.fallback));
25617
+ }
25618
+ summary.append(heading, snapshotLine);
25619
+
25620
+ const members = make("div", "workflow-status-stack-members");
25621
+ updates.forEach((update, index) => {
25622
+ const member = make("section", `workflow-status-stack-member${update?.isError || update?.result?.isError ? " error" : ""}`);
25623
+ const memberTitleText = [`Update ${index + 1} of ${updates.length}`, formatDate(update?.timestamp), toolExecutionStatus(update)].filter(Boolean).join(" · ");
25624
+ const memberTitle = make("div", "workflow-status-stack-member-title", memberTitleText);
25625
+ const memberBody = make("div", "workflow-status-stack-member-body");
25626
+ renderSingleToolExecution(memberBody, update);
25627
+ member.append(memberTitle, memberBody);
25628
+ members.append(member);
25629
+ });
25630
+ details.append(summary, members);
25631
+ parent.append(details);
25632
+ }
25633
+
25634
+ function renderToolExecution(parent, message) {
25635
+ if (message?.role === "workflowStatusStack") {
25636
+ renderWorkflowStatusStack(parent, message);
25637
+ return;
25638
+ }
25639
+ renderSingleToolExecution(parent, message);
25640
+ }
25641
+
24441
25642
  function liveToolRunMessage(run) {
24442
25643
  return {
24443
25644
  role: "toolExecution",
@@ -24746,6 +25947,9 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
24746
25947
  } else if (message.role === "toolExecution") {
24747
25948
  renderToolExecution(body, message);
24748
25949
  bubble._toolRenderSignature = toolExecutionRenderSignature(message);
25950
+ } else if (message.role === "workflowStatusStack") {
25951
+ renderToolExecution(body, message);
25952
+ if (message.isError) bubble.classList.add("error");
24749
25953
  } else if (message.role === "thinking") {
24750
25954
  const thinkingText = visibleThinkingText(message.thinking || textFromContent(message.content));
24751
25955
  if (thinkingOutputVisible && thinkingText) appendThinkingMarkdown(body, thinkingText);
@@ -24776,7 +25980,7 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
24776
25980
  } else {
24777
25981
  bubble.append(header, body);
24778
25982
  }
24779
- attachMessageCopyButton(bubble, message, body);
25983
+ if (message.role !== "workflowStatusStack") attachMessageCopyButton(bubble, message, body);
24780
25984
  attachMessageEditRetryButton(bubble, message, messageIndex, { streaming, transient });
24781
25985
  if (!streaming && !transient) renderActionFeedbackControls(bubble, message, messageIndex);
24782
25986
  return { bubble, body };
@@ -24800,6 +26004,27 @@ function appendMessage(message, options = {}) {
24800
26004
  return created;
24801
26005
  }
24802
26006
 
26007
+ function appendOptimisticUserPrompt(message, attachmentCount = 0) {
26008
+ const text = String(message || "").trim() || `${attachmentCount} attachment${attachmentCount === 1 ? "" : "s"}`;
26009
+ appendMessage({ role: "user", title: "you", timestamp: Date.now(), content: text }, { transient: true, animateEntry: true });
26010
+ if (autoFollowChat || isChatNearBottom()) scrollChatToBottom({ force: true });
26011
+ }
26012
+
26013
+ function toolExecutionMessageFromCall(displayMessage, { result = toolResultForCallId(displayMessage?.toolCallId), liveRun = liveToolRuns.get(displayMessage?.toolCallId) } = {}) {
26014
+ return {
26015
+ ...displayMessage,
26016
+ role: "toolExecution",
26017
+ title: `tool: ${displayMessage?.toolName || "unknown"}`,
26018
+ arguments: liveRun?.arguments ?? displayMessage?.arguments,
26019
+ result: result || liveRun?.result || null,
26020
+ isPartial: !result && !!liveRun?.isPartial,
26021
+ isError: !!(result?.isError || liveRun?.isError),
26022
+ startedAt: liveRun?.startedAt || null,
26023
+ endedAt: liveRun?.endedAt || null,
26024
+ live: !!liveRun && !result,
26025
+ };
26026
+ }
26027
+
24803
26028
  function appendTranscriptMessage(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, reusableToolCards = null, itemKey = "" } = {}) {
24804
26029
  if (streaming || transient || message?.role !== "assistant") {
24805
26030
  return appendMessage(message, { streaming, messageIndex, transient, animateEntry, reusableToolCards, itemKey });
@@ -24811,20 +26036,7 @@ function appendTranscriptMessage(message, { streaming = false, messageIndex = -1
24811
26036
  displayMessages.forEach((displayMessage) => {
24812
26037
  let transcriptMessage = displayMessage;
24813
26038
  if (displayMessage.role === "toolCall" && displayMessage.toolCallId) {
24814
- const result = toolResultForCallId(displayMessage.toolCallId);
24815
- const liveRun = liveToolRuns.get(displayMessage.toolCallId);
24816
- transcriptMessage = {
24817
- ...displayMessage,
24818
- role: "toolExecution",
24819
- title: `tool: ${displayMessage.toolName || "unknown"}`,
24820
- arguments: liveRun?.arguments ?? displayMessage.arguments,
24821
- result: result || liveRun?.result || null,
24822
- isPartial: !result && !!liveRun?.isPartial,
24823
- isError: !!(result?.isError || liveRun?.isError),
24824
- startedAt: liveRun?.startedAt || null,
24825
- endedAt: liveRun?.endedAt || null,
24826
- live: !!liveRun && !result,
24827
- };
26039
+ transcriptMessage = toolExecutionMessageFromCall(displayMessage);
24828
26040
  }
24829
26041
  if (compactTranscript && transcriptMessage.role !== "assistant") return;
24830
26042
  if (transcriptMessage.role === "thinking" && !thinkingOutputVisible) return;
@@ -25176,6 +26388,29 @@ function compactStoredTranscriptItems() {
25176
26388
  return items;
25177
26389
  }
25178
26390
 
26391
+ function workflowStatusExecutionFromTranscriptItem(item, toolResults) {
26392
+ const message = item?.message;
26393
+ if (isCompletedWorkflowStatusExecution(message)) return message;
26394
+ if (message?.role !== "assistant") return null;
26395
+ const visibleMessages = assistantDisplayMessages(message)
26396
+ .filter((displayMessage) => displayMessage.role !== "thinking" || thinkingOutputVisible);
26397
+ if (visibleMessages.length !== 1) return null;
26398
+ const toolCall = visibleMessages[0];
26399
+ if (toolCall.role !== "toolCall" || toolCall.toolName !== "workflow_status" || !toolCall.toolCallId) return null;
26400
+ const result = toolResults instanceof Map ? toolResults.get(toolCall.toolCallId) : toolResultForCallId(toolCall.toolCallId);
26401
+ if (!result) return null;
26402
+ return toolExecutionMessageFromCall(toolCall, { result, liveRun: liveToolRuns.get(toolCall.toolCallId) });
26403
+ }
26404
+
26405
+ function groupWorkflowStatusTranscriptItems(items, toolResults) {
26406
+ if (compactOutputActive()) return items;
26407
+ const projected = items.map((item) => {
26408
+ const execution = workflowStatusExecutionFromTranscriptItem(item, toolResults);
26409
+ return execution ? { ...item, message: execution } : item;
26410
+ });
26411
+ return groupConsecutiveWorkflowStatusItems(projected);
26412
+ }
26413
+
25179
26414
  function orderedTranscriptItems() {
25180
26415
  const items = compactOutputActive() ? compactStoredTranscriptItems() : [];
25181
26416
  const assistantToolCallIds = buildAssistantToolCallIdSet(latestMessages);
@@ -25196,7 +26431,8 @@ function orderedTranscriptItems() {
25196
26431
  items.push({ message, messageIndex: -1, transient: true, timestampMs: messageTimestampMs(message), order: liveOrder++ });
25197
26432
  }
25198
26433
  }
25199
- return items.sort((a, b) => a.timestampMs - b.timestampMs || a.order - b.order);
26434
+ const ordered = items.sort((a, b) => a.timestampMs - b.timestampMs || a.order - b.order);
26435
+ return groupWorkflowStatusTranscriptItems(ordered, toolResults);
25200
26436
  }
25201
26437
 
25202
26438
  /**
@@ -25300,6 +26536,8 @@ function messageStaticSignature(message) {
25300
26536
  contentSignature(message.result?.content),
25301
26537
  String(safeJsonLength(message.arguments)),
25302
26538
  );
26539
+ } else if (message.role === "workflowStatusStack") {
26540
+ for (const update of message.workflowStatusUpdates || []) sig.push(messageStaticSignature(update));
25303
26541
  }
25304
26542
  const joined = sig.join("|");
25305
26543
  if (cacheable) messageStaticSignatureCache.set(message, joined);
@@ -25401,8 +26639,19 @@ function applyNativeSlashCommandEffects(response, message, tabContext = activeTa
25401
26639
  });
25402
26640
  }
25403
26641
 
25404
- if (data.download && handleNativeDownloadResponse(data.download, data.command, data.serverPath)) {
25405
- addEvent(data.command === "export" ? `export ready: ${data.download.fileName || data.download.url}` : `download started: ${data.download.fileName || data.download.url}`, "info");
26642
+ if (data.download) {
26643
+ const downloadLabel = data.download.fileName || data.download.url || "unnamed download";
26644
+ try {
26645
+ const opened = handleNativeDownloadResponse(data.download, data.command, data.serverPath);
26646
+ if (opened) {
26647
+ addEvent(data.command === "export" ? `export ready: ${downloadLabel}` : `download started: ${downloadLabel}`, "info");
26648
+ } else {
26649
+ addEvent(`could not open ${data.command === "export" ? "HTML export" : "download"}: missing or invalid browser URL (${downloadLabel})`, "error");
26650
+ }
26651
+ } catch (error) {
26652
+ const reason = error?.message || String(error);
26653
+ addEvent(`could not open ${data.command === "export" ? "HTML export" : "download"} ${downloadLabel}: ${reason}`, "error");
26654
+ }
25406
26655
  }
25407
26656
 
25408
26657
  const cards = Array.isArray(data.cards) && data.cards.length ? data.cards : null;
@@ -25916,23 +27165,85 @@ async function refreshOptionalFeaturePackageStatuses({ announce = false } = {})
25916
27165
  }
25917
27166
  }
25918
27167
 
27168
+ function clearGitFooterPayloadState(tabId) {
27169
+ if (!tabId) return;
27170
+ gitFooterPayloadRequestSerialByTab.set(tabId, (gitFooterPayloadRequestSerialByTab.get(tabId) || 0) + 1);
27171
+ clearTimeout(gitFooterPayloadSettlementTimersByTab.get(tabId));
27172
+ gitFooterPayloadSettlementTimersByTab.delete(tabId);
27173
+ gitFooterPayloadStateByTab.delete(tabId);
27174
+ gitFooterPayloadRefreshInFlightByTab.delete(tabId);
27175
+ }
27176
+
27177
+ function settleGitFooterPayload(tabId, phase, error = "") {
27178
+ if (!tabId) return;
27179
+ clearTimeout(gitFooterPayloadSettlementTimersByTab.get(tabId));
27180
+ gitFooterPayloadSettlementTimersByTab.delete(tabId);
27181
+ gitFooterPayloadStateByTab.set(tabId, { phase, error });
27182
+ }
27183
+
27184
+ function waitForGitFooterPayloadSettlement(tabContext, requestSerial) {
27185
+ clearTimeout(gitFooterPayloadSettlementTimersByTab.get(tabContext.tabId));
27186
+ const timer = setTimeout(() => {
27187
+ gitFooterPayloadSettlementTimersByTab.delete(tabContext.tabId);
27188
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
27189
+ if (gitFooterPayloadStateByTab.get(tabContext.tabId)?.phase === "waiting") {
27190
+ settleGitFooterPayload(tabContext.tabId, "failed", "Git footer status was not received — refresh to retry");
27191
+ }
27192
+ if (isCurrentTabContext(tabContext)) renderFooter();
27193
+ }, GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS);
27194
+ gitFooterPayloadSettlementTimersByTab.set(tabContext.tabId, timer);
27195
+ }
27196
+
25919
27197
  function requestGitFooterWebuiPayload(tabContext = activeTabContext(), { force = false, silent = true, allowDuringRun = false } = {}) {
25920
27198
  if (!tabContext.tabId || isOptionalFeatureDisabled("gitFooterStatus")) return;
25921
27199
  if (!allowDuringRun && (currentState?.isStreaming || currentState?.isCompacting)) return;
25922
27200
  const refreshCommand = resolveAvailableCommandName("git-footer-refresh", { rpcOnly: true });
25923
- if (!refreshCommand || (!force && statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY))) return;
27201
+ if (!refreshCommand) {
27202
+ if (hasAvailableCommand("git-footer-refresh") || optionalFeatureAvailability.gitFooterStatus) {
27203
+ gitFooterPayloadRefreshInFlightByTab.delete(tabContext.tabId);
27204
+ const requestSerial = (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) || 0) + 1;
27205
+ gitFooterPayloadRequestSerialByTab.set(tabContext.tabId, requestSerial);
27206
+ settleGitFooterPayload(tabContext.tabId, "waiting");
27207
+ const timer = setTimeout(() => {
27208
+ gitFooterPayloadSettlementTimersByTab.delete(tabContext.tabId);
27209
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
27210
+ if (gitFooterPayloadStateByTab.get(tabContext.tabId)?.phase === "waiting") {
27211
+ settleGitFooterPayload(tabContext.tabId, "failed", "Git footer refresh command is unavailable — reload to retry");
27212
+ }
27213
+ if (isCurrentTabContext(tabContext)) renderFooter();
27214
+ }, GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS);
27215
+ gitFooterPayloadSettlementTimersByTab.set(tabContext.tabId, timer);
27216
+ if (isCurrentTabContext(tabContext)) renderFooter();
27217
+ }
27218
+ return;
27219
+ }
27220
+ if (!force && statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY)) return;
25924
27221
  if (gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId)) return;
25925
27222
 
27223
+ const requestSerial = (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) || 0) + 1;
27224
+ gitFooterPayloadRequestSerialByTab.set(tabContext.tabId, requestSerial);
27225
+ settleGitFooterPayload(tabContext.tabId, "waiting");
25926
27226
  gitFooterPayloadRefreshInFlightByTab.add(tabContext.tabId);
25927
27227
  if (isCurrentTabContext(tabContext)) renderFooter();
25928
27228
  return api("/api/prompt", {
25929
27229
  method: "POST",
25930
27230
  body: { message: `/${refreshCommand}${silent ? " --webui-silent" : ""}`, streamingBehavior: "steer" },
25931
27231
  tabId: tabContext.tabId,
27232
+ signal: AbortSignal.timeout(GIT_FOOTER_PAYLOAD_REQUEST_TIMEOUT_MS),
27233
+ }).then(() => {
27234
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
27235
+ if (gitFooterPayloadStateByTab.get(tabContext.tabId)?.phase === "waiting") waitForGitFooterPayloadSettlement(tabContext, requestSerial);
25932
27236
  }).catch((error) => {
25933
- if (isCurrentTabContext(tabContext)) addEvent(`git footer payload refresh failed: ${error.message || String(error)}`, "warn");
27237
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
27238
+ const message = `Git footer refresh failed: ${error.message || String(error)}`;
27239
+ settleGitFooterPayload(tabContext.tabId, "failed", "Git footer refresh failed — refresh to retry");
27240
+ if (isCurrentTabContext(tabContext)) {
27241
+ if (silent) addEvent(message, "warn");
27242
+ else surfaceRuntimeDiagnostic("Git footer refresh failed", message, "warn");
27243
+ }
25934
27244
  }).finally(() => {
25935
27245
  gitFooterPayloadRefreshInFlightByTab.delete(tabContext.tabId);
27246
+ if (gitFooterPayloadRequestSerialByTab.get(tabContext.tabId) !== requestSerial) return;
25936
27247
  if (isCurrentTabContext(tabContext)) renderFooter();
25937
27248
  });
25938
27249
  }
@@ -26210,6 +27521,16 @@ function renderOptionalFeatureControls() {
26210
27521
  );
26211
27522
  if (!hasNativeCommandMenu && nativeCommandMenuOpen) setNativeCommandMenuOpen(false);
26212
27523
 
27524
+ const hasWorkflowSetup = isOptionalFeatureEnabled("workflows") && hasLoadedRpcCommand("workflow-setup");
27525
+ if (elements.optionsWorkflowSetupButton) {
27526
+ elements.optionsWorkflowSetupButton.hidden = !hasWorkflowSetup;
27527
+ setOptionalControlState(
27528
+ elements.optionsWorkflowSetupButton,
27529
+ hasWorkflowSetup,
27530
+ commandUnavailableMessage("workflow-setup"),
27531
+ );
27532
+ }
27533
+
26213
27534
  const hasSafetyGuardSetup = isOptionalFeatureEnabled("safetyGuard") && hasAvailableCommand("safety-guard-setup");
26214
27535
  if (elements.optionsSafetyGuardSetupButton) {
26215
27536
  elements.optionsSafetyGuardSetupButton.hidden = !hasSafetyGuardSetup;
@@ -26972,7 +28293,7 @@ async function openNativeSettingsDialog() {
26972
28293
  autoCompact: state.autoCompactionEnabled !== false,
26973
28294
  steering: state.steeringMode || "one-at-a-time",
26974
28295
  followUp: state.followUpMode || "one-at-a-time",
26975
- busyBehavior,
28296
+ busyBehavior: busyPromptBehavior,
26976
28297
  density: interfaceDensity,
26977
28298
  doneNotifications: agentDoneNotificationsEnabled,
26978
28299
  });
@@ -27335,6 +28656,331 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
27335
28656
  }, "primary");
27336
28657
  }
27337
28658
 
28659
+ function normalizedWorkflowPolicyList(value) {
28660
+ return [...new Set(String(value || "").split("\n").map((entry) => entry.trim()).filter(Boolean))].sort();
28661
+ }
28662
+
28663
+ function parseWorkflowPolicyVerificationCommands(value) {
28664
+ const commands = [];
28665
+ for (const [index, line] of String(value || "").split("\n").entries()) {
28666
+ if (!line.trim()) continue;
28667
+ let command;
28668
+ try {
28669
+ command = JSON.parse(line);
28670
+ } catch (error) {
28671
+ throw new Error(`Verification command line ${index + 1} is not valid JSON: ${error.message || String(error)}`);
28672
+ }
28673
+ if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || part.length === 0)) {
28674
+ throw new Error(`Verification command line ${index + 1} must be a non-empty JSON string argv array.`);
28675
+ }
28676
+ commands.push(command);
28677
+ }
28678
+ return commands;
28679
+ }
28680
+
28681
+ function normalizeWorkflowPolicySuggestions(value) {
28682
+ const empty = { shellAllowlist: [], networkAllowlist: [], verificationCommands: [] };
28683
+ if (!value || typeof value !== "object" || Array.isArray(value)) return empty;
28684
+
28685
+ const normalizeStringGroup = (group) => {
28686
+ if (!Array.isArray(group) || group.some((item) => (
28687
+ typeof item !== "string"
28688
+ || !item
28689
+ || item.trim() !== item
28690
+ || item.includes("\n")
28691
+ || item.includes("\r")
28692
+ ))) return [];
28693
+ return [...new Set(group)];
28694
+ };
28695
+ const normalizeVerificationGroup = (group) => {
28696
+ if (!Array.isArray(group) || group.some((command) => (
28697
+ !Array.isArray(command)
28698
+ || command.length === 0
28699
+ || command.some((part) => typeof part !== "string" || part.length === 0)
28700
+ ))) return [];
28701
+ return [...new Set(group.map((command) => JSON.stringify(command)))];
28702
+ };
28703
+
28704
+ return {
28705
+ shellAllowlist: normalizeStringGroup(value.shellAllowlist),
28706
+ networkAllowlist: normalizeStringGroup(value.networkAllowlist),
28707
+ verificationCommands: normalizeVerificationGroup(value.verificationCommands),
28708
+ };
28709
+ }
28710
+
28711
+ function workflowPolicyPresentSuggestionLines(textarea, kind) {
28712
+ if (kind !== "verification") return new Set(normalizedWorkflowPolicyList(textarea.value));
28713
+ const present = new Set();
28714
+ for (const line of String(textarea.value || "").split("\n")) {
28715
+ if (!line.trim()) continue;
28716
+ try {
28717
+ const command = JSON.parse(line);
28718
+ if (Array.isArray(command) && command.length > 0 && command.every((part) => typeof part === "string" && part.length > 0)) {
28719
+ present.add(JSON.stringify(command));
28720
+ }
28721
+ } catch {
28722
+ // Invalid manual lines remain editable and are reported by the normalized preview.
28723
+ }
28724
+ }
28725
+ return present;
28726
+ }
28727
+
28728
+ function appendWorkflowPolicySuggestion(textarea, line) {
28729
+ const separator = textarea.value && !textarea.value.endsWith("\n") ? "\n" : "";
28730
+ textarea.value = `${textarea.value}${separator}${line}`;
28731
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
28732
+ textarea.focus();
28733
+ }
28734
+
28735
+ function workflowPolicySuggestionGroup(label, textarea, suggestions, kind, id) {
28736
+ if (!suggestions.length) return null;
28737
+ const group = make("div", "workflow-policy-suggestions");
28738
+ group.setAttribute("role", "group");
28739
+ const labelNode = make("span", "workflow-policy-suggestions-label", label);
28740
+ labelNode.id = `${id}SuggestionsLabel`;
28741
+ group.setAttribute("aria-labelledby", labelNode.id);
28742
+ group.append(labelNode);
28743
+
28744
+ const buttons = suggestions.map((line) => {
28745
+ const button = make("button", "workflow-policy-suggestion", `Add ${line}`);
28746
+ button.type = "button";
28747
+ button.setAttribute("aria-label", `${label}: add ${line}`);
28748
+ button.addEventListener("click", () => appendWorkflowPolicySuggestion(textarea, line));
28749
+ group.append(button);
28750
+ return { button, line };
28751
+ });
28752
+ const sync = () => {
28753
+ const present = workflowPolicyPresentSuggestionLines(textarea, kind);
28754
+ for (const { button, line } of buttons) button.disabled = present.has(line);
28755
+ };
28756
+ textarea.addEventListener("input", sync);
28757
+ sync();
28758
+ return { element: group, sync };
28759
+ }
28760
+
28761
+ function workflowPolicyTextarea(label, value, hint, id, { suggestions = [], suggestionLabel = "Suggestions", kind = "list" } = {}) {
28762
+ const field = make("div", "native-settings-field workflow-policy-field");
28763
+ const labelNode = make("label", "native-settings-label", label);
28764
+ labelNode.htmlFor = id;
28765
+ field.append(labelNode);
28766
+ const textarea = make("textarea", "workflow-policy-textarea");
28767
+ textarea.id = id;
28768
+ textarea.value = value;
28769
+ textarea.rows = 5;
28770
+ textarea.autocomplete = "off";
28771
+ textarea.spellcheck = false;
28772
+ const hintNode = make("span", "native-settings-hint", hint);
28773
+ hintNode.id = `${id}Hint`;
28774
+ textarea.setAttribute("aria-describedby", hintNode.id);
28775
+ const suggestionGroup = workflowPolicySuggestionGroup(suggestionLabel, textarea, suggestions, kind, id);
28776
+ field.append(textarea);
28777
+ if (suggestionGroup) field.append(suggestionGroup.element);
28778
+ field.append(hintNode);
28779
+ return { field, textarea, syncSuggestions: suggestionGroup?.sync || (() => {}) };
28780
+ }
28781
+
28782
+ function workflowPolicyDraftSignature(controls) {
28783
+ return JSON.stringify({
28784
+ permissions: {
28785
+ write: controls.write.input.checked,
28786
+ shell: controls.shell.input.checked,
28787
+ network: controls.network.input.checked,
28788
+ },
28789
+ shellAllowlist: controls.shellAllowlist.textarea.value,
28790
+ networkAllowlist: controls.networkAllowlist.textarea.value,
28791
+ verificationCommands: controls.verificationCommands.textarea.value,
28792
+ });
28793
+ }
28794
+
28795
+ function collectWorkflowPolicyFromControls(controls) {
28796
+ return {
28797
+ schemaVersion: 1,
28798
+ permissions: {
28799
+ write: controls.write.input.checked,
28800
+ shell: controls.shell.input.checked,
28801
+ network: controls.network.input.checked,
28802
+ },
28803
+ shellAllowlist: normalizedWorkflowPolicyList(controls.shellAllowlist.textarea.value),
28804
+ networkAllowlist: normalizedWorkflowPolicyList(controls.networkAllowlist.textarea.value),
28805
+ verificationCommands: parseWorkflowPolicyVerificationCommands(controls.verificationCommands.textarea.value),
28806
+ };
28807
+ }
28808
+
28809
+ function applyDeniedWorkflowPolicyControls(controls) {
28810
+ controls.write.input.checked = false;
28811
+ controls.shell.input.checked = false;
28812
+ controls.network.input.checked = false;
28813
+ controls.shellAllowlist.textarea.value = "";
28814
+ controls.networkAllowlist.textarea.value = "";
28815
+ controls.verificationCommands.textarea.value = "";
28816
+ }
28817
+
28818
+ async function openNativeWorkflowSetupDialog() {
28819
+ openNativeCommandDialog({
28820
+ title: "/workflow-setup",
28821
+ message: "Review and save the global workflow permission ceiling. This browser flow never starts an agent turn.",
28822
+ });
28823
+ renderNativeLoading("Loading workflow permission ceiling…");
28824
+
28825
+ let data;
28826
+ try {
28827
+ const response = await api("/api/workflow-policy", { scoped: false });
28828
+ data = response.data || {};
28829
+ } catch (error) {
28830
+ setNativeCommandError(`Could not load workflow policy: ${error.message || String(error)}`);
28831
+ elements.nativeCommandBody.replaceChildren();
28832
+ return;
28833
+ }
28834
+
28835
+ const deniedPolicy = {
28836
+ schemaVersion: 1,
28837
+ permissions: { write: false, shell: false, network: false },
28838
+ shellAllowlist: [],
28839
+ networkAllowlist: [],
28840
+ verificationCommands: [],
28841
+ };
28842
+ const policy = data.policy || deniedPolicy;
28843
+ const suggestions = normalizeWorkflowPolicySuggestions(data.suggestions);
28844
+ const controls = {
28845
+ write: nativeSettingToggle("Allow write", policy.permissions?.write === true, "Ceiling for workflow write capability; each workflow still has to request it.", { label: "global", tone: "safety" }),
28846
+ shell: nativeSettingToggle("Allow shell", policy.permissions?.shell === true, "Ceiling for workflow shell capability; the executable allowlist is not a sandbox.", { label: "global", tone: "safety" }),
28847
+ network: nativeSettingToggle("Allow network", policy.permissions?.network === true, "Ceiling for workflow network capability; each workflow still has to request it.", { label: "global", tone: "safety" }),
28848
+ shellAllowlist: workflowPolicyTextarea(
28849
+ "Shell executable allowlist",
28850
+ Array.isArray(policy.shellAllowlist) ? policy.shellAllowlist.join("\n") : "",
28851
+ "One executable entry per line. Entries are trimmed, deduplicated, and sorted in the preview. This is not an OS sandbox.",
28852
+ "workflowPolicyShellAllowlist",
28853
+ { suggestions: suggestions.shellAllowlist, suggestionLabel: "Shell executable suggestions" },
28854
+ ),
28855
+ networkAllowlist: workflowPolicyTextarea(
28856
+ "Network host allowlist",
28857
+ Array.isArray(policy.networkAllowlist) ? policy.networkAllowlist.join("\n") : "",
28858
+ "One host entry per line. Entries are trimmed, deduplicated, and sorted in the preview.",
28859
+ "workflowPolicyNetworkAllowlist",
28860
+ { suggestions: suggestions.networkAllowlist, suggestionLabel: "Network host suggestions" },
28861
+ ),
28862
+ verificationCommands: workflowPolicyTextarea(
28863
+ "Verification commands",
28864
+ Array.isArray(policy.verificationCommands) ? policy.verificationCommands.map((command) => JSON.stringify(command)).join("\n") : "",
28865
+ 'One JSON argv array per line, in execution order; for example ["npm","test"]. Blank lines are ignored.',
28866
+ "workflowPolicyVerificationCommands",
28867
+ { suggestions: suggestions.verificationCommands, suggestionLabel: "Verification command suggestions", kind: "verification" },
28868
+ ),
28869
+ };
28870
+
28871
+ const preview = make("pre", "workflow-policy-preview");
28872
+ preview.tabIndex = 0;
28873
+ preview.setAttribute("aria-label", "Exact normalized workflow policy JSON preview");
28874
+ const verificationStatus = make("p", "workflow-policy-verification-status muted");
28875
+ verificationStatus.setAttribute("role", "status");
28876
+ verificationStatus.setAttribute("aria-live", "polite");
28877
+ const previewSection = make("section", "workflow-policy-review");
28878
+ previewSection.append(make("h3", undefined, "Exact normalized JSON preview"), preview, verificationStatus);
28879
+
28880
+ const body = make("div", "native-settings-panel workflow-policy-panel");
28881
+ body.append(
28882
+ nativeSettingsNote("Authorization ceiling", "This ceiling is not blanket authority. Every workflow and agent call must still request its own capabilities, and all runtime restrictions still apply."),
28883
+ nativeSettingsNote("Shell safety", "The shell executable allowlist limits admitted commands only; it is not an OS sandbox."),
28884
+ nativeSettingsNote("Persistence", `${data.exists ? "Loaded" : "No file exists yet; Save is required to create"} ${data.filePath || "~/.pi/agent/workflow-policy.json"}. Browser data cannot choose another target.`),
28885
+ nativeSettingsSection("Permission toggles", "Lists may stay populated while a permission is off, but runtime authority remains off.", [controls.write, controls.shell, controls.network], { open: true }),
28886
+ nativeSettingsSection("Shell and network allowlists", "Enter one canonicalizable value per line.", [controls.shellAllowlist, controls.networkAllowlist], { open: true }),
28887
+ nativeSettingsSection("Ordered verification", "Each nonblank line is one JSON argv array. Line order is preserved.", [controls.verificationCommands], { open: true }),
28888
+ previewSection,
28889
+ );
28890
+ elements.nativeCommandBody.replaceChildren(body);
28891
+ elements.nativeCommandActions.replaceChildren();
28892
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
28893
+
28894
+ const initialDraftSignature = workflowPolicyDraftSignature(controls);
28895
+ let candidatePolicy = null;
28896
+ let saveButton;
28897
+ const renderPreview = () => {
28898
+ controls.shellAllowlist.syncSuggestions();
28899
+ controls.networkAllowlist.syncSuggestions();
28900
+ controls.verificationCommands.syncSuggestions();
28901
+ nativeSettingsDirty = workflowPolicyDraftSignature(controls) !== initialDraftSignature;
28902
+ try {
28903
+ candidatePolicy = collectWorkflowPolicyFromControls(controls);
28904
+ preview.textContent = JSON.stringify(candidatePolicy, null, 2);
28905
+ setNativeCommandError("");
28906
+ verificationStatus.textContent = candidatePolicy.verificationCommands.length
28907
+ ? `${candidatePolicy.verificationCommands.length} ordered verification command${candidatePolicy.verificationCommands.length === 1 ? "" : "s"} configured.`
28908
+ : "No verification commands are configured. Applying workflow worktrees will require an explicit empty-verification waiver.";
28909
+ verificationStatus.classList.toggle("warning", candidatePolicy.verificationCommands.length === 0);
28910
+ if (saveButton) saveButton.disabled = false;
28911
+ } catch (error) {
28912
+ candidatePolicy = null;
28913
+ preview.textContent = "Normalized preview unavailable until the editor error is fixed.";
28914
+ verificationStatus.textContent = "Fix the verification editor before review and save.";
28915
+ verificationStatus.classList.add("warning");
28916
+ setNativeCommandError(error.message || String(error));
28917
+ if (saveButton) saveButton.disabled = true;
28918
+ }
28919
+ };
28920
+ body.addEventListener("input", renderPreview);
28921
+ body.addEventListener("change", renderPreview);
28922
+
28923
+ addNativeCommandAction("Reset to all deny", () => {
28924
+ applyDeniedWorkflowPolicyControls(controls);
28925
+ renderPreview();
28926
+ controls.write.input.focus();
28927
+ });
28928
+
28929
+ saveButton = addNativeCommandAction("Review and save", async () => {
28930
+ renderPreview();
28931
+ if (!candidatePolicy) return;
28932
+ const policyToSave = candidatePolicy;
28933
+ const normalizedPreview = JSON.stringify(policyToSave, null, 2);
28934
+ const verificationReview = policyToSave.verificationCommands.length
28935
+ ? `Verification commands: ${policyToSave.verificationCommands.length} configured in the shown order.`
28936
+ : "Verification commands: none — applying workflow worktrees will require an explicit empty-verification waiver.";
28937
+ const reviewed = await appConfirm({
28938
+ title: "Save reviewed workflow permission ceiling?",
28939
+ summary: [
28940
+ `Target: ${data.filePath}`,
28941
+ `Expected revision: ${data.revision ?? "missing (the file is created only after Save)"}`,
28942
+ "This is an authorization ceiling, not blanket authority.",
28943
+ "The shell allowlist is not an OS sandbox.",
28944
+ verificationReview,
28945
+ "",
28946
+ "Exact normalized JSON:",
28947
+ normalizedPreview,
28948
+ ].join("\n"),
28949
+ affected: data.filePath || "The global workflow policy",
28950
+ undoable: false,
28951
+ confirmLabel: "Save reviewed policy",
28952
+ });
28953
+ if (!reviewed) return;
28954
+
28955
+ setNativeActionBusy(saveButton, true, "Saving…");
28956
+ setNativeCommandError("");
28957
+ try {
28958
+ const response = await api("/api/workflow-policy", {
28959
+ method: "POST",
28960
+ body: { policy: policyToSave, expectedRevision: data.revision ?? null },
28961
+ scoped: false,
28962
+ });
28963
+ const saved = response.data || {};
28964
+ addTransientMessage({
28965
+ role: "native",
28966
+ title: "/workflow-setup",
28967
+ content: `Saved the global workflow permission ceiling to ${saved.filePath || data.filePath}. No agent turn was started.`,
28968
+ level: "info",
28969
+ });
28970
+ nativeSettingsDirty = false;
28971
+ closeNativeCommandDialog({ force: true });
28972
+ } catch (error) {
28973
+ const message = error.message || String(error);
28974
+ setNativeCommandError(error.statusCode === 409
28975
+ ? `${message} Reload /workflow-setup and review the latest policy before saving again.`
28976
+ : `Workflow policy save failed: ${message}`);
28977
+ } finally {
28978
+ setNativeActionBusy(saveButton, false);
28979
+ }
28980
+ }, "primary");
28981
+ renderPreview();
28982
+ }
28983
+
27338
28984
  async function openNativeForkSelector() {
27339
28985
  openNativeCommandDialog({ title: "/fork", message: "Choose a previous user message to fork before.", searchPlaceholder: "Filter fork points…" });
27340
28986
  renderNativeLoading("Loading fork points…");
@@ -27889,6 +29535,14 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
27889
29535
  const name = slashCommandName(message);
27890
29536
  if (!NATIVE_SELECTOR_COMMANDS.has(name)) return false;
27891
29537
  const featureId = optionalFeatureIdForCommand(name);
29538
+ if (name === "workflow-setup" && !hasLoadedRpcCommand(name)) {
29539
+ const tabContext = activeTabContext();
29540
+ addEvent(commandUnavailableMessage(name), "warn");
29541
+ refreshCommands(tabContext).catch((error) => {
29542
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
29543
+ });
29544
+ return true;
29545
+ }
27892
29546
  if (featureId && !isOptionalFeatureEnabled(featureId)) {
27893
29547
  const tabContext = activeTabContext();
27894
29548
  addEvent(commandUnavailableMessage(name), "warn");
@@ -27910,6 +29564,9 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
27910
29564
  case "settings":
27911
29565
  await openNativeSettingsDialog();
27912
29566
  return true;
29567
+ case "workflow-setup":
29568
+ await openNativeWorkflowSetupDialog();
29569
+ return true;
27913
29570
  case "safety-guard-setup":
27914
29571
  await openNativeSafetyGuardSetupDialog();
27915
29572
  return true;
@@ -27958,6 +29615,21 @@ function shouldSendPromptFromEnter(event) {
27958
29615
  return !isMobileView();
27959
29616
  }
27960
29617
 
29618
+ function insertNumpadDecimal(event) {
29619
+ const isNumpadDecimal = event.code === "NumpadDecimal"
29620
+ || event.keyCode === 110
29621
+ || (event.location === 3 && [".", ",", "Decimal", "Delete"].includes(event.key));
29622
+ if (event.defaultPrevented || !isNumpadDecimal || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey || event.isComposing) return false;
29623
+ const input = event.currentTarget;
29624
+ if (!input || input.disabled || input.readOnly || typeof input.setRangeText !== "function") return false;
29625
+ const start = input.selectionStart ?? input.value.length;
29626
+ const end = input.selectionEnd ?? start;
29627
+ event.preventDefault();
29628
+ input.setRangeText(".", start, end, "end");
29629
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, data: ".", inputType: "insertText" }));
29630
+ return true;
29631
+ }
29632
+
27961
29633
  function renderMessages(messages) {
27962
29634
  latestMessages = messages || [];
27963
29635
  cleanupLiveToolRunsForMessages(latestMessages);
@@ -28883,12 +30555,12 @@ function mergeMessagesDelta(previous, data) {
28883
30555
  return previous.slice(0, since).concat(data.messages);
28884
30556
  }
28885
30557
 
28886
- async function refreshMessages(tabContext = activeTabContext()) {
30558
+ async function refreshMessages(tabContext = activeTabContext(), { authoritative = false } = {}) {
28887
30559
  if (!tabContext.tabId) return;
28888
30560
  const previousMessages = latestMessages;
28889
30561
  const sessionKey = resolveMessagesSessionKey(tabContext.tabId);
28890
30562
  let nextMessages = null;
28891
- if (previousMessages.length > 1 && sessionKey === latestMessagesSessionKey) {
30563
+ if (!authoritative && previousMessages.length > 1 && sessionKey === latestMessagesSessionKey) {
28892
30564
  // Delta fetch with a one-message overlap: the last known message is
28893
30565
  // re-requested so retroactive changes are detected via mergeMessagesDelta.
28894
30566
  const response = await api(`/api/messages?since=${previousMessages.length - 1}`, { tabId: tabContext.tabId });
@@ -30313,10 +31985,32 @@ async function sendUserBashCommand(parsed, { usesPromptInput = false, targetTabI
30313
31985
  await runUserBashCommand(parsed, { usesPromptInput, targetTabId });
30314
31986
  }
30315
31987
 
31988
+ function clearPromptInputForRouting({ usesPromptInput, targetTabId, tabContext }) {
31989
+ if (!usesPromptInput) return;
31990
+ tabDrafts.set(targetTabId, "");
31991
+ if (!isCurrentTabContext(tabContext)) return;
31992
+ elements.promptInput.value = "";
31993
+ resizePromptInput();
31994
+ hideCommandSuggestions();
31995
+ }
31996
+
31997
+ function restorePromptInputAfterRoutingError(message, { usesPromptInput, targetTabId, tabContext }) {
31998
+ if (!usesPromptInput) return;
31999
+ if (isCurrentTabContext(tabContext)) {
32000
+ if (elements.promptInput.value) return;
32001
+ elements.promptInput.value = message;
32002
+ resizePromptInput();
32003
+ tabDrafts.set(targetTabId, message);
32004
+ return;
32005
+ }
32006
+ if (!tabDrafts.get(targetTabId)) tabDrafts.set(targetTabId, message);
32007
+ }
32008
+
30316
32009
  async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = activeTabId, throwOnError = false, streamingBehavior } = {}) {
30317
32010
  const usesPromptInput = explicitMessage === undefined;
30318
32011
  const rawMessage = usesPromptInput ? elements.promptInput.value : explicitMessage;
30319
- const originalMessage = String(rawMessage || "").trim();
32012
+ const inputMessage = String(rawMessage || "");
32013
+ const originalMessage = inputMessage.trim();
30320
32014
  if (!targetTabId) return;
30321
32015
  if (voiceConversationActiveFor(targetTabId)) voiceConversation.handleUserActivity();
30322
32016
  const tabContext = activeTabContext(targetTabId);
@@ -30334,12 +32028,17 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
30334
32028
  const targetWasBusy = targetWasStreaming || targetWasCompacting;
30335
32029
  const busyBehavior = normalizeBusyPromptBehavior(busyPromptBehavior);
30336
32030
  const startsRun = kind === "prompt" && !targetWasBusy;
32031
+ clearPromptInputForRouting({ usesPromptInput, targetTabId, tabContext });
30337
32032
  resumeChatAutoFollow();
30338
32033
  updateJumpToLatestButton();
30339
32034
  setComposerActionsOpen(false);
30340
32035
  if (startsRun) {
32036
+ promptRoutingTabs.add(targetTabId);
30341
32037
  markTabWorkingLocally(targetTabId);
30342
- setRunIndicatorActivity(attachments.length ? "Uploading attachments…" : "Sending prompt to Pi…");
32038
+ if (isCurrentTabContext(tabContext)) {
32039
+ appendOptimisticUserPrompt(originalMessage, attachments.length);
32040
+ setRunIndicatorActivity(attachments.length ? "Preparing attachments for routing…" : "Routing prompt to the selected agent…");
32041
+ }
30343
32042
  }
30344
32043
 
30345
32044
  let message = originalMessage;
@@ -30355,7 +32054,7 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
30355
32054
  rememberPromptHistory(message, { tabId: targetTabId });
30356
32055
  if (kind === "prompt") rememberLastUserPrompt(message, { tabId: targetTabId });
30357
32056
  }
30358
- if (startsRun && isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending prompt to Pi…");
32057
+ if (startsRun && isCurrentTabContext(tabContext)) setRunIndicatorActivity("Routing complete; starting agent…");
30359
32058
 
30360
32059
  let response;
30361
32060
  if (kind === "steer") {
@@ -30368,6 +32067,7 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
30368
32067
  response = await api("/api/prompt", { method: "POST", body, tabId: targetTabId });
30369
32068
  }
30370
32069
  applyResponseTab(response);
32070
+ if (startsRun) promptRoutingTabs.delete(targetTabId);
30371
32071
  if (response?.command === "native_slash_command" && /^\/new(?:\s|$)/.test(message)) forgetLastUserPrompt(targetTabId);
30372
32072
  const targetStillActive = isCurrentTabContext(tabContext);
30373
32073
  if (startsRun && response?.command === "native_slash_command") {
@@ -30384,15 +32084,7 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
30384
32084
  if (targetStillActive && response?.command === "native_slash_command") {
30385
32085
  applyNativeSlashCommandEffects(response, message, tabContext);
30386
32086
  }
30387
- if (usesPromptInput) {
30388
- clearAttachments(targetTabId);
30389
- if (targetStillActive) {
30390
- elements.promptInput.value = "";
30391
- resizePromptInput();
30392
- } else {
30393
- tabDrafts.set(targetTabId, "");
30394
- }
30395
- }
32087
+ if (usesPromptInput) clearAttachments(targetTabId);
30396
32088
  if (targetStillActive) {
30397
32089
  hideCommandSuggestions();
30398
32090
  if (response?.command !== "native_slash_command") scheduleRefreshState(120, tabContext);
@@ -30400,7 +32092,9 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
30400
32092
  scheduleRefreshTabs(300);
30401
32093
  }
30402
32094
  } catch (error) {
32095
+ restorePromptInputAfterRoutingError(inputMessage, { usesPromptInput, targetTabId, tabContext });
30403
32096
  if (startsRun) {
32097
+ promptRoutingTabs.delete(targetTabId);
30404
32098
  markTabIdleLocally(targetTabId);
30405
32099
  if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
30406
32100
  }
@@ -30451,9 +32145,18 @@ function handleExtensionUiRequest(request) {
30451
32145
  }
30452
32146
  if (request.statusText) {
30453
32147
  statusEntries.set(statusKey, request.statusText);
30454
- if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) cacheGitFooterWebuiPayload(request.statusText, request.tabId);
32148
+ if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) {
32149
+ const validPayload = !!parseGitFooterWebuiPayloadRaw(request.statusText);
32150
+ cacheGitFooterWebuiPayload(request.statusText, request.tabId);
32151
+ settleGitFooterPayload(
32152
+ request.tabId || activeTabId,
32153
+ validPayload ? "ready" : "failed",
32154
+ validPayload ? "" : "Git footer returned invalid status data — refresh to retry",
32155
+ );
32156
+ }
30455
32157
  } else {
30456
32158
  statusEntries.delete(statusKey);
32159
+ if (statusKey === GIT_FOOTER_WEBUI_STATUS_KEY) settleGitFooterPayload(request.tabId || activeTabId, "idle");
30457
32160
  }
30458
32161
  if (statusKey === STATS_WEBUI_STATUS_KEY) handleStatsWebuiStatus(request.statusText);
30459
32162
  if (statusKey === BTW_WEBUI_STATUS_KEY) handleBtwWebuiStatus(request.statusText);
@@ -30815,6 +32518,99 @@ function showNextDialog() {
30815
32518
  elements.dialog.showModal();
30816
32519
  }
30817
32520
 
32521
+ function supervisorEventEnvelope(event, fallbackTabId = activeTabId) {
32522
+ if (!event || typeof event !== "object") return null;
32523
+ const fields = ["supervisorScopeId", "supervisorEpoch", "supervisorSeq"];
32524
+ const present = fields.map((field) => Object.prototype.hasOwnProperty.call(event, field));
32525
+ if (!present.some(Boolean)) return null;
32526
+ const scopeId = String(event.supervisorScopeId || "").trim();
32527
+ const epoch = String(event.supervisorEpoch || "").trim();
32528
+ const tabId = String(event.tabId || fallbackTabId || "").trim();
32529
+ const sequenceText = present[2] ? String(event.supervisorSeq ?? "").trim() : null;
32530
+ const sequenceValid = sequenceText === null || /^(?:0|[1-9]\d*)$/.test(sequenceText);
32531
+ return {
32532
+ valid: present[0] && present[1] && scopeId.length > 0 && epoch.length > 0 && tabId.length > 0 && sequenceValid,
32533
+ scopeId,
32534
+ epoch,
32535
+ tabId,
32536
+ sequence: sequenceText === null || !sequenceValid ? null : BigInt(sequenceText),
32537
+ };
32538
+ }
32539
+
32540
+ function supervisorCursorKey(envelope) {
32541
+ return JSON.stringify([envelope.scopeId, envelope.tabId]);
32542
+ }
32543
+
32544
+ function acceptSupervisorEvent(event, fallbackTabId = activeTabId) {
32545
+ const envelope = supervisorEventEnvelope(event, fallbackTabId);
32546
+ if (!envelope) return true;
32547
+ if (!envelope.valid) {
32548
+ const warningKey = String(event?.type || "unknown");
32549
+ if (!supervisorEnvelopeWarnings.has(warningKey)) {
32550
+ supervisorEnvelopeWarnings.add(warningKey);
32551
+ addEvent(`ignored malformed supervisor event (${warningKey})`, "warn");
32552
+ }
32553
+ return false;
32554
+ }
32555
+
32556
+ const key = supervisorCursorKey(envelope);
32557
+ const cursor = supervisorEventCursors.get(key);
32558
+ if (!cursor) {
32559
+ supervisorEventCursors.set(key, { epoch: envelope.epoch, sequence: envelope.sequence });
32560
+ return true;
32561
+ }
32562
+
32563
+ if (cursor.epoch !== envelope.epoch) {
32564
+ const retired = supervisorRetiredEpochs.get(key) || new Set();
32565
+ if (retired.has(envelope.epoch)) return false;
32566
+ retired.add(cursor.epoch);
32567
+ supervisorRetiredEpochs.set(key, retired);
32568
+ supervisorEventCursors.set(key, { epoch: envelope.epoch, sequence: envelope.sequence });
32569
+ return true;
32570
+ }
32571
+
32572
+ if (envelope.sequence === null) return true;
32573
+ if (cursor.sequence !== null && envelope.sequence <= cursor.sequence) return false;
32574
+ cursor.sequence = envelope.sequence;
32575
+ return true;
32576
+ }
32577
+
32578
+ function supervisorContinuityKey(event, fallbackTabId = activeTabId) {
32579
+ const envelope = supervisorEventEnvelope(event, fallbackTabId);
32580
+ return envelope?.valid ? `${supervisorCursorKey(envelope)}|${envelope.epoch}` : "";
32581
+ }
32582
+
32583
+ function scheduleSupervisorContinuityRefresh(event, { gap = false } = {}) {
32584
+ const tabContext = activeTabContext(event?.tabId || activeTabId);
32585
+ const key = supervisorContinuityKey(event, tabContext.tabId);
32586
+ if (!key || !tabContext.tabId || !isCurrentTabContext(tabContext)) return;
32587
+
32588
+ if (gap && !supervisorGapWarnings.has(key)) {
32589
+ supervisorGapWarnings.add(key);
32590
+ addEvent("Buffered live output may be incomplete; refreshing tabs, state, and transcript from Pi.", "warn");
32591
+ }
32592
+ if (supervisorContinuityRefreshes.has(key)) return;
32593
+
32594
+ const timer = setTimeout(async () => {
32595
+ try {
32596
+ const results = await Promise.allSettled([refreshTabs()]);
32597
+ if (isCurrentTabContext(tabContext)) {
32598
+ results.push(...(await Promise.allSettled([
32599
+ refreshState(tabContext),
32600
+ refreshMessages(tabContext, { authoritative: true }),
32601
+ ])));
32602
+ }
32603
+ if (!isCurrentTabContext(tabContext)) return;
32604
+ for (const result of results) {
32605
+ if (result.status === "rejected") addEvent(`continuity refresh failed: ${result.reason?.message || String(result.reason)}`, "error");
32606
+ }
32607
+ } finally {
32608
+ supervisorContinuityRefreshes.delete(key);
32609
+ }
32610
+ }, 25);
32611
+ supervisorContinuityRefreshes.set(key, timer);
32612
+ }
32613
+
30818
32614
  function handleInactiveTabEvent(event) {
30819
32615
  if (event.type === "extension_ui_request" && EXTENSION_UI_BLOCKING_METHODS.has(event.method)) {
30820
32616
  if (!event.replayed) notifyBlockedTab(event.tabId, { request: event, count: event.pendingExtensionUiRequestCount });
@@ -30838,7 +32634,7 @@ function handleInactiveTabEvent(event) {
30838
32634
  setWidgetForTab(event.tabId, AUR_REVIEW_RPC_WIDGET_KEY, event);
30839
32635
  updateOptionalFeatureAvailability();
30840
32636
  renderTabs();
30841
- } else if (event.type === "agent_end") {
32637
+ } else if (event.type === "agent_settled") {
30842
32638
  notifyAgentDone(event.tabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
30843
32639
  }
30844
32640
  }
@@ -30867,9 +32663,17 @@ function handleEvent(event) {
30867
32663
  renderWidgets();
30868
32664
  }
30869
32665
  addEvent(`connected to ${event.tabTitle || "terminal"} for ${event.cwd}`);
32666
+ if (event.supervisorReplayGap === true) scheduleSupervisorContinuityRefresh(event, { gap: true });
30870
32667
  scheduleForegroundReconcile("event stream reconnect", 0);
30871
32668
  break;
30872
32669
  }
32670
+ case "webui_supervisor_reconnected":
32671
+ addEvent("reconnected to the running Pi session");
32672
+ scheduleSupervisorContinuityRefresh(event);
32673
+ break;
32674
+ case "webui_supervisor_replay_gap":
32675
+ scheduleSupervisorContinuityRefresh(event, { gap: true });
32676
+ break;
30873
32677
  case "webui_output_mode":
30874
32678
  applyOutputModeControl(event, tabContext);
30875
32679
  break;
@@ -31012,6 +32816,7 @@ function handleEvent(event) {
31012
32816
  break;
31013
32817
  case "agent_start":
31014
32818
  assistantErrorSurfacedThisRun = false;
32819
+ markTabWorkingLocally(event.tabId || activeTabId, { runStarted: true });
31015
32820
  if (currentState) currentState = { ...currentState, isStreaming: true };
31016
32821
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ streaming: true });
31017
32822
  setRunIndicatorActivity("Agent run started; waiting for first output or action…");
@@ -31030,34 +32835,11 @@ function handleEvent(event) {
31030
32835
  assistantErrorSurfacedThisRun = true;
31031
32836
  }
31032
32837
  }
31033
- addEvent("agent finished");
31034
- notifyAgentDone(event.tabId || activeTabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
31035
- clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
31036
- if (currentState) currentState = { ...currentState, isStreaming: false };
31037
- // handleAssistantTurnEnd resets the controller's streaming/tool flags and
31038
- // flushes queued interruptions itself; calling setAssistantActivity here
31039
- // first would flush the queue and then speak the interrupted answer.
31040
- if (voiceConversationActiveFor(event.tabId || activeTabId)) void handleVoiceConversationTurnEnd(tabContext);
31041
- clearRunIndicatorActivity();
31042
- markTabOutputSeen();
31043
- requestGitFooterWebuiPayload(tabContext, { force: true });
31044
- scheduleRefreshState();
32838
+ addEvent("agent run ended; waiting for settlement");
32839
+ if (runIndicatorIsActive()) setRunIndicatorActivity("Agent run ended; checking for retry or continuation…", { scroll: false });
31045
32840
  scheduleRefreshMessages();
32841
+ scheduleRefreshState();
31046
32842
  scheduleRefreshFooter();
31047
- scheduleRefreshCodexUsage(2200);
31048
- scheduleRefreshClaudeUsage(2200);
31049
- renderFeedbackTray();
31050
- {
31051
- const workflowTabId = event.tabId || activeTabId;
31052
- const workflow = gitWorkflowForTab(workflowTabId, { create: false });
31053
- if (workflow?.active && workflow.step === "generating") {
31054
- loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
31055
- } else if (workflow?.active && workflow.step === "branchNaming") {
31056
- loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
31057
- } else if (workflow?.active && workflow.step === "prGenerating") {
31058
- loadGitWorkflowPr({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
31059
- }
31060
- }
31061
32843
  break;
31062
32844
  case "message_start":
31063
32845
  if (event.message?.role === "assistant") {
@@ -31143,6 +32925,35 @@ function handleEvent(event) {
31143
32925
  break;
31144
32926
  case "agent_settled":
31145
32927
  if (compactOutputActive()) finishCompactLiveOutput(tabContext);
32928
+ streamMessageActive = false;
32929
+ addEvent("agent finished");
32930
+ notifyAgentDone(event.tabId || activeTabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
32931
+ clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
32932
+ if (currentState) currentState = { ...currentState, isStreaming: false };
32933
+ // handleAssistantTurnEnd resets the controller's streaming/tool flags and
32934
+ // flushes queued interruptions itself; calling setAssistantActivity here
32935
+ // first would flush the queue and then speak the interrupted answer.
32936
+ if (voiceConversationActiveFor(event.tabId || activeTabId)) void handleVoiceConversationTurnEnd(tabContext);
32937
+ clearRunIndicatorActivity();
32938
+ markTabOutputSeen();
32939
+ requestGitFooterWebuiPayload(tabContext, { force: true });
32940
+ scheduleRefreshState();
32941
+ scheduleRefreshMessages();
32942
+ scheduleRefreshFooter();
32943
+ scheduleRefreshCodexUsage(2200);
32944
+ scheduleRefreshClaudeUsage(2200);
32945
+ renderFeedbackTray();
32946
+ {
32947
+ const workflowTabId = event.tabId || activeTabId;
32948
+ const workflow = gitWorkflowForTab(workflowTabId, { create: false });
32949
+ if (workflow?.active && workflow.step === "generating") {
32950
+ loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
32951
+ } else if (workflow?.active && workflow.step === "branchNaming") {
32952
+ loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
32953
+ } else if (workflow?.active && workflow.step === "prGenerating") {
32954
+ loadGitWorkflowPr({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
32955
+ }
32956
+ }
31146
32957
  break;
31147
32958
  case "auto_retry_start": {
31148
32959
  const seconds = Math.max(0, Math.ceil(Number(event.delayMs || 0) / 1000));
@@ -31219,7 +33030,9 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
31219
33030
  source.onmessage = (message) => {
31220
33031
  if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
31221
33032
  try {
31222
- handleEvent(JSON.parse(message.data));
33033
+ const event = JSON.parse(message.data);
33034
+ if (!acceptSupervisorEvent(event, tabContext.tabId)) return;
33035
+ handleEvent(event);
31223
33036
  } catch (error) {
31224
33037
  if (isCurrentTabContext(tabContext)) addEvent(error.message, "error");
31225
33038
  }
@@ -31553,6 +33366,7 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
31553
33366
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
31554
33367
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
31555
33368
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
33369
+ elements.optionsWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/workflow-setup"));
31556
33370
  elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
31557
33371
  elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
31558
33372
  elements.optionsExportButton.addEventListener("click", () => runNativeCommandMenu("/export"));
@@ -32595,6 +34409,7 @@ elements.fileViewerResizeHandle?.addEventListener("pointerdown", beginFileViewer
32595
34409
  elements.fileViewerResizeHandle?.addEventListener("keydown", handleFileViewerResizeKeydown);
32596
34410
  elements.fileViewerSaveButton?.addEventListener("click", () => saveActiveFileViewer());
32597
34411
  elements.fileViewerCloseButton?.addEventListener("click", closeFileViewer);
34412
+ elements.fileViewerChangesModeButton?.addEventListener("click", () => setFileViewerMode("changes"));
32598
34413
  elements.fileViewerSourceModeButton?.addEventListener("click", () => setFileViewerMode("source"));
32599
34414
  elements.fileViewerPreviewModeButton?.addEventListener("click", () => setFileViewerMode("preview"));
32600
34415
  elements.fileViewerEditor?.addEventListener("input", () => {
@@ -32663,7 +34478,7 @@ elements.composer.addEventListener("dragleave", handleComposerDragLeave);
32663
34478
  elements.composer.addEventListener("drop", handleComposerDrop);
32664
34479
 
32665
34480
  elements.promptInput.addEventListener("keydown", (event) => {
32666
- if (event.defaultPrevented) return;
34481
+ if (event.defaultPrevented || insertNumpadDecimal(event)) return;
32667
34482
  if (shouldSendPromptFromEnter(event)) {
32668
34483
  event.preventDefault();
32669
34484
  hideCommandSuggestions();
@@ -32730,6 +34545,7 @@ elements.promptInput.addEventListener("blur", () => {
32730
34545
  });
32731
34546
 
32732
34547
  installModalPrimitives();
34548
+ initializeIssueWizard();
32733
34549
  resizePromptInput();
32734
34550
  restoreSidePanelWidthPreference();
32735
34551
  restoreFileViewerWidthPreference();